text
stringlengths
180
608k
[Question] [ **This question already has answers here**: [Largest Number Printable](/questions/18028/largest-number-printable) (93 answers) Closed 7 years ago. ## Introduction I found a really interesting puzzle it was called [Busy Brain Beaver](https://codegolf.stackexchange.com/questions/4813/busy-brain-beaver?newreg=5e5f4ab790c044019295fe253a9bfcc1#). But it has been 3 years since the latest activity and there are some things I didn't like about it. So I decided to make a new one. ## The Rules I want this one to be more brainfuck focused: * Your goal is to make a brainfuck program that outputs the biggest number. * It has to output that number in finite time so you can't say `+[+].` outputs infinity (it doesn't have to terminate ex: `+.[+]` is OK) * Your program can only be 500 useful characters(non-brainfuck characters don't count) * You can assume `.` outputs your number (in decimal notation). * Only the first output counts (so you can't say `+[+.]` outputs infinity) * You can't ask for input so `,` is ignored * This takes place in a special brainfuck environment: + There are an infinite amount of cell to the left and to the right. + All cells start at 0 + All cells can hold **any** integer (so `-` at 0 becomes -1) * Give an approximation (lower bound) for which number your program would output (given an arbitrarily finite time) (if you are using a special notation please say which one or provide a link) * An explanation of your algorithm would be appreciated. (posting the formatted and commented version will be appreciated too) ### Not a duplicate It was marked as a possible duplicate of [Largest Number Printable](https://codegolf.stackexchange.com/questions/18028/largest-number-printable) I think this is different because: * This question is brainfuck focused. And in largest number printable brainfuck isn't even allowed. Yes they are both a busy beaver. But if you think these two are duplicates then any two busy beavers are duplicates. The difference between a brainfuck contest and a non-brainfuck contest is really big. And before it got closed people seemed to have a lot of interest in this one. * The goal here is to output a long number not a lot of bytes ## Leader Board (top 10) 1. Gabriel Benamy 2↑↑↑411 2. Mike Bufardeci 4277772 = 163\*(162\*162) 3. fejfo 60762 = 246\*247 [Answer] # 22222222... (65536 twos) = [2↑↑↑4](https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation) Before I begin, this is not the largest number expressible using 500 bytes of New Brainfuck. It's simply where I gave up trying to wrap my head around how big the numbers were getting. **This answer only uses 93 bytes** and is therefore not the largest number, but it's proof of concept that mind-bogglingly large numbers are possible. ``` +++[->++[->+>+<<]>>[-<<+>>]+<[->[-<<[->>>+>+<<<<]>>>>[-<<<<+>>>>]<<]>[-<+>]<<]>[-<+>]<<<]>>. ``` This is a modification of the exponentiation algorithm in Brainfuck. This number is so large, it's almost impossible to describe in human terms. It isn't sufficient to say "the number has this many digits" because it has more digits than particles in the universe. In fact, the number of digits this number contains has more digits than the number of particles in the universe. Let this number be x, and let `f(0) = x`. Recursively define `f(n) = floor[log10[f(n-1)]]`. The first *n* which is smaller than 1 googol is over 10,000. This answer is 93 bytes. If we removed removed a single leading `+`, the result would be `65536` = 2222. Removing another `+` gives us 4. This means that if we add another +, we would get a number tower with 2↑↑↑4 twos, which would be 2↑↑↑5. That answer would be 94 bytes. If I were to add another 406 plus signs to this, we would get 2↑↑↑411, which is mind-bogglingly big. Instead, if I were to add yet another outer loop, I could probably get something close to 2↑↑↑↑380. For the record, 2↑↑↑↑3 = 2↑↑↑4, and 2↑↑↑↑4 dwarfs 2↑↑↑4 much the same way that 2↑↑↑4 dwarfs 65536. In fact, it may just be possible to actually get close to Graham's Number using 500 bytes of brainfuck. [Answer] # 4277772 = 163\*(162\*162) ``` +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<-]<-]>>. ``` As a reaction to the [60762 solution](https://codegolf.stackexchange.com/a/103725/41863) this is another simple solution. Here we multiply just like that answer but inside of another loop. I am somewhat concerned that I am interpreting this nested loop incorrectly but I think that this is correct and the output would be 4,277,772. The loop looks like the code below except the first `+` is replaced with 163 `+`s and the other two `+`s are replaced with 162 `+`s: ``` +[>+[>+<-]<-]>>. ``` [Answer] # 499 ``` +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++. ``` The naive approach, increments the starting cell 499 times before outputting that cell and terminating. I would submit a more complex answer, but there are no online testbeds for this variant of brainfuck and I do not want to post an answer that doesn't work. [Answer] # 60762 = 246\*247 As a reaction on the 499 solution I will do an other very simple solution it just multiplies 2 numbers ``` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<-]>. ``` how it works is pretty self explanatory it uses the standard multiplication loop ++[>+++<-]>. would be 2\*3 = 6 ]
[Question] [ **Input:** A single word as a string (matches `[a-zA-Z]+`). If the input doesn't follow these guidelines, print "Error" (but no error should be thrown) **Output:** The NATO pronunciation of the word. Print out a space separated list of the NATO word that matches each letter of the input word. Trailing white space is acceptable. **Restrictions:** Your source code must contain each ASCII character from 32 (space) to 126 (tilde) **in that order**, excluding numbers and letters. You may have anything you like mingled in between the required characters, but the required characters must be there and in order. (If `ABC` were the required characters, `YA8iBC3` or `C6ABn#C` would be valid, but `A7CRT` or `8mdB9AC` would not be). Standard loopholes and built-ins for generating the NATO pronunciation are not allowed. **References:** The NATO pronunciation is as follows: ***A***lpha **B**ravo **C**harlie **D**elta **E**cho **F**oxtrot **G**olf **H**otel **I**ndia **J**uliet **K**ilo **L**ima **M**ike **N**ovember **O**scar **P**apa **Q**uebec **R**omeo **S**ierra **T**ango **U**niform **V**ictor **W**hiskey **X**ray **Y**ankee **Z**ulu. The required symbols (in order) are as follows: `!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~` **Test cases:** (The quotation marks won't be part of input, but are included to show whitespace) ``` "a" => Alpha "Z" => Zulu "twig" => Tango Whiskey India Golf "PPCG" => Papa Papa Charlie Golf "camelCase" => Charlie Alpha Mike Echo Lima Charlie Alpha Sierra Echo "Quebec" => Quebec Uniform Echo Bravo Echo Charlie "" => Error " " => Error "()" => Error "twig " => Error " PPCG" => Error "one+two" => Error "Queen bee" => Error ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in your favorite language wins! [Answer] # JavaScript (ES6), 268 An anonymous function ``` i=>[...i].every(c=>(c=parseInt(c,36))>9?o+="AlphaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu".match(/[A-Z][^A-Z]+/g)[c-10]+' ':0,o='',!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~")?o:'Error' ``` [Answer] # Ruby, 343 bytes ``` puts gets.chop.chars.map!{|c|"AlphaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu"[/#{c.upcase}[a-z]+/]||$$%0&0}*' 'rescue(puts"Error")#*+,-./:;<=>?@[\]^_`{|}~ ``` Tried incorporating as many of the required characters as possible, but after a while it was shorter to just put them in a comment at the end. For readability, here's the non-comment part with the long string taken out: ``` puts gets.chop.chars.map!{|c|"AlphaBravo..."[/#{c.upcase}[a-z]+/]||$$%0&0}*' 'rescue(puts"Error") ``` That's a space and all the characters `!"#$%&'()` in the right order without comments [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~151~~ ~~150~~ ~~146~~ ~~145~~ ~~143~~ 135 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` !áмg_ilA”¤±Ð†vo¼¯¤œ®È¨›trotŠˆƒ‹Š™ÈŸt Kilo´àma—……ÍЗŽêpa¼°«Äoµ†Çâgo¸šÉµ Whiskey Xrayµ‹nkeeâ¸lu”#ð«‡ë”‰ë”q"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ ``` -8 bytes implicitly thanks to [*@ErikTheGolfer*'s comment here](https://codegolf.stackexchange.com/questions/112208/charlie-oscar-delta-echo?noredirect=1&lq=1#comment273386_112221) for a better compressed string (only difference is `Alpha` vs `Alfa`). [Try it online](https://tio.run/##yy9OTMpM/f9f8fDCC3vS4zNzHB81zD205NDGwxMeNSwoyz@059D6Q0uOTj607nDHoRWPGnaVFOWXHF1wuu3YpEcNO48ueNSy6HDH0R0lCt6ZOfmHthxekJv4qGHKo4ZlQHS4F2TIlKN7D68qSAQatOHQ6sMt@Ye2Ag0@3H54UXr@oR1HFx7uPLRVITwjszg7tVIhoiixEiS/My87NfXwokM7ckqBzlE@DNT5qGHhYSAx91HDBjBdqKSsoqqmrqGppa2jq6dvZW1ja2fvEB0TGxefUF1TW/f/f0l4pjsA) or [verify all test cases](https://tio.run/##HY5NSwJRFIb391fcxj407Qt3fVm4aNHGVkVZdpWLDY7e0FEZ0rgLMVsEYm6FUSSioAwSNGxzDtOmTb/h/pFpFA7vWTznfTiiwJI6dyslK6JRVW9RLWJh053D7t8kndCNfSU70IcPbCpplwRM4B36ziO8YQOelfwy88J07N/6T0vJsWOrWg8bzsikh7oh4BPtLFOyreSTN/gwlbSdb3y5Zp5oAK9YEzD0xHiHvbSAkdPFexjS4yu9kOEWPckza8rHuQzn2IORUfTe8aHXVLKLXnSUHMy25ptfWFzyB5aDoZXVtc2t7Z3dyN5Z/PwicXlTqd5qcbcachk5JWZZT5NYLHpAUizLjSgrcHJU5EmeIpT4AzNOCZ1diBwPmmUx5TxHk5yTcDhM1snGPw). **Explanation:** ``` ! # Take the factorial of the (implicit) input # (This will leave the input-string unchanged if it isn't an integer) áм # Remove all letters g_i # If the length of the remainder is 0: l # Make the (implicit) input lowercase A # Push the lowercase alphabet ”¤±Ð†vo¼¯¤œ®È¨›trotŠˆƒ‹Š™ÈŸt Kilo´àma—……ÍЗŽêpa¼°«Äoµ†Çâgo¸šÉµ Whiskey Xrayµ‹nkeeâ¸lu” # Push string "Alpha Bravo Charlie ... Yankee Xray Zulu" # # Split the string by spaces: # ["Alpha","Bravo","Charlie",...,"Yankee","Xray","Zulu"] ð« # Append each with a space: # ["Alpha ","Bravo ","Charlie ",...,"Yankee ","Xray ","Zulu "] ‡ # Transliterate; map all letters in the lowercase input with this # list at the same indices (and output the result implicitly) ë # Else: ”‰ë” # Push the dictionary word "Error" q # Stop the program (and output the "Error" at the top of the stack implicitly) "#$%&'()*+,-./:;<=>?@[\]^_`{|}~ "# Push the string "#$%&'()*+,-./:;<=>?@[\]^_`{|}~", # which is a no-op since the program has already stopped ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `”¤±Ð†vo¼¯¤œ®È¨›trotŠˆƒ‹Š™ÈŸt Kilo´àma—……ÍЗŽêpa¼°«Äoµ†Çâgo¸šÉµ Whiskey Xrayµ‹nkeeâ¸lu”` is `"Alpha Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliet Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform Victor Whiskey Xray Yankee Zulu"` and `”‰ë”` is `"Error"`. [Answer] # CJam, 173 bytes ``` qeu:M'[,65>:L- !{M'Af-L"{;ege& \@IQ#5~wUNxuznY_E+TLsBTC9\$8 ]%9b Y9&G~|Yedz9?7pLD&&6PNg[vXY4D}Q"127b26b'`f+'`/.+f=S*}"Error"?e#()*+,-./:;<=>?@[\]^_`{|}~ ``` Contains lots of unprintable characters. [Try it out here.](http://cjam.aditsu.net/#code=qeu%3AM'%5B%2C65%3E%3AL-%20!%7BM'Af-L%22%7B%3B%12e%12%0F%18ge%26%19%20%5C%40IQ%235~%1C%18wU%1ENxuz%15nY%07_E%2BTLsB%04%1DTC9%5C%248%0A%05%5D%259b%09Y9%01%26G~%7CY%13%1Be%14dz%039%3F7pLD%26%266PNg%5BvXY%17%1F4D%7D%15Q%22127b26b'%60f%2B'%60%2F.%2Bf%3DS*%7D%22Error%22%3Fe%23()*%2B%2C-.%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E_%60%7B%7C%7D~&input=camelCase) [Answer] # PHP, 268 bytes Same byte count as the [JavaScript answer](https://codegolf.stackexchange.com/a/67932/41859). :) I couldn't find a byte-saving way around the "penalty" of adding the special char string as is: ``` for(;$c=ucfirst($argv[1][$i++]);"!\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~")preg_match("/{$c}[a-z]+/",AlphaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu,$m)?$o.="$m[0] ":die(Error);echo$o; ``` Takes an input from command line, like: ``` $ php tango.php Word ``` --- **Ungolfed** ``` for(;$c=ucfirst($argv[1][$i++]);"!\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~") preg_match("/{$c}[a-z]+/",AlphaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu,$m) ? $o.="$m[0] " : die(Error); echo$o; ``` [Answer] # x86 machine code, IBM PC DOS, 274 bytes ``` a080 0032 e4fe c8be 8100 03f0 8bc8 8bd8 b805 008e c0fd ac24 dfbf 0800 51b1 a4fc f2ae 5975 064f 57e2 eceb 07ba af00 52bb 0100 8cc0 8ed8 b409 8bcb 5acd 21ba b400 cd21 e2f6 b44c cd21 416c 7068 6124 4272 6176 6f24 4368 6172 6c69 6524 4465 6c74 6124 4563 686f 2446 6f78 7472 6f74 2447 6f6c 6624 486f 7465 6c24 496e 6469 6124 4a75 6c69 6574 244b 696c 6f24 4c69 6d61 244d 696b 6524 4e6f 7665 6d62 6572 244f 7363 6172 2450 6170 6124 5175 6562 6563 2452 6f6d 656f 2453 6965 7272 6124 5461 6e67 6f24 556e 6966 6f72 6d24 5669 6374 6f72 2457 6869 736b 6579 2458 7261 7924 5961 6e6b 6565 245a 756c 7524 2122 2345 7272 6f72 2024 2526 2728 292a 2b2c 2d2e 2f3a 3b3c 3d3e 3f40 5b5c 5d5e 5f60 7b7c 7d7e ``` Ungolfed: ``` .DATA NATO DB 'Alpha$Bravo$Charlie$Delta$Echo$Foxtrot$Golf$Hotel$India$' DB 'Juliet$Kilo$Lima$Mike$November$Oscar$Papa$Quebec$Romeo$' DB 'Sierra$Tango$Uniform$Victor$Whiskey$Xray$Yankee$Zulu$' LNATO EQU $-NATO DB '!"#' ; required string part 1 ERRSTR DB 'Error' ; Error string SEPSTR DB ' $' ; word separator string DB '%&',"'()*+,-./:;<=>?@[\]^_`{|}~" ; required string part 2 .CODE MOV AL, DS:[80H] ; DS:80H is length of input string from command line XOR AH, AH ; clear AH DEC AL ; command line arg length includes preceeding space MOV SI, 81H ; look in DS:82H-1 for start of string ADD SI, AX ; start at end of string MOV CX, AX ; search length of input string MOV BX, AX ; BL is length of input to search MOV AX, @DATA ; Initialize ES to CODE segment MOV ES, AX ; align ES pointer (leave DS pointing to PSP) SEARCH: STD ; set dir flag (search backwards) LODSB ; load next char from DS:SI into AL, advance SI AND AL, 0DFH ; uppercase the input letter MOV DI, OFFSET NATO ; re-point SCASB to beginning of word data PUSH CX ; save outer loop position MOV CL, LNATO ; CL = length of NATO word data CLD ; clear dir flag (search forward) REPNE SCASB ; search until key in AL is found ES:DI, advance DI POP CX ; restore outer loop counter JNZ SHORT ERROR ; if REPNE ends without ZF, no value was found DEC DI ; un-advance DI to start of found string PUSH DI ; save position for later output LOOP SEARCH JMP SHORT OUTPUT ERROR: MOV DX, OFFSET ERRSTR ; error string PUSH DX ; push to top of stack MOV BX, 1 ; only output this one below OUTPUT: MOV AX, ES ; get data segment from ES MOV DS, AX ; point DS for DOS API string output MOV AH, 09H ; display string function MOV CX, BX ; loop for number of input letters OUT_LOOP: POP DX ; get pointer to next word from stack INT 21H MOV DX, OFFSET SEPSTR ; display a space between words INT 21H LOOP OUT_LOOP EXIT: MOV AH, 4CH ; exit to DOS INT 21H ``` Reads input from command line, displays output to console. Implementation notes: In order to prevent any otherwise valid words from being displayed before the Error string, the searching and screen output are separate. The input string is searched end to beginning since the stack (LIFO) is used to hold the output words (otherwise they'd be displayed in reverse). Output: ``` A>SYMLET a Alpha A>SYMLET Z Zulu A>SYMLET twig Tango Whiskey India Golf A>SYMLET PPCG Papa Papa Charlie Golf A>SYMLET camelCase Charlie Alpha Mike Echo Lima Charlie Alpha Sierra Echo A>SYMLET Quebec Quebec Uniform Echo Bravo Echo Charlie A>SYMLET Error A>SYMLET " " Error A>SYMLET () Error A>SYMLET "twig " Error A>SYMLET PPCG Error A>SYMLET one+two Error A>SYMLET Queen bee Error ``` [Answer] # Japt, 188 bytes The compressed string is littered with unprintables, so I've replaced each with a `¿`. [Try it online!](http://ethproductions.github.io/japt?v=master&code=Vj1VbUBgQWxwlUKfdm9DlXKmZURlbHRhRa5vRm94yZVHb2xmSMdVSZhpYUqqaWV0S2lsb0yLYU1pa2VOb3ZlbbxyT3OvclBhcGFRdWW8Y1JvtG9TaYCfVGFuZ29Vbmlmjm1WxaFyV5Zza2V5WJ95WYRrZWVaqnVgZlh1ICsiW2Etel0rIiArU307IVVmIlsgISMkJSYnKCkqKywtLi86Ozw9Pj9AW1xcXV5fYFx7fH1+XSIgP1Y6YEVynnI=&input=IlBQQ0ci) ``` V=Um@`Alp¿B¿voC¿r¦eDeltaE®oFoxÉ¿GolfHÇUI¿iaJªietKiloL¿aMikeNovem¼rOs¯rPapaQue¼cRo´oSi¿¿TangoUnif¿mVÅ¡rW¿skeyX¿yY¿keeZªu`fXu +"[a-z]+" +S};!Uf"[ !#$%&'()*+,-./:;<=>?@[\\]^_`\{|}~]" ?V:`Er¿r ^ ^ ^ ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^ ``` The top line is the actual code; the bottom line points out each of the required characters. I was lucky to find a way to put every one of them to good use, especially the backslash, which would have been needed there even if it was not required. I could save four bytes by using JS's `atob` to compress the string, instead of Japt's built-in `Oc`, but the transpiler inserts an extra parenthesis due to [this bug](https://github.com/ETHproductions/Japt/issues/11). ``` V=Um@ }; // Set variable V to: map each character X in U to: `...`f // Take the long string, decompress it, and match: Xu +"[a-z]+" // the uppercase version of X, followed by multiple lowercase letters. +S // Take the resulting match and add a space. // All this results with "Alpha Bravo Charlie" for an input of "Abc", or // "Alpha Bravo null" for something like "Ab!". Uf"..." // Match any of the characters in this string in the input. ! ? // If the result is null (none were matched): V // output V. :"Error // Otherwise, output "Error". ``` [Answer] # Python ~~279~~ 276 bytes It would have been much shorter than the odd requirement. **EDIT**: I just learned that s.split(' ')==s.split() ``` #!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ x=raw_input().lower();a='' l="Alpha Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliet Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform Victor Whiskey Xray Yankee Zulu".split() for i in x: a+=l[ord(i)-97]+' ' print a ``` I commented out the requirement. I used ord() to find the index position of the letter in l. [Try it here!](http://ideone.com/tnckSE) ]
[Question] [ I'm looking for some solution in returning values in main function, I need to shorten my program more, `return 0` takes too much characters of my code, I need to return 0, or my code fails. I know that in C there can be no `return` statement, and then program will use result of last operation - but on which operations I can 'really' shorten my code? At the moment I found `brk(0)` as shortest return. ``` main(n){while(~scanf("%i",&n))printf("%i ",n*~n/-2);brk(0);} ``` [Answer] You don't need to do anything. This assumption: > > then program will use result of last operation > > > is erroneous. If there is no `return` statement, `main` returns 0. It is *not* dependent on whatever might be left over in registers or anything like that. From the [standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf): > > **5.1.2.2.3 Program termination** > > > If the return type of the `main` function is a type compatible with `int`, a return from the initial call to the `main` function is equivalent to calling the `exit` function with the value returned by the `main` function as its argument; reaching the `}` that terminates the `main` function **returns a value of 0.** If the return type is not compatible with `int`, the termination status returned to the host environment is unspecified. > > > (emphasis mine) Your program's `main` already returns zero, or something is wrong somewhere else. [Answer] To be precise, the return value is generally dependent not on any previous "operation", but on the return value of the last function call. You are hoping that the function dumps a 0 into the EAX register, and that it stays there when `main` returns. You may be able to get better mileage out of `atoi`/`atol` and `gets` here. When `gets` hits EOF without reading a line, it returns a null pointer. Then, `atol` will return 0 upon receiving a null pointer as input. Since 0 is not an allowed value for `n`, this can be used as the loop condition, as well as the way to drop 0 into the appropriate register. ``` main(n){while(n=atol(gets(??????)))printf("%i ",n*~n/-2);} ``` The only problem is to find some memory for `gets` to write on. I'm not familiar with the Unix-specific library functions such as `brk`, but surely you can find something 6 characters or less (needed for an overall shortening) which returns `char*` or `void*` among all the cruft. ]
[Question] [ We have a group of stealthy computer-savvy geeks who are also musicians with a very subversive element to their songs that the authorities in their totalitarian country just can't stand, and are itching to show up at one of the concerts, fire off rubber bullets and tear gas at the audience, and arrest the band members and as may other fans as their paddy vans can carry and "disappear" them. However, the authorities are a bit slow to act, and will only show up to the *second* concert held under the same band name (case, accent and whitespace-length insensitive). They are also not very tech-savvy, so can't reverse-engineer the decoder (see later). Since they are working from memory, they'll forget a name after five years, so a repeat after that time won't attract their attention. One of these tech-savvy band members comes up with an algorithm that - given the date of a concert - generates a (hopefully) unique cool-sounding and pronounceable band name using the latin alphabet (A-Z) plus Space. They also create a *decoder* that they distribute to fans, which, given a band name and a date, returns some output indicating that this is indeed a code-generated name of our subversive band, or some other output indicating that the band name entered is that of some other band (or a sting set up by the authorities to catch fans they want to arrest). The decoder does not output any valid names, as the authorities are just tech-savvy enough themselves to obtain a copy and use that to generate possible names if it can output them, but don't have time to check all the names of the hundreds of other bands that appear and disappear (sometimes with their assistance) from time to time against it. **Your Task:** Produce these two complementary pieces of code - the name generator and the name checker. As this is a popularity contest, we're looking for cool-sounding, pronounceable band names for the English-speaking world, not random unpronounceable text. Any programming language is OK, as the fans are all very tech-savvy like us. Please provide a sample of the cool names your generator generates. If it can be shown that an algorithm produces a duplicate for any two dates in a 5-calendar-year period, then that will be considered a disqualification. (Disqualification is a far better fate than what the authorities would do to them). [Answer] # Pyth Encoder: ``` Jf-\'T'jdm@JdjswlJ ``` Takes two arguments: a dictionary on one line, and the date, in DDMMYYYY form on the next. Filters out words with apostrophes from the dictionary, then converts the current date into a number with base equal to the dictionary length, and then chooses words from the filtered dictionary with indexes of the digits, and prints them out, space separated. Today's result: ``` $ pyth -c "Jf-\'T'jdm@JdjswlJ" <<< '/usr/share/dict/words 30102014' Annam pals ``` Future results: ``` 31102014 Antarctica economical 01112014 Abernathy carousels 02112014 Acadia unsnarled 03112014 Actaeon oversimplifying 04112014 Adela dugouts 0511204 Adolph Maude ``` To decode, run the date through the program and see if the output matches the name given. I'm not going to list any more band names, but from how the program works it should be clear there are no repeats. [Answer] ### Encoder ``` {18+65}% ``` Expects input in the form `YYYYMMDD`. [Online demo](http://golfscript.apphb.com/?c=OycyMDE0MTAzMScKCnsxOCs2NX0l) ### Decoder ``` n/~{18+65}%= ``` Expects input in the form ``` BANDNAME YYYYMMDD ``` [Online demo](http://golfscript.apphb.com/?c=OydEQUJBQ0FGQUNBQkFFQUNBCjIwMTQxMDMxJwoKbi9%2BezE4KzY1fSU9) I'm not going to post a list of 260 names because a) that would be a complete waste of space; b) it's easy to convince yourself that the encoder is an injection. [Answer] # Python 3 ## Generator This generates shorter names so they seem a little less obscure. ``` import string date = input() vowels = 'aeiou' name = '' consonants = ''.join(i for i in string.ascii_lowercase if not i in vowels) for i in range(0,len(date),2): name += vowels[int(date[i])%len(vowels)]+consonants[int(date[i])%len(consonants)] print(name) ``` ### Example ``` Input: 30102014 Output: ofecidec ``` ## Validator Just performs the above and compares the result with the supplied name. ``` import string date, name = input().split(',') vowels = 'aeiou' tname = '' consonants = ''.join(i for i in string.ascii_lowercase if not i in vowels) for i in range(0,len(date),2): tname += vowels[int(date[i])%len(vowels)]+consonants[int(date[i])%len(consonants)] print(tname == name) ``` ### Examples ``` Input: 30102014,ofecidec Output: True Input: 30102014,ofocidoc Output: False ``` Input should be in the format: ``` DDMMYYYY,NAME ``` [Answer] # Javascript Since the authorities forget names after 5 years, we can leave the millennium, century, and decade digits out of the year. We can also use day of year (DoY). This program accepts input in the form of YDoY ## Encoder The encoder converts the base 10 date to a base 26 string, then shifts it over 10 characters to remove any numbers. Then we add vowels, spaces, and capitalization to make the words look like english. ``` function encodeName(date){ var alphabet = '0123456789abcdefghijklmnopqrstuvwxyz'; var vowels = 'aeiou'; var rebased = date.toString(26); var shifted = ''; var name = ''; for(var c in rebased){ var i = alphabet.indexOf(rebased[c]); shifted += alphabet.substring(i+10, i+11) } for(var a in shifted) name += a%2 == 0 ? shifted[a].toUpperCase() + vowels[a%vowels.length] : shifted[a] + ' '; return name.trim(); } ``` ## Decoder ``` function decodeName(name){ var alphabet = '0123456789abcdefghijklmnopqrstuvwxyz'; var vowels = 'aeiou'; var stripped = ''; var shifted = ''; for(var n in name) stripped += vowels.indexOf(name[n]) >= 0 || name[n] == ' ' ? '' : name[n].toLowerCase(); for(var n in stripped) shifted += alphabet[alphabet.indexOf(stripped[n])-10]; return parseInt(shifted, 26); } ``` ## Examples ``` function encodeName(b){b=b.toString(26);var a="",d="",c;for(c in b)var f="0123456789abcdefghijklmnopqrstuvwxyz".indexOf(b[c]),a=a+"0123456789abcdefghijklmnopqrstuvwxyz".substring(f+10,f+11);for(var e in a)d+=0==e%2?a[e].toUpperCase()+"aeiou"[e%5]:a[e]+" ";return d.trim()} function decodeName(b){var a="",d="",c;for(c in b)a+=0<="aeiou".indexOf(b[c])||" "==b[c]?"":b[c].toLowerCase();for(c in a)d+="0123456789abcdefghijklmnopqrstuvwxyz"["0123456789abcdefghijklmnopqrstuvwxyz".indexOf(a[c])-10];return parseInt(d,26)}; var date = 1003; alert(encodeName(date) + ' -- ' + decodeName(encodeName(date))); var date = 9123; alert(encodeName(date) + ' -- ' + decodeName(encodeName(date))); var date = 3333; alert(encodeName(date) + ' -- ' + decodeName(encodeName(date))); var date = 2321; alert(encodeName(date) + ' -- ' + decodeName(encodeName(date))); var date = 0345; alert(encodeName(date) + ' -- ' + decodeName(encodeName(date))); ``` ]
[Question] [ As you may know, the Unicode standard has room for 1,114,111 code points, and each assigned code point represents a glyph (character, emoji, etc.). Most code points are not yet assigned. Current Unicode implementations take a lot of space to encode all possible code points (UTF-32 takes 4 bytes per code point, UTF-16: 2 to 4 bytes, UTF-8: 1 to 4 bytes, etc.) ## Task Today, your task is to implement your own Unicode implementation, with the following rules: * Write an encoder and a decoder in any language of your choice * The encoder's input is a list of code points (as integers) and it outputs a list of bytes (as integers) corresponding to your encoding. * The decoder does the opposite (bytes => code points) * Your implementation has to cover all Unicode 7.0.0 assigned code points * It has to stay backwards-compatible with ASCII, i.e. encode Basic latin characters (U+0000-U+007F) on one byte, with 0 as most significant bit. * Encode all the other assigned code points in any form and any number of bytes you want, as long as there is no ambiguity (i.e. two code points or group of code points can't have the same encoding and vice versa) * Your implementation doesn't have to cover UTF-16 surrogates (code points U+D800-U+DFFF) nor private use areas (U+E000-U+F8FF, U+F0000-U+10FFFF) * Your encoding must be context-independant (i.e. not rely on previously encoded characters) and does NOT require self-synchronization (i.e. each byte doesn't have to infer where it's located in the encoding of a code point, like in UTF-8). To sum up, here are the blocks that you have to cover, in JSON: (source: <http://www.unicode.org/Public/UNIDATA/Blocks.txt>) ``` [ [0x0000,0x007F], // Basic Latin [0x0080,0x00FF], // Latin-1 Supplement [0x0100,0x017F], // Latin Extended-A [0x0180,0x024F], // Latin Extended-B [0x0250,0x02AF], // IPA Extensions [0x02B0,0x02FF], // Spacing Modifier Letters [0x0300,0x036F], // Combining Diacritical Marks [0x0370,0x03FF], // Greek and Coptic [0x0400,0x04FF], // Cyrillic [0x0500,0x052F], // Cyrillic Supplement [0x0530,0x058F], // Armenian [0x0590,0x05FF], // Hebrew [0x0600,0x06FF], // Arabic [0x0700,0x074F], // Syriac [0x0750,0x077F], // Arabic Supplement [0x0780,0x07BF], // Thaana [0x07C0,0x07FF], // NKo [0x0800,0x083F], // Samaritan [0x0840,0x085F], // Mandaic [0x08A0,0x08FF], // Arabic Extended-A [0x0900,0x097F], // Devanagari [0x0980,0x09FF], // Bengali [0x0A00,0x0A7F], // Gurmukhi [0x0A80,0x0AFF], // Gujarati [0x0B00,0x0B7F], // Oriya [0x0B80,0x0BFF], // Tamil [0x0C00,0x0C7F], // Telugu [0x0C80,0x0CFF], // Kannada [0x0D00,0x0D7F], // Malayalam [0x0D80,0x0DFF], // Sinhala [0x0E00,0x0E7F], // Thai [0x0E80,0x0EFF], // Lao [0x0F00,0x0FFF], // Tibetan [0x1000,0x109F], // Myanmar [0x10A0,0x10FF], // Georgian [0x1100,0x11FF], // Hangul Jamo [0x1200,0x137F], // Ethiopic [0x1380,0x139F], // Ethiopic Supplement [0x13A0,0x13FF], // Cherokee [0x1400,0x167F], // Unified Canadian Aboriginal Syllabics [0x1680,0x169F], // Ogham [0x16A0,0x16FF], // Runic [0x1700,0x171F], // Tagalog [0x1720,0x173F], // Hanunoo [0x1740,0x175F], // Buhid [0x1760,0x177F], // Tagbanwa [0x1780,0x17FF], // Khmer [0x1800,0x18AF], // Mongolian [0x18B0,0x18FF], // Unified Canadian Aboriginal Syllabics Extended [0x1900,0x194F], // Limbu [0x1950,0x197F], // Tai Le [0x1980,0x19DF], // New Tai Lue [0x19E0,0x19FF], // Khmer Symbols [0x1A00,0x1A1F], // Buginese [0x1A20,0x1AAF], // Tai Tham [0x1AB0,0x1AFF], // Combining Diacritical Marks Extended [0x1B00,0x1B7F], // Balinese [0x1B80,0x1BBF], // Sundanese [0x1BC0,0x1BFF], // Batak [0x1C00,0x1C4F], // Lepcha [0x1C50,0x1C7F], // Ol Chiki [0x1CC0,0x1CCF], // Sundanese Supplement [0x1CD0,0x1CFF], // Vedic Extensions [0x1D00,0x1D7F], // Phonetic Extensions [0x1D80,0x1DBF], // Phonetic Extensions Supplement [0x1DC0,0x1DFF], // Combining Diacritical Marks Supplement [0x1E00,0x1EFF], // Latin Extended Additional [0x1F00,0x1FFF], // Greek Extended [0x2000,0x206F], // General Punctuation [0x2070,0x209F], // Superscripts and Subscripts [0x20A0,0x20CF], // Currency Symbols [0x20D0,0x20FF], // Combining Diacritical Marks for Symbols [0x2100,0x214F], // Letterlike Symbols [0x2150,0x218F], // Number Forms [0x2190,0x21FF], // Arrows [0x2200,0x22FF], // Mathematical Operators [0x2300,0x23FF], // Miscellaneous Technical [0x2400,0x243F], // Control Pictures [0x2440,0x245F], // Optical Character Recognition [0x2460,0x24FF], // Enclosed Alphanumerics [0x2500,0x257F], // Box Drawing [0x2580,0x259F], // Block Elements [0x25A0,0x25FF], // Geometric Shapes [0x2600,0x26FF], // Miscellaneous Symbols [0x2700,0x27BF], // Dingbats [0x27C0,0x27EF], // Miscellaneous Mathematical Symbols-A [0x27F0,0x27FF], // Supplemental Arrows-A [0x2800,0x28FF], // Braille Patterns [0x2900,0x297F], // Supplemental Arrows-B [0x2980,0x29FF], // Miscellaneous Mathematical Symbols-B [0x2A00,0x2AFF], // Supplemental Mathematical Operators [0x2B00,0x2BFF], // Miscellaneous Symbols and Arrows [0x2C00,0x2C5F], // Glagolitic [0x2C60,0x2C7F], // Latin Extended-C [0x2C80,0x2CFF], // Coptic [0x2D00,0x2D2F], // Georgian Supplement [0x2D30,0x2D7F], // Tifinagh [0x2D80,0x2DDF], // Ethiopic Extended [0x2DE0,0x2DFF], // Cyrillic Extended-A [0x2E00,0x2E7F], // Supplemental Punctuation [0x2E80,0x2EFF], // CJK Radicals Supplement [0x2F00,0x2FDF], // Kangxi Radicals [0x2FF0,0x2FFF], // Ideographic Description Characters [0x3000,0x303F], // CJK Symbols and Punctuation [0x3040,0x309F], // Hiragana [0x30A0,0x30FF], // Katakana [0x3100,0x312F], // Bopomofo [0x3130,0x318F], // Hangul Compatibility Jamo [0x3190,0x319F], // Kanbun [0x31A0,0x31BF], // Bopomofo Extended [0x31C0,0x31EF], // CJK Strokes [0x31F0,0x31FF], // Katakana Phonetic Extensions [0x3200,0x32FF], // Enclosed CJK Letters and Months [0x3300,0x33FF], // CJK Compatibility [0x3400,0x4DBF], // CJK Unified Ideographs Extension A [0x4DC0,0x4DFF], // Yijing Hexagram Symbols [0x4E00,0x9FFF], // CJK Unified Ideographs [0xA000,0xA48F], // Yi Syllables [0xA490,0xA4CF], // Yi Radicals [0xA4D0,0xA4FF], // Lisu [0xA500,0xA63F], // Vai [0xA640,0xA69F], // Cyrillic Extended-B [0xA6A0,0xA6FF], // Bamum [0xA700,0xA71F], // Modifier Tone Letters [0xA720,0xA7FF], // Latin Extended-D [0xA800,0xA82F], // Syloti Nagri [0xA830,0xA83F], // Common Indic Number Forms [0xA840,0xA87F], // Phags-pa [0xA880,0xA8DF], // Saurashtra [0xA8E0,0xA8FF], // Devanagari Extended [0xA900,0xA92F], // Kayah Li [0xA930,0xA95F], // Rejang [0xA960,0xA97F], // Hangul Jamo Extended-A [0xA980,0xA9DF], // Javanese [0xA9E0,0xA9FF], // Myanmar Extended-B [0xAA00,0xAA5F], // Cham [0xAA60,0xAA7F], // Myanmar Extended-A [0xAA80,0xAADF], // Tai Viet [0xAAE0,0xAAFF], // Meetei Mayek Extensions [0xAB00,0xAB2F], // Ethiopic Extended-A [0xAB30,0xAB6F], // Latin Extended-E [0xABC0,0xABFF], // Meetei Mayek [0xAC00,0xD7AF], // Hangul Syllables [0xD7B0,0xD7FF], // Hangul Jamo Extended-B [0xF900,0xFAFF], // CJK Compatibility Ideographs [0xFB00,0xFB4F], // Alphabetic Presentation Forms [0xFB50,0xFDFF], // Arabic Presentation Forms-A [0xFE00,0xFE0F], // Variation Selectors [0xFE10,0xFE1F], // Vertical Forms [0xFE20,0xFE2F], // Combining Half Marks [0xFE30,0xFE4F], // CJK Compatibility Forms [0xFE50,0xFE6F], // Small Form Variants [0xFE70,0xFEFF], // Arabic Presentation Forms-B [0xFF00,0xFFEF], // Halfwidth and Fullwidth Forms [0xFFF0,0xFFFF], // Specials [0x10000,0x1007F], // Linear B Syllabary [0x10080,0x100FF], // Linear B Ideograms [0x10100,0x1013F], // Aegean Numbers [0x10140,0x1018F], // Ancient Greek Numbers [0x10190,0x101CF], // Ancient Symbols [0x101D0,0x101FF], // Phaistos Disc [0x10280,0x1029F], // Lycian [0x102A0,0x102DF], // Carian [0x102E0,0x102FF], // Coptic Epact Numbers [0x10300,0x1032F], // Old Italic [0x10330,0x1034F], // Gothic [0x10350,0x1037F], // Old Permic [0x10380,0x1039F], // Ugaritic [0x103A0,0x103DF], // Old Persian [0x10400,0x1044F], // Deseret [0x10450,0x1047F], // Shavian [0x10480,0x104AF], // Osmanya [0x10500,0x1052F], // Elbasan [0x10530,0x1056F], // Caucasian Albanian [0x10600,0x1077F], // Linear A [0x10800,0x1083F], // Cypriot Syllabary [0x10840,0x1085F], // Imperial Aramaic [0x10860,0x1087F], // Palmyrene [0x10880,0x108AF], // Nabataean [0x10900,0x1091F], // Phoenician [0x10920,0x1093F], // Lydian [0x10980,0x1099F], // Meroitic Hieroglyphs [0x109A0,0x109FF], // Meroitic Cursive [0x10A00,0x10A5F], // Kharoshthi [0x10A60,0x10A7F], // Old South Arabian [0x10A80,0x10A9F], // Old North Arabian [0x10AC0,0x10AFF], // Manichaean [0x10B00,0x10B3F], // Avestan [0x10B40,0x10B5F], // Inscriptional Parthian [0x10B60,0x10B7F], // Inscriptional Pahlavi [0x10B80,0x10BAF], // Psalter Pahlavi [0x10C00,0x10C4F], // Old Turkic [0x10E60,0x10E7F], // Rumi Numeral Symbols [0x11000,0x1107F], // Brahmi [0x11080,0x110CF], // Kaithi [0x110D0,0x110FF], // Sora Sompeng [0x11100,0x1114F], // Chakma [0x11150,0x1117F], // Mahajani [0x11180,0x111DF], // Sharada [0x111E0,0x111FF], // Sinhala Archaic Numbers [0x11200,0x1124F], // Khojki [0x112B0,0x112FF], // Khudawadi [0x11300,0x1137F], // Grantha [0x11480,0x114DF], // Tirhuta [0x11580,0x115FF], // Siddham [0x11600,0x1165F], // Modi [0x11680,0x116CF], // Takri [0x118A0,0x118FF], // Warang Citi [0x11AC0,0x11AFF], // Pau Cin Hau [0x12000,0x123FF], // Cuneiform [0x12400,0x1247F], // Cuneiform Numbers and Punctuation [0x13000,0x1342F], // Egyptian Hieroglyphs [0x16800,0x16A3F], // Bamum Supplement [0x16A40,0x16A6F], // Mro [0x16AD0,0x16AFF], // Bassa Vah [0x16B00,0x16B8F], // Pahawh Hmong [0x16F00,0x16F9F], // Miao [0x1B000,0x1B0FF], // Kana Supplement [0x1BC00,0x1BC9F], // Duployan [0x1BCA0,0x1BCAF], // Shorthand Format Controls [0x1D000,0x1D0FF], // Byzantine Musical Symbols [0x1D100,0x1D1FF], // Musical Symbols [0x1D200,0x1D24F], // Ancient Greek Musical Notation [0x1D300,0x1D35F], // Tai Xuan Jing Symbols [0x1D360,0x1D37F], // Counting Rod Numerals [0x1D400,0x1D7FF], // Mathematical Alphanumeric Symbols [0x1E800,0x1E8DF], // Mende Kikakui [0x1EE00,0x1EEFF], // Arabic Mathematical Alphabetic Symbols [0x1F000,0x1F02F], // Mahjong Tiles [0x1F030,0x1F09F], // Domino Tiles [0x1F0A0,0x1F0FF], // Playing Cards [0x1F100,0x1F1FF], // Enclosed Alphanumeric Supplement [0x1F200,0x1F2FF], // Enclosed Ideographic Supplement [0x1F300,0x1F5FF], // Miscellaneous Symbols and Pictographs [0x1F600,0x1F64F], // Emoticons [0x1F650,0x1F67F], // Ornamental Dingbats [0x1F680,0x1F6FF], // Transport and Map Symbols [0x1F700,0x1F77F], // Alchemical Symbols [0x1F780,0x1F7FF], // Geometric Shapes Extended [0x1F800,0x1F8FF], // Supplemental Arrows-C [0x20000,0x2A6DF], // CJK Unified Ideographs Extension B [0x2A700,0x2B73F], // CJK Unified Ideographs Extension C [0x2B740,0x2B81F], // CJK Unified Ideographs Extension D [0x2F800,0x2FA1F], // CJK Compatibility Ideographs Supplement [0xE0000,0xE007F], // Tags [0xE0100,0xE01EF] // Variation Selectors Supplement ] ``` Total: 116,816 code points. ## Scoring Your score is not the size of your encoder/decoder, but the number of bytes that your encoder outputs when you feed it with all the 116,816 possible code points (in one time or separately). ## Winner The most efficient encoding will win and will be the subject of a future code-golf challenge ;) Good luck! [Answer] # Score: 318080 (~2.72 bytes/char) 1. I assume the encoding does not require self-synchronization (like UTF-8 / UTF-16). 2. Because there is no example text, I assume the encoding is *context-independent* (unlike e.g. [SCSU](http://en.wikipedia.org/wiki/Standard_Compression_Scheme_for_Unicode)), i.e. the encoder converts every code point to a unique bytes sequence. 3. log₂ 116816 = 16.83 > 16, so any encoding chosen must contain some code point that map to 3 bytes. For simplicity, let's assume we need to encode exactly 217 = 131072 code points. We could first map every code point to an integer from 0 to 131071. Then remaining is the optimization problem (a *mathematical* problem) on choosing a code which minimize L(E) = ∑0≤i<131072 |E(i)|. One possible encoding is *prefix code*. The specification already 0-prefixed sequence is for 0 ... 127 only. A simple, inefficient encoding is to use 1-prefixed sequence for the remaining code: ``` 0xxxxxxx = x (this encodes values < 128) 1xxxxxxx xxxxxxxx xxxxxxxx = x + 128 (this encodes values < 131072) ``` The value is (1 byte × 128 + 3 bytes × (131072 − 128)) = 392960 bytes. We could also use 2-bit prefix, e.g. ``` 0xxxxxxx = x (< 128) 10xxxxxx = x + 128 (< 192) 11xxxxxx xxxxxxxx xxxxxxxx = x + 192 (< 131072) L(E) = 192×1 + 130880×3 = 392832 ``` or ``` 0xxxxxxx = x (< 128) 10xxxxxx xxxxxxxx = x + 128 (< 16512) 11xxxxxx xxxxxxxx xxxxxxxx = x + 16512 (< 131072) L(E) = 376576 ``` etc. I think the most efficient coding is like this: ``` 0xxxxxxx = x 10xxxxxx xxxxxxxx = x + 128 110xxxxx xxxxxxxx = x + 16512 \ 1110xxxx xxxxxxxx = x + 24704 | squeeze all possible values 11110xxx xxxxxxxx = x + 28800 | encodable by 2 bytes 111110xx xxxxxxxx = x + 30848 | until 17 bits remains. 1111110x xxxxxxxx = x + 31872 / 1111111x xxxxxxxx xxxxxxxx = x + 32384 (up to 163456) L(E) = 360704 ``` --- Since the encoding supports all numbers up to 163456, I have chosen to close some "narrow" gaps under 14000 code points to simply the code point → number conversion, so it will support the ranges: ``` U+0000 .. U+17000 U+1b000 .. U+2b900 U+2f800 .. U+2fb00 U+e0000 .. U+e0200 ``` Since the range of numbers are extended, **the score will be a few bytes above optimal**, but I would compromise that for simplicity of the encoder here. So the encoder and decoders may be written as (Python 3): ``` def codepoint_to_number(codepoint): if 0 <= codepoint < 0x17000: return codepoint elif 0x1b000 <= codepoint < 0x2b900: return codepoint - 0x4000 elif 0x2f800 <= codepoint < 0x2fb00: return codepoint - 0x7f00 elif 0xe0000 <= codepoint < 0xe0200: return codepoint - 0xb8400 else: raise UnicodeError('Cannot encode ' + hex(codepoint)) def number_to_bytes(number): if number < 0x80: return bytes([number]) elif number < 0x7e80: number += 0x7f80 return bytes([number >> 8, number & 0xff]) else: number += 0xfd8180 return bytes([number >> 16, (number >> 8) & 0xff, number & 0xff]) def bytes_to_number(bs): first_byte = bs[0] if first_byte < 0x80: return (first_byte, bs[1:]) elif first_byte < 0xfe: return (0x80 + ((first_byte & 0x7f) << 8 | bs[1]), bs[2:]) else: return (0x7e80 + ((first_byte & 1) << 16 | bs[1] << 8 | bs[2]), bs[3:]) def number_to_codepoint(number): if number < 0x17000: return number elif number < 0x27900: return number + 0x4000 elif number < 0x27c00: return number + 0x7f00 else: return number + 0xb8400 def encode(codepoints): result = bytearray() for codepoint in codepoints: result.extend(number_to_bytes(codepoint_to_number(codepoint))) return result def decode(bytes_sequence): bs = memoryview(bytes_sequence) while bs: (number, bs) = bytes_to_number(bs) yield number_to_codepoint(number) ``` # Test case: ``` import itertools import unittest # {{{ CODEPOINT_RANGES = [ [0x0000,0x007F], # Basic Latin [0x0080,0x00FF], # Latin-1 Supplement [0x0100,0x017F], # Latin Extended-A [0x0180,0x024F], # Latin Extended-B [0x0250,0x02AF], # IPA Extensions [0x02B0,0x02FF], # Spacing Modifier Letters [0x0300,0x036F], # Combining Diacritical Marks [0x0370,0x03FF], # Greek and Coptic [0x0400,0x04FF], # Cyrillic [0x0500,0x052F], # Cyrillic Supplement [0x0530,0x058F], # Armenian [0x0590,0x05FF], # Hebrew [0x0600,0x06FF], # Arabic [0x0700,0x074F], # Syriac [0x0750,0x077F], # Arabic Supplement [0x0780,0x07BF], # Thaana [0x07C0,0x07FF], # NKo [0x0800,0x083F], # Samaritan [0x0840,0x085F], # Mandaic [0x08A0,0x08FF], # Arabic Extended-A [0x0900,0x097F], # Devanagari [0x0980,0x09FF], # Bengali [0x0A00,0x0A7F], # Gurmukhi [0x0A80,0x0AFF], # Gujarati [0x0B00,0x0B7F], # Oriya [0x0B80,0x0BFF], # Tamil [0x0C00,0x0C7F], # Telugu [0x0C80,0x0CFF], # Kannada [0x0D00,0x0D7F], # Malayalam [0x0D80,0x0DFF], # Sinhala [0x0E00,0x0E7F], # Thai [0x0E80,0x0EFF], # Lao [0x0F00,0x0FFF], # Tibetan [0x1000,0x109F], # Myanmar [0x10A0,0x10FF], # Georgian [0x1100,0x11FF], # Hangul Jamo [0x1200,0x137F], # Ethiopic [0x1380,0x139F], # Ethiopic Supplement [0x13A0,0x13FF], # Cherokee [0x1400,0x167F], # Unified Canadian Aboriginal Syllabics [0x1680,0x169F], # Ogham [0x16A0,0x16FF], # Runic [0x1700,0x171F], # Tagalog [0x1720,0x173F], # Hanunoo [0x1740,0x175F], # Buhid [0x1760,0x177F], # Tagbanwa [0x1780,0x17FF], # Khmer [0x1800,0x18AF], # Mongolian [0x18B0,0x18FF], # Unified Canadian Aboriginal Syllabics Extended [0x1900,0x194F], # Limbu [0x1950,0x197F], # Tai Le [0x1980,0x19DF], # New Tai Lue [0x19E0,0x19FF], # Khmer Symbols [0x1A00,0x1A1F], # Buginese [0x1A20,0x1AAF], # Tai Tham [0x1AB0,0x1AFF], # Combining Diacritical Marks Extended [0x1B00,0x1B7F], # Balinese [0x1B80,0x1BBF], # Sundanese [0x1BC0,0x1BFF], # Batak [0x1C00,0x1C4F], # Lepcha [0x1C50,0x1C7F], # Ol Chiki [0x1CC0,0x1CCF], # Sundanese Supplement [0x1CD0,0x1CFF], # Vedic Extensions [0x1D00,0x1D7F], # Phonetic Extensions [0x1D80,0x1DBF], # Phonetic Extensions Supplement [0x1DC0,0x1DFF], # Combining Diacritical Marks Supplement [0x1E00,0x1EFF], # Latin Extended Additional [0x1F00,0x1FFF], # Greek Extended [0x2000,0x206F], # General Punctuation [0x2070,0x209F], # Superscripts and Subscripts [0x20A0,0x20CF], # Currency Symbols [0x20D0,0x20FF], # Combining Diacritical Marks for Symbols [0x2100,0x214F], # Letterlike Symbols [0x2150,0x218F], # Number Forms [0x2190,0x21FF], # Arrows [0x2200,0x22FF], # Mathematical Operators [0x2300,0x23FF], # Miscellaneous Technical [0x2400,0x243F], # Control Pictures [0x2440,0x245F], # Optical Character Recognition [0x2460,0x24FF], # Enclosed Alphanumerics [0x2500,0x257F], # Box Drawing [0x2580,0x259F], # Block Elements [0x25A0,0x25FF], # Geometric Shapes [0x2600,0x26FF], # Miscellaneous Symbols [0x2700,0x27BF], # Dingbats [0x27C0,0x27EF], # Miscellaneous Mathematical Symbols-A [0x27F0,0x27FF], # Supplemental Arrows-A [0x2800,0x28FF], # Braille Patterns [0x2900,0x297F], # Supplemental Arrows-B [0x2980,0x29FF], # Miscellaneous Mathematical Symbols-B [0x2A00,0x2AFF], # Supplemental Mathematical Operators [0x2B00,0x2BFF], # Miscellaneous Symbols and Arrows [0x2C00,0x2C5F], # Glagolitic [0x2C60,0x2C7F], # Latin Extended-C [0x2C80,0x2CFF], # Coptic [0x2D00,0x2D2F], # Georgian Supplement [0x2D30,0x2D7F], # Tifinagh [0x2D80,0x2DDF], # Ethiopic Extended [0x2DE0,0x2DFF], # Cyrillic Extended-A [0x2E00,0x2E7F], # Supplemental Punctuation [0x2E80,0x2EFF], # CJK Radicals Supplement [0x2F00,0x2FDF], # Kangxi Radicals [0x2FF0,0x2FFF], # Ideographic Description Characters [0x3000,0x303F], # CJK Symbols and Punctuation [0x3040,0x309F], # Hiragana [0x30A0,0x30FF], # Katakana [0x3100,0x312F], # Bopomofo [0x3130,0x318F], # Hangul Compatibility Jamo [0x3190,0x319F], # Kanbun [0x31A0,0x31BF], # Bopomofo Extended [0x31C0,0x31EF], # CJK Strokes [0x31F0,0x31FF], # Katakana Phonetic Extensions [0x3200,0x32FF], # Enclosed CJK Letters and Months [0x3300,0x33FF], # CJK Compatibility [0x3400,0x4DBF], # CJK Unified Ideographs Extension A [0x4DC0,0x4DFF], # Yijing Hexagram Symbols [0x4E00,0x9FFF], # CJK Unified Ideographs [0xA000,0xA48F], # Yi Syllables [0xA490,0xA4CF], # Yi Radicals [0xA4D0,0xA4FF], # Lisu [0xA500,0xA63F], # Vai [0xA640,0xA69F], # Cyrillic Extended-B [0xA6A0,0xA6FF], # Bamum [0xA700,0xA71F], # Modifier Tone Letters [0xA720,0xA7FF], # Latin Extended-D [0xA800,0xA82F], # Syloti Nagri [0xA830,0xA83F], # Common Indic Number Forms [0xA840,0xA87F], # Phags-pa [0xA880,0xA8DF], # Saurashtra [0xA8E0,0xA8FF], # Devanagari Extended [0xA900,0xA92F], # Kayah Li [0xA930,0xA95F], # Rejang [0xA960,0xA97F], # Hangul Jamo Extended-A [0xA980,0xA9DF], # Javanese [0xA9E0,0xA9FF], # Myanmar Extended-B [0xAA00,0xAA5F], # Cham [0xAA60,0xAA7F], # Myanmar Extended-A [0xAA80,0xAADF], # Tai Viet [0xAAE0,0xAAFF], # Meetei Mayek Extensions [0xAB00,0xAB2F], # Ethiopic Extended-A [0xAB30,0xAB6F], # Latin Extended-E [0xABC0,0xABFF], # Meetei Mayek [0xAC00,0xD7AF], # Hangul Syllables [0xD7B0,0xD7FF], # Hangul Jamo Extended-B [0xF900,0xFAFF], # CJK Compatibility Ideographs [0xFB00,0xFB4F], # Alphabetic Presentation Forms [0xFB50,0xFDFF], # Arabic Presentation Forms-A [0xFE00,0xFE0F], # Variation Selectors [0xFE10,0xFE1F], # Vertical Forms [0xFE20,0xFE2F], # Combining Half Marks [0xFE30,0xFE4F], # CJK Compatibility Forms [0xFE50,0xFE6F], # Small Form Variants [0xFE70,0xFEFF], # Arabic Presentation Forms-B [0xFF00,0xFFEF], # Halfwidth and Fullwidth Forms [0xFFF0,0xFFFF], # Specials [0x10000,0x1007F], # Linear B Syllabary [0x10080,0x100FF], # Linear B Ideograms [0x10100,0x1013F], # Aegean Numbers [0x10140,0x1018F], # Ancient Greek Numbers [0x10190,0x101CF], # Ancient Symbols [0x101D0,0x101FF], # Phaistos Disc [0x10280,0x1029F], # Lycian [0x102A0,0x102DF], # Carian [0x102E0,0x102FF], # Coptic Epact Numbers [0x10300,0x1032F], # Old Italic [0x10330,0x1034F], # Gothic [0x10350,0x1037F], # Old Permic [0x10380,0x1039F], # Ugaritic [0x103A0,0x103DF], # Old Persian [0x10400,0x1044F], # Deseret [0x10450,0x1047F], # Shavian [0x10480,0x104AF], # Osmanya [0x10500,0x1052F], # Elbasan [0x10530,0x1056F], # Caucasian Albanian [0x10600,0x1077F], # Linear A [0x10800,0x1083F], # Cypriot Syllabary [0x10840,0x1085F], # Imperial Aramaic [0x10860,0x1087F], # Palmyrene [0x10880,0x108AF], # Nabataean [0x10900,0x1091F], # Phoenician [0x10920,0x1093F], # Lydian [0x10980,0x1099F], # Meroitic Hieroglyphs [0x109A0,0x109FF], # Meroitic Cursive [0x10A00,0x10A5F], # Kharoshthi [0x10A60,0x10A7F], # Old South Arabian [0x10A80,0x10A9F], # Old North Arabian [0x10AC0,0x10AFF], # Manichaean [0x10B00,0x10B3F], # Avestan [0x10B40,0x10B5F], # Inscriptional Parthian [0x10B60,0x10B7F], # Inscriptional Pahlavi [0x10B80,0x10BAF], # Psalter Pahlavi [0x10C00,0x10C4F], # Old Turkic [0x10E60,0x10E7F], # Rumi Numeral Symbols [0x11000,0x1107F], # Brahmi [0x11080,0x110CF], # Kaithi [0x110D0,0x110FF], # Sora Sompeng [0x11100,0x1114F], # Chakma [0x11150,0x1117F], # Mahajani [0x11180,0x111DF], # Sharada [0x111E0,0x111FF], # Sinhala Archaic Numbers [0x11200,0x1124F], # Khojki [0x112B0,0x112FF], # Khudawadi [0x11300,0x1137F], # Grantha [0x11480,0x114DF], # Tirhuta [0x11580,0x115FF], # Siddham [0x11600,0x1165F], # Modi [0x11680,0x116CF], # Takri [0x118A0,0x118FF], # Warang Citi [0x11AC0,0x11AFF], # Pau Cin Hau [0x12000,0x123FF], # Cuneiform [0x12400,0x1247F], # Cuneiform Numbers and Punctuation [0x13000,0x1342F], # Egyptian Hieroglyphs [0x16800,0x16A3F], # Bamum Supplement [0x16A40,0x16A6F], # Mro [0x16AD0,0x16AFF], # Bassa Vah [0x16B00,0x16B8F], # Pahawh Hmong [0x16F00,0x16F9F], # Miao [0x1B000,0x1B0FF], # Kana Supplement [0x1BC00,0x1BC9F], # Duployan [0x1BCA0,0x1BCAF], # Shorthand Format Controls [0x1D000,0x1D0FF], # Byzantine Musical Symbols [0x1D100,0x1D1FF], # Musical Symbols [0x1D200,0x1D24F], # Ancient Greek Musical Notation [0x1D300,0x1D35F], # Tai Xuan Jing Symbols [0x1D360,0x1D37F], # Counting Rod Numerals [0x1D400,0x1D7FF], # Mathematical Alphanumeric Symbols [0x1E800,0x1E8DF], # Mende Kikakui [0x1EE00,0x1EEFF], # Arabic Mathematical Alphabetic Symbols [0x1F000,0x1F02F], # Mahjong Tiles [0x1F030,0x1F09F], # Domino Tiles [0x1F0A0,0x1F0FF], # Playing Cards [0x1F100,0x1F1FF], # Enclosed Alphanumeric Supplement [0x1F200,0x1F2FF], # Enclosed Ideographic Supplement [0x1F300,0x1F5FF], # Miscellaneous Symbols and Pictographs [0x1F600,0x1F64F], # Emoticons [0x1F650,0x1F67F], # Ornamental Dingbats [0x1F680,0x1F6FF], # Transport and Map Symbols [0x1F700,0x1F77F], # Alchemical Symbols [0x1F780,0x1F7FF], # Geometric Shapes Extended [0x1F800,0x1F8FF], # Supplemental Arrows-C [0x20000,0x2A6DF], # CJK Unified Ideographs Extension B [0x2A700,0x2B73F], # CJK Unified Ideographs Extension C [0x2B740,0x2B81F], # CJK Unified Ideographs Extension D [0x2F800,0x2FA1F], # CJK Compatibility Ideographs Supplement [0xE0000,0xE007F], # Tags [0xE0100,0xE01EF] # Variation Selectors Supplement ] #}}} ALL_CODEPOINTS = list(itertools.chain.from_iterable(range(x, y+1) for x, y in CODEPOINT_RANGES)) ENCODE_RESULT = encode(ALL_CODEPOINTS) print(len(ENCODE_RESULT), '/', len(ALL_CODEPOINTS)) DECODE_RESULT = list(decode(ENCODE_RESULT)) tc = unittest.TestCase() tc.assertListEqual(ALL_CODEPOINTS, DECODE_RESULT) ``` ]
[Question] [ The [edit (or Levenshtein) distance](https://en.wikipedia.org/wiki/Edit_distance) between two strings is the minimal number of single character insertions, deletions and substitutions needed to transform one string into the other. The challenge is to write code to output all strings with edit distance exactly k from a fixed string of length 10, where k is a variable set in your code as is the fixed string. The alphabet is 0 or 1. To test, take ``` 1111011010 ``` as the fixed string. The twist is that you can't output the same string twice. You may not use any library or built in functions that compute the Levenshtein distance for you. **Score** This is a standard code-golf challenge. You can assume k will be a one-digit number. **Reference Implementation** (added by Martin Büttner) For reference, here is a Mathematica solution (which isn't valid, due to use of `EditDistance`) which can be used to check results for correctness: ``` s = "1111011010"; k = 2; Union @ Cases[ Join @@ Array[# <> "" & /@ {"0", "1"}~Tuples~# &, 2 k + 1, 10 - k], x_ /; x~EditDistance~s == k ] ``` For the first ten values of `k` I the following results: ``` k | # of results 0 1 1 28 2 302 3 1652 4 5533 5 14533 6 34808 7 80407 8 180663 9 395923 ``` [Answer] # Scala 168 228 My first submission had a bug where it didn't consider multiple insertions at the same point in the input string. After ``` val k = 1 val s = "1111011010" ``` The code that counts is: ``` def e(k:Int,s:String):Set[String]=if(k<1)Set(s)else e(k-1,s).flatMap(e=>"01"map(_+e))++(if(s=="")Set()else e(k,s.tail).map(s.head+_)++e(k-1,s.tail).flatMap(e=>(Set("0","1","")-(s take 1))map(_+e))) print(e(k,s)) ``` To run, save both sections together as a file and run like: ``` $ scala distancek.scala Set(111111010, 111101010, 1111001010, 11110011010, 1101011010, 11101011010, 111101101, 111101100, 11111011010, 1111011011, 1111011000, 11110101010, 1111010010, 11110110110, 11110110101, 111101110, 11110110010, 0111011010, 1110011010, 11110110100, 10111011010, 11011011010, 01111011010, 1011011010, 1111111010, 111011010, 11110111010, 1111011110) $ ``` Recursive function to build the edited strings. k is the number of edits remaining, s is the string to edit. Slightly ungolfed: ``` def e(k:Int,s:String):Set[String]= if(k<1) Set(s) // No edits left else e(k-1,s).flatMap(e=>"01"map(_+e))++ // Insert a character, consume an edit, continue from the same point (if(s=="") Set() // We're at the end of the string so only insertions are allowed else e(k,s.tail).map(s.head+_)++ // skip past this character, making no edit e(k-1,s.tail).flatMap(e=>(Set("0","1","")-(s take 1))map(_+e))) // replace this character with its inverse or "" ``` Note that each step makes at least one of k, s smaller so we're guaranteed to terminate. --- First submission (Incorrect) ``` print((0 to 10).permutations.flatMap{i=>((s.map(_+""):+"")zip i).:\(Set("")){case((s,i),a)=>a.flatMap{a=>(if(i<k)Set(1+s,0+s,"","0","1")-s else Set(s))map(_+a)}}}toSet) ``` We take the permutations of 0..10 and zip them with the word s + a terminal "" (for insertions at the end). All the positions < k are positions where an edit should occur. For each edit we replace the string at that position with ``` Set(1+s,0+s,"","0","1")-s # don't count substituting s for itself as an edit. ``` and finally convert to a set to remove duplicates. [Answer] # JavaScript (E6) 167 ~~183~~ Assuming the definition of variables *k* (required distance) and *s* (fixed string, 1111011010 for test). As requested it outputs in console just the list of string, so good luck for counting. ``` o={},o[s]=1, A=x=>o[x]||(o[x]=d,d-k||console.log(x)), S=r=>{ for(l='';A(l+1+r),A(l+0+r),c=r[0];l+=c) r=r.slice(1),A(l+r),A(l+1+r),A(l+0+r) }; for(d=0;++d<=k;) for(q in o)S(q) ``` Less golfed and more sensible, a function with 2 parameters and a count in output ``` F=(k,s)=> { o={}, o[s]=1, h=0, add=x=>{ o[x]||(o[x] = d, d == k && console.log(++h,x)); }, scan=s=>{ add(s+1) add(s+0) for (l='',r=s,i=0; r; l += c) // l,r:left and right { add(l+1+r) add(l+0+r) c=r[0] r=r.slice(1) add(l+r) add(l+1+r) add(l+0+r) } }; for(d=0; ++d <= k;) for (q in o) scan(q) } ``` **Test** In FireFox/FireBug console ``` F(1,'1111011010') ``` *Output* ``` 1 11110110101 2 11110110100 3 11111011010 4 01111011010 5 111011010 6 0111011010 7 10111011010 8 1011011010 9 11011011010 10 1101011010 11 11101011010 12 1110011010 13 11110011010 14 111111010 15 1111111010 16 11110111010 17 111101010 18 1111001010 19 11110101010 20 1111010010 21 11110110010 22 111101110 23 1111011110 24 11110110110 25 111101100 26 1111011000 27 111101101 28 1111011011 ``` Just counting, no string output: ``` 10 -> 850064 (in 3min & 600 MB) 11 -> 1795537 (in 8min & 900 MB) ``` [Answer] # Haskell, ~~136~~ 134 ``` import Data.List n%l=iterate(>>=foldr(\t@(x:y)r->['0':t,'1':t,'0':y,'1':y,y]++map(x:)r)["0","1"].init.tails)[l]!!n r=nub(n%l)\\(n-1)%l ``` upon running `r` will become the list of all strings with edit distance of `3` from `"1111011010"`. the string is embedded in the code at line 5 and the required distance is at the end of the last line. **edit:** explanation is removed because it is nor relevant anymore [Answer] # CJam, ~~72~~ 64 bytes ``` QaK{_{_,),\f{[\:Lm>_,L>{_)1^+_);@}*_'0+\'1+]{Lm<}/}~}%_&}*]W%:-p ``` Assumes the string is stored in `Q` and the integer in `K`. This can be achieved by executing ``` "1111011010":Q;1:K; ``` for example. [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") ### Example run ``` $ cjam <(echo '"1111011010":Q;1:K;'; cat edit-distance.cjam) ["1111011011" "11110110100" "11110110101" "111101101" "1111011000" "11110110110" "111101100" "1111011110" "11110110010" "111101110" "1111010010" "11110111010" "111101010" "1111001010" "11110101010" "1111111010" "11110011010" "111111010" "1110011010" "11111011010" "111011010" "1101011010" "11101011010" "1011011010" "11011011010" "0111011010" "10111011010" "01111011010"] $ cjam <(echo '"1111011010":Q;1:K;'; sed 's/p/,p/' < edit-distance.cjam) 28 $ cjam <(echo '"1111011010":Q;2:K;'; sed 's/p/,p/' < edit-distance.cjam) 302 ``` ### How it works The idea is to recursively compute all strings at distance d or less ("or less" part not exhaustive), then remove the strings at distance k - 1 or less from the array of strings at distance k or less. ``` Qa " Push R := [Q]. "; K{ " Do the following K times: "; _ " Push a copy of R. "; { " For each S ∊ R: "; _,),\ " Push A := [ 0 1 ... len(S) ] below S. "; f{ " For each I ∊ A, push I S and: "; [ " "; \:Lm> " Rotate S (L := I) characters to the right. "; _,L " Push len(S) L. "; >{ " If len(S) > L: "; _)1^+ " XOR the last character code of a copy of S with 1. "; _);@ " Remove the last character of a copy of S. "; }* " "; _'0+ " Append '0' to a copy of S. "; \'1+ " Append '1' to S. "; ] " Collect the modified values of S in an array T. "; {Lm<}/ " For each U ∊ T, push U rotated L characters to the left. "; }~ " Dump the resulting array on the stack. "; }% " Collect the results in R. "; _& " Remove duplicates from R. "; }* " "; ]W% " Collect the different values of R in an array and reverse it. "; :- " Reduce the array using setwise difference. "; p " Print a string representation of the resulting array. "; ``` [Answer] ## Mathematica, 244 bytes ``` l=Length;e[s_,t_]:=(m=l@s;n=l@t;Clear@f;f[0,m_]:=m;f[m_,0]:=m;For[j=0,j++<n,For[i=0,i++<m,p=f[i-1,j-1];f[i,j]=If[s[[i]]==t[[j]],p,Min[p,f[i,j-1],f[i-1,j]]+1]]];f[m,n])#<>""&/@Union@Cases[Join@@Array[{"0","1"}~Tuples~#&,2k+1,l@s-k],x_/;x~e~s==k] ``` This is basically the same as the reference implementation I added to the question, except I reimplemented `EditDistance` (as `e`) using the Wagner-Fischer algorithm. That is, I simply generate all possible strings of the relevant lengths, and then I just reject all which aren't an edit distance of 2 away from the input string. This expects the distance to be stored in `k` and the input as an [array of characters](http://meta.codegolf.stackexchange.com/a/2216/8478) in `s`. Less golf: ``` l = Length; e[s_, t_] := ( m = l@s; n = l@t; Clear@f; f[0, m_] := m; f[m_, 0] := m; For[j = 0, j++ < n, For[i = 0, i++ < m, p = f[i - 1, j - 1]; f[i, j] = If[s[[i]] == t[[j]], p, Min[p, f[i, j - 1], f[i - 1, j]] + 1 ] ] ]; f[m, n] ) # <> "" & /@ Union@Cases[Join @@ Array[{"0", "1"}~Tuples~# &, 2 k + 1, l@s - k], x_ /; x~e~s == k] ``` [Answer] ## APL, ~~109~~ ~~103~~ 101 Assuming `s` and `k` are defined ``` ~⍨/{{∪⊃,/{⍵≡'':⍕¨0 1⋄(,/⍕¨↑(⍎¨⍵)∘≠¨↓∘.=⍨x),(/∘⍵¨↓∘.≠⍨x),(,⍨-0,x)⌽¨,'01'∘.,⌽∘⍵¨0,x←⍳⍴⍵}¨⍵}⍣⍵⊂s}¨0,⍳k ``` **Explantion** The program consists of 3 nested functions. **The inner function `{⍵≡'':⍕¨0 1⋄(,/⍕¨↑(⍎¨⍵)∘≠¨↓∘.=⍨x),(/∘⍵¨↓∘.≠⍨x),(,⍨-0,x)⌽¨,'01'∘.,⌽∘⍵¨0,x←⍳⍴⍵}`returns all string that is distance 1 from the argument** `(,⍨-0,x)⌽¨,'01'∘.,⌽∘⍵¨0,x←⍳⍴⍵` calculate insertions: `⍴⍵` length of the argument `⍳` generate array from 1 to that number `x←` assign to variable `x` `0,` concatenate `0` to the start of the array `⌽∘⍵¨` and for each of the number in the array, rotate the argument by that amount, generating an array of strings (rotate is defined as taking characters from the start of the string and appending to the back) `'01'∘.,` generate a matrix whose first row are the strings with `0` concatenated to the start and the second row are the strings with `1` concatenated to the start `,` unravel the matrix to give a simple array of its elements `(,⍨-0,x)` give the negatives of the array constructed by concatenating `0` to the start of `x`, and then concatenate that with another copy of it `⌽¨` finally, rotate the strings back by using the negative numbers `(/∘⍵¨↓∘.≠⍨x)` calculates deletions: `∘.≠⍨x` generate a square matrix consisting of 0's on the diagonal and 1's elsewhere, whose side is same length as `x` `↓` split the matrix rows to create a nested array `/∘⍵¨` for each of those arrays, replicate the characters of the argument according the the array (in the case where the array only contains 0's and 1's, it means where there is a 1 in the array, keep the character in the corresponding index and where there is a 0, discard the corresponding character) `(,/⍕¨↑(⍎¨⍵)∘≠¨↓∘.=⍨x)` calculates substitutions: `∘.=⍨x` generate a square matrix consisting of 1's on the diagonal and 0's elsewhere, whose side is same length as `x` `↓` split the matrix rows to create a nested array `(⍎¨⍵)∘≠¨` generate an array by converting the argument into a numerical array of its digits, then XOR it with each of the arrays from the split `↑` "mix" the nested array to create a matrix (reverse of split) `⍕¨` for each element of the matrix (which is either 1 or 0), convert to string `,/` for each row of the matrix, concatenate the elements `⍵≡'':⍕¨0 1` is a special case for the empty string (the substitution part will throw an error on empty string) `⍵≡'':` if the argument is the empty string... `⍕¨0 1` return this (an array of the strings `'0'` and `'1'`) **The middle function `{∪⊃,/{...}¨⍵}` takes an array of strings and return an array of all strings that is distance 1 from any of them** `{...}¨⍵` for each of the strings in the argument, use the inner function to get all strings distance 1 for it `,/` concatenate all of the returned arrays `⊃` as the result is "wrapped" in a scalar, "unwrap" it `∪` remove duplicates **The outer function {{...}⍣⍵⊂s}, given a number, calculates all string that is *potentially* that distance from `s`** `{...}⍣⍵` repeat the middle function `⍵` times (`⍵` is the argument) `⊂s` "wrap" `s` and call the function with that as the argument **The remaining part `~⍨/{...}¨0,⍳k`** `0,⍳k` generate array from `0` to `k` `{...}¨` for each of those numbers, call the outer function with it `~⍨/` remove the strings found in distances 0,1,2,...,k-1 from the strings found in distance k. This is necessary because the "distance 1" function is stateless - it does not consider stuff like substituting the same character twice or inserting and deleting the same character. ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/35532/edit). Closed 7 years ago. [Improve this question](/posts/35532/edit) Write a program that outputs a graph of the collatz sequence any way you want (ASCII Image Video etc). You have to implement it that way that you can adjust the size of the graph by either the maximum number of nodes or highest number in graph. [A boring example here.](http://2.bp.blogspot.com/-AsWaPOhHjfE/T1TA1kqzkxI/AAAAAAAAAAA/PEoWZkAhUUU/s1600/cc-crop.png "A boring example") Try to present the graph in a creative / insightful way, this is a popularity contest! Please comment your code / algorithm and post at least one example output in your answer. ### Background: *Collatz sequence* The Collatz sequence is defined for any natural number `n > 0` by the recursion: ![enter image description here](https://i.stack.imgur.com/DBTvR.png) The Collatz conjecture states that the sequence ends in the cycle 1,4,2 [Answer] ## Python+Graphviz ``` #!/usr/bin/env python # -*- coding: utf-8 -*- import networkx as nx import os """Tool to generate collatz sequence graphs.""" def collatz_one(x): """Make a single step in the collatz sequence.""" if x % 2 == 0: x = x/2 else: x = 3*x + 1 return x def main(max_collatz=20): """Create the collatz graph. """ G = nx.DiGraph() seen = [1] G.add_node("1") edges = [] for i in range(1, max_collatz): while i != 1: if i not in seen: seen.append(i) G.add_node(str(i)) j = collatz_one(i) edges.append((str(i), str(j))) i = j else: i = 1 for i, j in edges: G.add_edge(i, j) nx.write_dot(G, 'test.dot') os.system("dot -Tpng test.dot -o test.png") if __name__ == '__main__': from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument("-m", dest="m", help=("The first 1..m elements are guaranteed " "to be included"), default=20, type=int) args = parser.parse_args() main(args.m) ``` ## Image Created with `dot` and `m=20`: ![enter image description here](https://i.stack.imgur.com/XGE68.png) [Answer] # Ruby (via ChunkyPNG) I don't know if this is *quite* what you had in mind, but I had the idea to try this a while ago and hadn't gotten around to it. We create a row of random colors, then iteratively replace each color n with the color at `collatz(n)`, or an empty pixel if greater than the max, until every sequence either escapes or converges. The result is that each pixel gradually propagates to the positions connected to it in the graph. ``` gem 'chunky_png' require 'chunky_png' def random_color ChunkyPNG::Color.rgba(*(1..3).map{rand(1..255)},255) end def collatz(n) n.even? ? n/2 : 3*n + 1 end def collatz_grid(max) grid = [] colors = (1..max).map { |i| random_color } collatz_steps = (1..max).map { |n| collatz(n) } overflow = ChunkyPNG::Color::TRANSPARENT while colors.uniq.count > 4 grid << colors colors = collatz_steps.map { |i| colors[i-1] || overflow } end img = ChunkyPNG::Image.new(max, grid.size, ChunkyPNG::Color::TRANSPARENT) max.times do |x| grid.size.times do |y| img[x,y] = grid[y][x] end end img.save("collatz#{max}.png") end ``` Images below, suggest opening them in a new window and zooming in. `collatz_grid(100)`: ![A visualization of the Collatz graph with maximum node 100](https://i.stack.imgur.com/aFIfJ.png) `collatz_grid(10000)`: ![Maximum node 10000](https://i.stack.imgur.com/LUj8j.jpg) ]
[Question] [ **This question already has an answer here**: [Regex validating regex [closed]](/questions/3596/regex-validating-regex) (1 answer) Closed 9 years ago. Your task is to write a regular expression that matches *any valid regular expression* and no invalid expression. You may pick any regex flavour for your answer, but you have to match regular expressions of that *same* flavour. This is regex-golf, so the shortest regex wins. You can't invent your own regex language for this. That would be an example of a [standard loophole](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny). [Answer] # Not possible in Ruby! I wanted to write a regular expression in Ruby that matches valid regular expressions in Ruby, but I must conclude that writing one is not possible. At first, Ruby seems like a good choice. If I want to check for matching parentheses, I can write a recursive expression like `(?<mparen>([^()]|\(\g<mparen>\))*)` where *mparen* matches zero or more things that are either not parentheses, or are a set of parentheses with *mparen* inside. So I listed things that are valid and not valid in Ruby regular expressions. Then I found things that I cannot check with regular expressions. ## Empty ranges of characters In Ruby, `[a-b]` is a valid, but `[b-a]` is not valid, because `a` comes before `b`. This rule is common to several flavors of regular expressions: ``` $ ruby21 -e '/[b-a]/' -e:1: empty range in char class: /[b-a]/ $ perl -e 'qr/[b-a]/' Invalid [] range "b-a" in regex; marked by <-- HERE in m/[b-a <-- HERE ]/ at -e line 1. $ sed '/[b-a]/!d' sed: 1: "/[b-a]/!d": RE error: invalid character range ``` So how do I write a regular expression that matches `a-b` but not `b-a`, and works with any range? I can't. I would like to write `(?<begin>.)-[\k<begin>-z]` using a backreference to the first character. This would become `a-[a-z]` or `b-[b-z]` or so on. (Later I would change `z` to the highest character, but for now I test lowercase letters.) This fails because I can't use backreferences in ranges! `[\k<begin>-z]` is the same as `[<>-z]`, as the range `>-z` includes the letters `begkin`. I can write in 202 characters: ``` a-[a-z]|b-[b-z]|c-[c-z]|d-[d-z]|e-[e-z]|f-[f-z]|g-[g-z]|h-[h-z]|i-[i-z]|j-[j-z]|k-[k-z]|l-[l-z]|m-[m-z]|n-[n-z]|o-[o-z]|p-[p-z]|q-[q-z]|r-[r-z]|s-[s-z]|t-[t-z]|u-[u-z]|v-[v-z]|w-[w-z]|x-[x-z]|y-[yz]|z-z ``` This covers 26 lowercase letters, but only in their literal forms. Octal and hex escapes are also part of the regular expression syntax. Now `a` is also `\141` and `\x61`, and `z` is also `\172` and `\x7a`. My regular expression would need to match `\141-\172` and `\x61-\x7a`, and also `a-\172` and `\x61-z` and so on. ``` (a|\\141|\\x61)-([a-z]|\\1(4[2-7]|[5-7][0-7])|\\x(4[1-9a-fA-F]|[5-7]\h)) ``` I would not try to extend this to the 1112064 codepoints of Unicode. ## Missing capture groups A regular expression is not valid if it has a backreference to an undefined capture group. For example, `(?<a>)\k<b>` is not valid because it has no capture group *b*. So, my regular expression for valid regular expressions would need to check `\k<b>` against the set of valid names. I can't think of a way to do this in one regular expression. The answer is not `(?<=\(\?<b>.*)\\k<b>`. This would use the lookbehind feature to match `\k<b>` if there was a `(?<b>` earlier in the string. It fails because variable quantifiers like `*` are not valid in lookbehind expressions. Another problem happens with subexpression calls. It is valid for two capture groups to share the same name, but it is not valid for a subexpression call to use a multiplex name. So `(?<a>)(?<a>)` is valid but `(?<a>)(?<a>)\g<a>` is not. ## Encoding troubles A valid regular expression must also be valid in its character encoding. If the encoding is UTF-8, then `\xc4\x80` is valid but `\x80\x80` is not. My regular expression for regular expressions would also need to validate UTF-8. It is valid to mix octal and hex escapes, so `\xc4\200` and `\304\x80` are valid too. Ruby has other encodings. My regular expression would also need to validate EUC-JP, Windows-31J, GB18030, and every other ASCII-compatible encoding known to Ruby. That's not possible! My regular expression can't know which encoding to validate. Is `\200` a valid regular expression? `Regexp.new '\200'.encode('binary')` is valid, but `Regexp.new '\200'.encode('utf-8')` is not valid. My regular expression can't see the encoding tag. It can only see the four ASCII characters in `\200`, so it can't decide whether `\200` is valid. I might fix this if I decree that my regular expression for regular expressions only works with one encoding. I might pick 'us-ascii', which has only 128 characters. This does not fix my problem with capture groups. ]
[Question] [ Most of you have probably heard of the famous Turtle Graphics program, initially made popular by Logo. This challenge is to implement a Turtle Graphics program in your language of choice. Rules: 1. Rule one is that when the pen is in the down state, it must draw in both the square the turtle leaves and the square the turtle enters. This is what would happen in real life, so that is what your program should do. 2. Rule two is the turtle must include these 10 commands, which can be represented in the input as you like: > > RESET - resets board to blank - turtle position is default. > > > UP and DOWN - these two commands set the pen/eraser state. > > > RIGHT and LEFT - these two commands turn the turtle in the specified direction. > > > FORWARD - advances turtle to next square. > > > DRAW and ERASE - these commands set the turtle to drawing and erasing, respectively. > > > DISPLAY - displays board. > > > POSITION - prints turtle's x/y coordinate on the board. > > > STOP, which stops drawing, displays the board, and terminates the program after the user enters any input. > > > 1. The floor must be 20x20. You can use `vector`s, `array`s, or anything you like to represent it. 2. You must stop the turtle and display an error message if the turtle hits the wall. 3. Default turtle position is 0,0 facing right. Scoring: This program will use standard [atomic-code-golf](/questions/tagged/atomic-code-golf "show questions tagged 'atomic-code-golf'") scoring rules with a few modifications to try to allow industry programming languages, such as Java and C++, to compete. 1. `Import`s, `include`s, `using`s and other similar statements do not score anything. 2. Loop header statements each only score one point. All other statements add the full number of characters in the statement to the score. Example: These statements do not score: ``` #include <iostream> import java.util.Scanner; def inputCommand(): string inputCommand(){} ``` These statements score only one point: ``` for(int i = 0; i < 9; i++){} for i in range(0,10): while(true){} while x in y: ``` These statements score the full number of their characters: ``` string n; i = 9; switch(d) { case i: break; default: break; } return x; cout<<'example'; cin>>s; System.out.println() print('example') ``` If you have any questions or comments, please let me know in the comments. [Answer] ## JavaScript, one point ``` for (s=' ', reset=function(){a=s.split(/./).map(function(){return s.split(/(?=.)/)}); x=0; y=0; dx=1; dy=0; pen='#'; down=1;}, display=function(){console.log(a.map(function(x){return x.join('')}).join('\n'))}, position=function(){console.log(x, y)}, draw=function(){a[y][x]=down?pen:a[y][x]}, forward=function(){draw(); x+=dx; y+=dy; (y<0||y>19||x<0||x>19) && (console.log('Hit wall')||(dx?(x-=dx):(y-=dy))); draw();}, turn=function(d){nx=-1*(!dx)*d*dy; dy=(!dy)*d*dx; dx=nx;}, reset(); ((p=prompt()) != 'STOP') || display(); (p == "RESET") && reset(), (p == "DISPLAY") && display(), (p == "POSITION") && position(), (p == "DRAW") && (pen='#'), (p == "ERASE") && (pen=' '), (p == "UP") && (down=0), (p == "DOWN") && (down=1), (p == "RIGHT") && turn(1), (p == "LEFT") && turn(-1), (p == "FORWARD") && forward() ); ``` Sorry, I couldn't resist. [Answer] # Mathematica (1 point and ~~211~~ ~~208~~ 205 characters) ``` A:=Abort[] q@1:=Check[a〚##〛=c,A]&@@p DI:=Print@ArrayPlot@a ST:=DI+A PO:=Print@p FO:=p+=v LE:=v=Cross@v RI:=v=-LE DR:=c=1 ER:=c=0 UP:=d=0 DO:=d=1 v={UP,DR}; a=0Array[p=0v+1,20p]; Symbol@StringTake[#,2]q@d&/@StringSplit@s ``` It prints ![enter image description here](https://i.stack.imgur.com/ZrUAj.png) for ``` s = "DOWN RIGHT FORWARD FORWARD FORWARD FORWARD LEFT UP FORWARD LEFT \ FORWARD FORWARD DOWN RIGHT FORWARD UP FORWARD LEFT FORWARD DOWN \ FORWARD LEFT FORWARD FORWARD UP LEFT LEFT FORWARD FORWARD DOWN ERASE STOP"; ``` I assume that the initial state is up&drawing. You can put the whole code inside the header of `Do` loop ``` `Do[,{code; 1}]` ``` It is only `1` point! [Answer] # Java Here is my program - un-golfed (too complicated), unscored (I am unsure what the enums and Scanner object creation score as), and over-done: ``` package javaapplication74; import java.util.Scanner; import static java.lang.Integer.parseInt; public class JavaApplication74 { // create Scanner for input static Scanner in = new Scanner(System.in); // enumerator of commands private enum Commands {RESET, UP, DOWN, RIGHT, LEFT, FORWARD, DISPLAY, ERASE, REVERSE, POSITION, STOP, ERROR}; // enumerator of directions turtle can face private enum Direction {UP, DOWN, RIGHT, LEFT}; // array of valid commands static final char[] commands = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'r' }; // width and height of room; static final int ROOM = 20; // turtle's position static int[] position = {0, 0}; // number of squares to move static int move = 0; // Write a "turtle graphics" program public static void main(String[] args) { // array of drawn lines boolean[][] floor = new boolean[ROOM][ROOM]; // store command Commands command; // store current direction - default right Direction direction = Direction.RIGHT; // pen in drawing condition boolean draw = false; boolean erase = false; // provide directions directions(); // get and execute commands until stop do { // get command command = inputCommand(); // analyse and execute command switch(command) { case RESET: reset(floor); case UP: draw = false; erase = false; break; case DOWN: draw = true; erase = false; break; case RIGHT: case LEFT: direction = turn(command, direction); break; case FORWARD: floor = move(floor, direction, draw, erase); break; case DISPLAY: display(draw, floor); break; case ERASE: draw = false; erase = true; break; case REVERSE: reverse(floor); break; case POSITION: showPosition(direction); break; case STOP: case ERROR: break; } // end switch } while(command != Commands.STOP); // end do-while } // end method main // Provide directions public static void directions() { System.out.println("This is a turtle graphics program."); System.out.println("You have 11 commands available, use the number to the right to use that command:"); System.out.printf("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n", "0: Clear floor.", "1: Pen up, eraser up (default position).", "2: Pen down.", "3: Turn right.", "4: Turn left.", "5: Go forward x spaces (enter 5,x)", "6: Display current layout", "7: Erase", "8: Show turtle's position", "9: Quit program", "r: Draw or erase current square."); System.out.println("Note: the turtle will draw one more symbol than the number of spaces entered\n\tbecause it will draw in the square it is initially in."); } // end method main // Input command public static Commands inputCommand() { // store command as string String command; // input command do { System.out.print("Enter your command: "); command = in.next(); } while(!valid(command.charAt(0))); // end do-while // return command as enum value switch(command.charAt(0)) { case '0': return Commands.RESET; case '1': return Commands.UP; case '2': return Commands.DOWN; case '3': return Commands.RIGHT; case '4': return Commands.LEFT; case '5': // recover from bad input if(command.substring(1).isEmpty() || command.charAt(1) != ',' || command.substring(2).isEmpty()) return Commands.ERROR; move = parseInt(command.substring(2)); return Commands.FORWARD; case '6': return Commands.DISPLAY; case '7': return Commands.ERASE; case '8': return Commands.POSITION; case '9': return Commands.STOP; case 'r': return Commands.REVERSE; default: return Commands.ERROR; } // end switch } // end method inputCommand // Validate command public static boolean valid(char c) { for(int ch : commands) { if(c == ch) return true; } // end for // if reach this point, not valid return false; } // end method valid // Turn turtle public static Direction turn(Commands c, Direction d) { // turn turtle switch(d) { case UP: if(c == Commands.RIGHT) d = Direction.RIGHT; else d = Direction.LEFT; break; case RIGHT: if(c == Commands.RIGHT) d = Direction.DOWN; else d = Direction.UP; break; case DOWN: if(c == Commands.RIGHT) d = Direction.LEFT; else d = Direction.RIGHT; break; case LEFT: if(c == Commands.RIGHT) d = Direction.UP; else d = Direction.DOWN; break; } // end switch return d; } // end method turn // move turtle public static boolean[][] move(boolean[][] floor, Direction d, boolean draw, boolean erase) { // get direction to move turtle switch(d) { // move turtle up case UP: for(; move > 0; move--) { // draw, erase, or leave square draw(draw, erase, floor); // change position position[0]--; // return to caller if turtle hits wall if(position[0] <= 0) { // reset value position[0] = 0; // print warning System.out.println("Your turtle hit the wall and had to stop."); // stop moving turtle break; } // end if } // end for break; // move turtle down case DOWN: for(; move > 0; move--) { // draw, erase, or leave square draw(draw, erase, floor); // change position position[0]++; // make sure turtle does not walk through wall if(position[0] >= ROOM) { // reset value position[0] = ROOM-1; // print warning System.out.println("Your turtle hit the wall and had to stop."); // stop moving turtle break; } // end if } // end for break; // move turtle right case RIGHT: for(; move > 0; move--) { // draw, erase, or leave square draw(draw, erase, floor); // change position position[1]++; // make sure turtle does not walk through wall if(position[1] >= ROOM) { // reset value position[1] = ROOM-1; // print warning System.out.println("Your turtle hit the wall and had to stop."); // stop moving turtle break; } // end if } // end for break; // move turtle left case LEFT: for(; move > 0; move--) { // draw, erase, or leave square draw(draw, erase, floor); // change position position[1]--; // make sure turtle does not walk through wall if(position[1] <= 0) { // reset value position[1] = 0; // print warning System.out.println("Your turtle hit the wall and had to stop."); // stop moving turtle break; } // end if } // end for break; } // end switch // draw, erase, or leave square draw(draw, erase, floor); return floor; } // end method move // Draw, erase, or leave square public static boolean[][] draw(boolean draw, boolean erase, boolean[][] floor) { // if draw, turtle cannot leave square without drawing if(draw) floor[position[0]][position[1]] = true; // if erase, turtle cannot leave square without erasing if(erase) floor[position[0]][position[1]] = false; return floor; } // end method draw // Display array public static void display(boolean draw, boolean[][] array) { // loop through array for(boolean b[] : array) { for(boolean bb : b) { // draw picture if(bb) System.out.print("*"); else System.out.print(" "); } // end inner for // return at end of row System.out.println(); } // end outer for } // end method display // Reverse value (draw or erase square) of current position public static void reverse(boolean floor[][]) { floor[position[0]][position[1]] = !floor[position[0]][position[1]]; } // end method reverse // Show turtle's position public static void showPosition(Direction d) { // x-y coordinate System.out.printf("(%d, %d)\n", position[1], position[0]); // direction System.out.print("You are facing "); switch(d) { case UP: System.out.println("up."); break; case DOWN: System.out.println("down."); break; case RIGHT: System.out.println("right."); break; case LEFT: System.out.println("left."); break; } // end switch } // end method showPosition // Reset floor to blank public static boolean[][] reset(boolean[][] floor) { for(boolean b[] : floor) for(int i = 0; i < b.length; i++) b[i] = false; return floor; } // end method reset } // end class JavaApplication74 ``` I wrote this for my programming class about a month ago, so it isn't optimized for golf. I thought you might like to see my solution though. [Answer] # Python 2.7 (443? Points, 531 chars) --- Not really that well golfed and the display looks kind of horrid. Takes input from a file 'i' and runs printing out the output. I defined two new 'commands': 'CW' and 'CCW' which rotate the turtle 90 degrees clockwise and counter-clockwise respectivly. ``` b=[];u=1;s=r=0;p=[];d=[(1,0),(0,1),(-1,0),(0,-1)];l='0'; def q(): for i in b:print ''.join(i) def z(): r=0;p=[0]*2 for i in [0]*20: b.append([l]*20) def k(): b[p[1]][p[0]]=(('1',l)[s],b[p[1]][p[0]])[u] z() for c in open('i','r').read().split(): if c=="RESET":z() elif c=="UP":u=1 elif c=="DOWN":u=0 elif c=="FORWARD": k();p[0]+=d[r][0];p[1]+=d[r][1];k() elif c=="DRAW":s=0 elif c=="ERASE":s=1 elif c=="DISPLAY":q() elif c=="POSITION":print p elif c=="STOP":q();break elif c=="CW":r=(r+1)%4 elif c=="CCW":r=(r-1)%4 ``` --- Test Input: ``` DOWN FORWARD FORWARD CW FORWARD FORWARD CW FORWARD FORWARD CW FORWARD FORWARD CW UP FORWARD FORWARD FORWARD FORWARD DOWN FORWARD FORWARD CW FORWARD FORWARD CW FORWARD FORWARD CW FORWARD FORWARD CW ERASE FORWARD FORWARD STOP ``` Output: ``` 11100000000000000000 10101010000000000000 11101110000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 00000000000000000000 ``` [Answer] ## Java, 10 Points ``` import java.util.Scanner; import static java.lang.System.*; class Turtle{ public static void main(String...args){ Scanner s=new Scanner(in).useDelimiter("\\W+"); for( String board = "Lol I'm coding stuff".replaceAll(".","00000000000000000000\n"), input, x = "0", y = "0", rotation = "0", up = "true", mode = "1", nop ; null==(s.hasNext()?null:out.printf(board)) ; nop = ((input=s.next()).equals("RESET") ?(x = y = rotation = "0") + (up = "true") + (mode = "1") :input.equals("STOP") ?(s=new Scanner("")).toString() :input.equals("DISPLAY") ?out.printf(board).toString() :input.equals("POSITION") ?out.printf("(%s,%s)",x,y).toString() :"")+ (up = input.equals("UP") ?"true" :input.equals("DOWN") ?"false" :up)+ (rotation = input.equals("LEFT") ?""+((1+Integer.parseInt(rotation))%4) :input.equals("RIGHT") ?""+((3+Integer.parseInt(rotation))%4) :rotation)+ (mode = input.equals("DRAW") ?"1" :input.equals("ERASE") ?"0" :mode)+ (input.equals("FORWARD") ? ((x = Integer.parseInt(rotation)%2!=0 ?x :rotation.equals("0") ?Integer.parseInt(x)+1+"" :Integer.parseInt(x)-1+"")+ (y = Integer.parseInt(rotation)%2==0 ?y :rotation.equals("3") ?Integer.parseInt(y)+1+"" :Integer.parseInt(y)-1+"")) :"")+ (out.printf("\nx:%s y:%s rot:%s up:%s mode:%s input:%s\n",x,y,rotation,up,mode,input))+ (board = up.equals("false") ?board.replaceFirst("(?<=(?:[01]{20}\n){"+y+"}.{"+x+"}).",mode) :board)+ (Integer.parseInt(x)<0||Integer.parseInt(x)>20||Integer.parseInt(y)<0||Integer.parseInt(y)>20 ?(board = String.format("Error at position (%s,%s)",x,y)) + (s=new Scanner("")).toString() :"") ); } } ``` `Scanner s=new Scanner(in).useDelimiter("\\W+");` counts as 9 points, and the rest of the main method is just a for-loop's header and so it counts as 1 point. > > Loop header statements each only score one point > > > ]
[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/15872/edit). Closed 7 years ago. [Improve this question](/posts/15872/edit) You bought a tasty **Orange** in the supermarket and got **78** cents change. How many possible ways the supermarket guy can give you the change using 1,5,10 or 25 coins * **Input**: Change amount * **Output**: The number of possible ways to give the change. Order is not important 1,5 is same as 5,1 Win conditions: 1. **Best performance** 2. **Shortest code** *Also please add the result for 78 in your title.* [Answer] # Mathematica answer= 121, chars=~~74~~ 37 [121 ways to give change of $0.78, in pennies, nickels, dimes, and quarters.] **Method 1**: FroebeniusSolve This gives all the ways to solve the Frobenius equation `p + 5n + 10d + 25q = c`: ``` FrobeniusSolve[{1, 5, 10, 25}, #]& ``` The number of ways is (37 chars): ``` Length@FrobeniusSolve[{1,5,10,25},#]& ``` **Examples** Solutions are of the form, `{pennies, nickels, dimes, quarters}`: ``` FrobeniusSolve[{1, 5, 10, 25}, #]&[21] ``` > > {{1,0,2,0}, {1,2,1,0}, {1,4,0,0}, {6,1,1,0}, {6,3,0,0}, {11,0,1,0}, {11,2,0,0}, {16,1,0, 0}, {21,0,0,0}} > > > --- ``` Length@FrobeniusSolve[{1,5,10,25},#]&[78] ``` > > 121 > > > --- **How many ways are there to give change to (.01 to $2.50)?** ``` Length@FrobeniusSolve[{1,5,10,25},#]&/@Range[250] // AbsoluteTiming ``` Timing: 2.004 sec > > {2.00398, {{1, > 1}, {2, 1}, {3, 1}, {4, 1}, {5, 2}, {6, 2}, {7, 2}, {8, 2}, {9, > 2}, {10, 4}, {11, 4}, {12, 4}, {13, 4}, {14, 4}, {15, 6}, {16, > 6}, {17, 6}, {18, 6}, {19, 6}, {20, 9}, {21, 9}, {22, 9}, {23, > 9}, {24, 9}, {25, 13}, {26, 13}, {27, 13}, {28, 13}, {29, 13}, {30, > 18}, {31, 18}, {32, 18}, {33, 18}, {34, 18}, {35, 24}, {36, > 24}, {37, 24}, {38, 24}, {39, 24}, {40, 31}, {41, 31}, {42, > 31}, {43, 31}, {44, 31}, {45, 39}, {46, 39}, {47, 39}, {48, > 39}, {49, 39}, {50, 49}, {51, 49}, {52, 49}, {53, 49}, {54, > 49}, {55, 60}, {56, 60}, {57, 60}, {58, 60}, {59, 60}, {60, > 73}, {61, 73}, {62, 73}, {63, 73}, {64, 73}, {65, 87}, {66, > 87}, {67, 87}, {68, 87}, {69, 87}, {70, 103}, {71, 103}, {72, > 103}, {73, 103}, {74, 103}, {75, 121}, {76, 121}, {77, 121}, {78, > 121}, {79, 121}, {80, 141}, {81, 141}, {82, 141}, {83, 141}, {84, > 141}, {85, 163}, {86, 163}, {87, 163}, {88, 163}, {89, 163}, {90, > 187}, {91, 187}, {92, 187}, {93, 187}, {94, 187}, {95, 213}, {96, > 213}, {97, 213}, {98, 213}, {99, 213}, {100, 242}, {101, > 242}, {102, 242}, {103, 242}, {104, 242}, {105, 273}, {106, > 273}, {107, 273}, {108, 273}, {109, 273}, {110, 307}, {111, > 307}, {112, 307}, {113, 307}, {114, 307}, {115, 343}, {116, > 343}, {117, 343}, {118, 343}, {119, 343}, {120, 382}, {121, > 382}, {122, 382}, {123, 382}, {124, 382}, {125, 424}, {126, > 424}, {127, 424}, {128, 424}, {129, 424}, {130, 469}, {131, > 469}, {132, 469}, {133, 469}, {134, 469}, {135, 517}, {136, > 517}, {137, 517}, {138, 517}, {139, 517}, {140, 568}, {141, > 568}, {142, 568}, {143, 568}, {144, 568}, {145, 622}, {146, > 622}, {147, 622}, {148, 622}, {149, 622}, {150, 680}, {151, > 680}, {152, 680}, {153, 680}, {154, 680}, {155, 741}, {156, > 741}, {157, 741}, {158, 741}, {159, 741}, {160, 806}, {161, > 806}, {162, 806}, {163, 806}, {164, 806}, {165, 874}, {166, > 874}, {167, 874}, {168, 874}, {169, 874}, {170, 946}, {171, > 946}, {172, 946}, {173, 946}, {174, 946}, {175, 1022}, {176, > 1022}, {177, 1022}, {178, 1022}, {179, 1022}, {180, 1102}, {181, > 1102}, {182, 1102}, {183, 1102}, {184, 1102}, {185, 1186}, {186, > 1186}, {187, 1186}, {188, 1186}, {189, 1186}, {190, 1274}, {191, > 1274}, {192, 1274}, {193, 1274}, {194, 1274}, {195, 1366}, {196, > 1366}, {197, 1366}, {198, 1366}, {199, 1366}, {200, 1463}, {201, > 1463}, {202, 1463}, {203, 1463}, {204, 1463}, {205, 1564}, {206, > 1564}, {207, 1564}, {208, 1564}, {209, 1564}, {210, 1670}, {211, > 1670}, {212, 1670}, {213, 1670}, {214, 1670}, {215, 1780}, {216, > 1780}, {217, 1780}, {218, 1780}, {219, 1780}, {220, 1895}, {221, > 1895}, {222, 1895}, {223, 1895}, {224, 1895}, {225, 2015}, {226, > 2015}, {227, 2015}, {228, 2015}, {229, 2015}, {230, 2140}, {231, > 2140}, {232, 2140}, {233, 2140}, {234, 2140}, {235, 2270}, {236, > 2270}, {237, 2270}, {238, 2270}, {239, 2270}, {240, 2405}, {241, > 2405}, {242, 2405}, {243, 2405}, {244, 2405}, {245, 2545}, {246, > 2545}, {247, 2545}, {248, 2545}, {249, 2545}, {250, 2691}}} > > > --- **Method 2**: Solution by `Solve` (66 chars). This solves the same equation listed in Method 1, albeit by a more standard method, `Solve`: ``` f[c_]:=Solve[p +5n+10d+25q==c &&p>=0&&n>= 0&&d>=0&&q>= 0,{p,n,d,q},Integers] ``` The number of ways is (74 chars): ``` g@c_:= Length@Solve[p +5n+10d+25q==c &&p>=0&&n>= 0&&d>=0&&q>= 0,{p,n,d,q},Integers] ``` **Examples** ``` f[21] ``` > > {{p → 1, n → 0, d → 2, q → 0}, {p → 1, n → 2, d → 1, q → 0}, > {p → 1, n → 4, d → 0, q → 0}, {p → 6, n → 1, d → 1, q → 0}, {p → 6, n → 3, d → 0, q → 0}, > {p → 11, n → 0, d → 1, q → 0}, {p → 11, n → 2, d → 0, q → 0}, {p → 16, n → 1, > d → 0, q → 0}, {p → 21, n → 0, d → 0, q → 0}} > > > --- ``` Length[f[78]] ``` > > 121 > > > --- **How many ways are there to give change to (.01 to $2.50)?** ``` {#, g[#]} & /@ Range[250] // AbsoluteTiming ``` Timing: 4.72 sec [Answer] # K3 (kona), 121. Simple dynamic progamming. 57 chars. ``` cg:{*{+/x{(y _ x),y#0}/:y*!1+(#x)%y}/[(x#0),1;1 5 10 25]} cg 78 121 ``` Calculate all results up to 250 cents ``` {{+/x{(y _ x),y#0}/:y*!1+(#x)%y}/[(x#0),1;1 5 10 25]} 250 2691 2545 2545 2545 2545 2545 2405 2405 2405 2405 2405 2270 2270 2270 2270 2270 2140 2140 2140 2140 2140 2015 2015 2015 2015 2015 1895 1895 1895 1895 1895 1780 1780 1780 1780 1780 1670 1670 1670 1670 1670 1564 1564 1564 1564 1564 1463 1463 1463 1463 1463 1366 1366 1366 1366 1366 1274 1274 1274 1274 1274 1186 1186 1186 1186 1186 1102 1102 1102 1102 1102 1022 1022 1022 1022 1022 946 946 946 946 946 874 874 874 874 874 806 806 806 806 806 741 741 741 741 741 680 680 680 680 680 622 622 622 622 622 568 568 568 568 568 517 517 517 517 517 469 469 469 469 469 424 424 424 424 424 382 382 382 382 382 343 343 343 343 343 307 307 307 307 307 273 273 273 273 273 242 242 242 242 242 213 213 213 213 213 187 187 187 187 187 163 163 163 163 163 141 141 141 141 141 121 121 121 121 121 103 103 103 103 103 87 87 87 87 87 73 73 73 73 73 60 60 60 60 60 49 49 49 49 49 39 39 39 39 39 31 31 31 31 31 24 24 24 24 24 18 18 18 18 18 13 13 13 13 13 9 9 9 9 9 6 6 6 6 6 4 4 4 4 4 2 2 2 2 2 1 1 1 1 1 ``` Time to do so (in milliseconds) ``` \t {{+/x{(y _ x),y#0}/:y*!1+(#x)%y}/[(x#0),1;1 5 10 25]} 250 10 ``` Time to calculate up to 5000 cents: \t {{+/x{(y \_ x),y#0}/:y\*!1+(#x)%y}/[(x#0),1;1 5 10 25]} 5000 360 [Answer] result=121, javascript with memoize (160 chars) ``` c=[25,10,5,1] d=[[1],[1],[1],[1]] function f(x,y){ return d[x][y]||(d[x][y]=c.slice(x).reduce(function(i,j,k){ return i+(j>y?0:f(x+k,y-j)) },0)) } alert(f(0,prompt())) ``` result=121, javascript without memoize (126 chars) ``` c=[25,10,5,1] function f(x,y){ return y?c.slice(x).reduce(function(i,j,k){ return i+(j>y?0:f(x+k,y-j)) },0):1 } alert(f(0,prompt())) ``` [Answer] # J, 50 48 40 ### result: 121 ``` g=.{[:+//.@(*/)/0=1 5 10 25|"0 _ ]@i.@>: ``` Using generating functions approach. I'd say performance is not bad and can be easily made much better. ``` g 78 121 g 248 2545 ``` Timing: ``` time'g 78' 0.000254s ``` [Answer] ## Haskell - 51 / 69 Answer: 121 ``` _%0=1;[]%_=0;(x:y)%m=sum[y%(m-i*x)|i<-[0..m`div`x]] ``` Call notation: `[1,5,10,25]%78` Or more complete with an extra line: ``` f=([1,5,10,25]%) ``` The call is just: `f 78` Efficiency test (should be comparable with David Carraher): ``` main=mapM_(print.([1,5,10,25]%))[1..250] > ghc -O2 frob.hs && time ./frob - - ./frob 1.81s user 0.02s system 99% cpu 1.843 total ``` ]
[Question] [ Implement Stopwatch for typing Alphabets **Alphabets** = "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". **Note** * The program should run infinitely and should stop only when **Esc** button is pressed. * The stopwatch starts with keystroke "a" and ends with keystroke "z" * Output is the time taken to type the **Alphabets** correctly (ie. time take for **51 keystrokes**) * If an illegal character occurs then stopwatch should stop and print **"Failed"** * If a new record is set then print "**!!New record!!," TimeTaken** where, **TimeTaken** = time taken to print alphabets correctly. **Winner:** One with the shortest code. [Answer] Mathematica, 303 Here with white-space and expanded symbols. Everything happens in the `Switch` statement of the `EventHandler` where I pattern match `{pressed key, next letter}`. Might want to replace the `Quit` with something less sinister before hitting escape: ``` z := AbsoluteTime[]; f = "a"; y = Dynamic; DynamicModule[{ a = f~CharacterRange~"z", c = 1, d = f, r = \[Infinity]}, EventHandler[ y@d~InputField~String, "KeyDown" :> Switch[ {CurrentValue@"EventKey", a[[c]]}, {f ..}, t = z; c++; d = y@a[[c]], {"z" ..}, t = z - t; d = If[t < r, r = t; "!!New record!!,", ""] ~~ ToString@t; c = 1, {a_, a_}, c++, {"\[RawEscape]", _}, Quit[], _, d = "Failed"; c = 1]]] ``` [Answer] ## C, 181 Note that in order for this to work, your terminal must be setup to not buffer characters. One possible linux solution is [here](https://stackoverflow.com/questions/1798511/how-to-avoid-press-enter-with-any-getchar). Should this be considered part of my code? ``` double t,c,r=2<<29;main(l){for(;l<27&&96+l++==(c=getchar());)l==2&&time(&t);if(c==27)return;t=difftime(time(),t);l-27?puts("Failed"):t<r&&printf("!!New record!! %f\n",r=t);main(1);} ``` [Answer] ## Perl, 182 ``` use Term::ReadKey;ReadMode 3;@a=a..z;while(1){$c=getc;$s=time if!$i;last if$c eq"\e";if($c ne$a[$i++]){print"Failed";last}if($i==@a){print"!!New record!!,",(time-$s);last}}ReadMode 0 ``` There's probably room for improvement. I could also remove the `ReadMode 0` from the end, saving 10 chars. In addition, it's not clear to me if the use of `Term::ReadKey` is OK or not for the Code Golf. If it's not, then I don't think that this particular golf can be solved with Perl. Same program written properly and in a readable fashion: ``` use warnings; use strict; use Term::ReadKey; use Time::HiRes qw(time); ReadMode 3; my @a=('a'..'z'); my $i=0; my $s; while (1) { my $c=ReadKey(0); $s=time if !$i; last if $c eq "\e"; if ($c ne $a[$i++]) { print "Failed"; last; } if ($i==@a) { print "!!New record!!,",(time-$s); last; } } ReadMode 0; ``` ]
[Question] [ Given two binary numbers (strings containing 0s and 1s), perform operations on them, with one problem: **You must keep them in binary.** That means no going `binary(integer(n1)+integer(n2))` or anything like that. **Input:** Two binary numbers, `n1` and `n2`, and a number between 0 and 3, `o`, defining the operator. The two binary numbers will be the same length. **Output:** If `o` is 0, return `n1+n2` as a binary number. If `o` is 1, return `n1-n2` as a binary number. If `o` is 2, return `n1*n2` as a binary number. If `o` is 3, return `n1/n2` as a binary number, using floor division. **The output will not be the same length as the input. Please truncate all leading zeros.** If you implement Two's Complement, subtract 10% off your character count, up to a limit of 50. Truncate to `length(n1)+length(n2)` digits. **Test Cases:** `n1=01010, n2=10101, o=0: 11111` `n1=11110, n2=01010, o=1: 10100` `n1=0010, n2=1000, o=2: 10000` `n1=1011010, n2=0010001, o=3: 101` Shortest code wins. Good luck! [Answer] ## Python, 429 chars - 10% bonus = 386.1 Numbers are kept in [little endian](https://en.wikipedia.org/wiki/Endianness) order, which is stretching the rules a bit but makes for easier processing. Maximum number size is 32 bits. Addition is standard, subtraction is implemented by x-y = x+~y+1 (throwing away the carry out of the 32 bits), multiplication is done using the [Russian Peasant algorithm](https://web.archive.org/web/20180101093529/http://mathforum.org/dr.math/faq/faq.peasant.html), and division is done with repeated subtraction. ``` z,i='01' P=z*32 def A(x,y): r='';c=z for a,b in zip(x+P,y+P):k=(a+b+c).count(i);r+='0101'[k];c='0011'[k] return r[:32] S=lambda x,y:A(A(x,''.join(chr(ord(c)^1)for c in y+P)),i) def M(x,y): r='' while y: if y[0]==i:r=A(r,x) x=z+x;y=y[1:] return r def D(x,y): x=(x+P)[:32];y=(y+P)[:32];r='' while x[::-1]>=y[::-1]:r=A(r,i);x=S(x,y) return r def B(x,y,o):r=[A,S,M,D][o](x,y).rstrip(z)[:len(x)+len(y)];return[r,z][r==''] ``` `B` is the function of interest, here is its result on the test cases: ``` print B('01010','10101',0) 11111 print B('01111','01010',1) 00101 print B('0100','0001',2) 00001 print B('0101101','1000100',3) 101 ``` [Answer] ### Scala 785: Let's start with a famous quote of Bjarne Stroustrup, the inventor of C++, which in his great wisdom told us: > > Don't divide without necessity! > > > To make a submission to this fine question, we not only have to perform division - we have to implement it! Well - let's not talk about that. ``` object B{ val(l,o)=('1',"0") type S=String def n(v:S,c:S)=o*(c.size-v.size)+v def g(n:S,m:S)=((n zip m)find(a=>a._1!=a._2)).getOrElse((l,'0'))._1==l def a(x:S,y:S)=(((x zip y):\o)((n,m)=>{val s=Seq(m(0),n._1,n._2).filter(_==l).size Seq("00","01","10","11")(s)}+m.tail)) def P(x:S,y:S)=t(a(n(x,y),n(y,x))) def m(a:S,b:S)=(o/:a.zipWithIndex.filter(_._1==l).map(x=>b+o*(a.size-x._2-1)))(P) def x(x:S,y:S)=t(s(x,y)) def s(x:S,y:S)=((x zip y):\o)((n,m)=>{val s=Seq(if(n._1==l)'0'else l,m(0),n._2).filter(_==l).size Seq("01","00","11","10")(s)}+m.tail) def M(a:S,b:S)=if(b==o)a else t(x(n(a,b),n(b,a))) def d(n:S,m:S):S=if(g(n,m))P(D(M(n,m),m),"1")else o def D(a:S,b:S)=t(d(n(a,b),n(b,a))) def t(s:S)={val r=(s.substring(s.size-math.min(s.size,32))).replaceAll("^0*","") if(r=="")o else r} } ``` As usual, I have a less golfed version too, to explain 1 or 2 points (and this thread has much space left): ``` object BinArithmetic { def normalize (v: String, cmp: String) = "0" * (cmp.size - v.size) + v def ge(n:String, m:String)=((n zip m)find(a=>a._1!=a._2)).getOrElse(('1','0'))._1=='1' def greaterEqual (a:String, b:String): Boolean = ge (normalize (a, b), normalize (b, a)) def i(s:String)=if(s=="0")"0"else trim32(j(s)) def j(s:String):String=if(s.size==0)""else{if(s(0)=='1')'0'else'1'}+j(s.tail) def add (x:String, y: String): String = (((x zip y) :\ "0")((b, a) => { List (a(0), b._1, b._2).filter (_ == '1').size match { case 0 => "00" case 1 => "01" case 2 => "10" case 3 => "11" } }+a.tail)) def plus (a:String, b:String): String = { trim32 (add (normalize (a, b), normalize (b, a))) } def mul (a:String, b: String): String =("0" /: a.zipWithIndex.filter (_._1 == '1').map (x=> b+ "0" * (a.size - x._2 - 1)))(plus) def sub(x:String, y: String): String = trim32(s(x,y)) def s(x:String, y: String): String = ((x zip y) :\ "0")((b, ü) => { List (if(b._1=='1')'0' else '1', ü(0), b._2).filter (_ == '1').size match { case 0 => "01" case 1 => "00" case 2 => "11" case 3 => "10" } }+ü.tail) def minus (a:String, b:String): String = if (b=="0") a else { trim32 (sub (normalize (a, b), normalize (b, a))) } def d(n:String,m:String):String=if(ge(n,m))plus(div(minus(n,m),m),"1")else "0" def div (a:String, b:String): String = { trim32 (d (normalize (a, b), normalize (b, a))) } def trim32 (s: String): String = { val res = (s.substring (s.length - math.min (s.length, 32))).replaceAll ("^0*", "") if (res == "") "0" else res } } ``` Half way through golfing and obfuscating the code I changed the methods *add* and *s(ub)* a bit. Later I recognized that I didn't used the methods *i(nv)* and *j* which handled inversing numbers - my research showed that you can inverse a number as binary string, you can add "1" and so `sub (a, b)` should theoretically be the same as `add (add (a, inv(b)), "1")` but in practice, it isn't. :) There are 4 sorts of Methods: * preparation (normalize (a,b)) for example, which takes tow numbers, and makes them equal long * core calculation methods (add, sub, mul, div) * wrapping methods, which usually take (a,b) and normalize the call to the calculation methods with similar names (plus, minus) * finishing methods, which post process the result (trim32) The root is the add method. ``` def a(x:S, y: S) = (((x zip y) :\ "0")((n, m) => { val s=List (m(0), n._1, n._2).filter (_ == '1').size List ("00", "01", "10", "11") (s) }+m.tail)) ``` :\ is the right-fold operator. x zip y produces the list of pairs (10), (01), (11) from "101", "011", combines it with the overrun of the last operation, starting with no such overrun 0, counts the 1s in the result and produces a micro String like "10" from it. The 0 gets the growing part of the output, while 1 is the new overrun. You learned that at elementary school, didn't you? Now you remember! The mul - method is interesting: ``` def mul (a:String, b: String): String = ("0" /: a.zipWithIndex.filter (_._1 == '1').map (x=> b+ "0" * (a.size - x._2 - 1)))(plus) ``` From mul ("1010", "0110"), it takes a and zips with index ("1010"->0123 => 10, 01, 12, 03) filters those which are 1 in a: (10, 12) takes the b and adds (a.size=4 - (x.\_2=[0,2]) - 1) times a literal "0". 4-0-1 = 3, 4-2-1=1 => "0110"+"000", "0110"+"0". The result is put into the already defined plus operation, which is a normalized add. div is just subtraction combined with addition: ``` def d (n:String, m:String):String= if (greaterEqual (n,m)) plus (div (minus (n, m), m),"1") else "0" if (n > m) then n/m = (n-m)/m + 1 else 0 if (8 > 3) 8/3 = (8-3)/3 + 1 if (5 > 3) 8/3 = (5-3)/3 + 1 + 1 since ! (2 > 3) 8/3 = 0 + 1 + 1 ``` Sub is just similar implemented like add. Thanks to cyclic nature of ints, it doesn't really matter if the result is positive or negative. Maybe I try the 2s-complement part later again. Invocation ``` val ba = B ba.plus ( "01010", "10101") // 11111 res412: String = 11111 ba.minus ( "11110", "01010") // 10100 res413: String = 10100 ba.mul ( "0010", "1000") // 10000 res414: String = 10000 ba.div ("1011010", "0010001") // 101 res415: String = 101 ``` [Answer] ## Smalltalk Squeak 4.x flavour, 570 bytes **First Try**: define an operator in Object to evaluate any Object: ``` `x^self cull:x ``` We refine the eval message in Character to get the value: ``` `x^value ``` Then define bit ops with binary messages in Character: ``` &x^self class value:(x`1bitAnd:value) |x^self class value:(x`1bitOr:value) /x^self class value:((x`1bitXor:value)bitXor:$0`1) ``` / is xor operator, because it looks like the truth table ``` 01 10 ``` Then add two more messages in Character for repeating in a String and concatanating ``` *n^String new:n withAll:self ,s^(String with:self),s ``` Or my favourite hack to gain 2 chars: ``` ,s^'',(self`1+#[0]),s ``` Now create a new notation for accessing Array elements because `(x at:i)` costs two much. The operator @ could be used for at: and <@ would then means that it starts from the right (0-based) because our bit-Strings are big-endian. That would be ``` Object subclass:#At instanceVariableNames:'a i'classVariableNames:''poolDictionaries:''category:'' ``` In At, we would define two methods for initializing and accessing: ``` a:b i:j a:=b.i:=j `x^(a atWrap:0-i)`x ``` Since this costs to much, we will replace this nice thing by using Association. So we define the accessor message in String (or in SequenceableCollection) ``` <@i^self->i ``` And just define ` to retrieve the At value in Association: ``` `x^(key atWrap:0-value)`x ``` Now we are ready to implement the operations in String first, strip the $0 left: ``` \~c |x|(x:=self)size>1or:[^x].c=(x at:1)or:[^x].^x allButFirst\~c ``` Then the awfull bit sum +| (just a naive xor with carry) ``` +|y|x z c m n|(m:=(x:=self)size)<=(n:=y size)or:[^y+|x].c:=$0.z:=''.0to:m-1do:[:i|z:=c/(x<@i)/(y<@i),z.c:=c|(y<@i)&(x<@i)|(c&(y<@i))].m to:n-1do:[:i|z:=c/(y<@i),z.c:=c&(y<@i)].c=$0or:[^c,z].^z ``` Then the bit multiply \*| : ``` *|y|x z|x:=self.z:='0'.0to:y size-1do:[:i|$0/(y<@i)=$0or:[z:=z+|x].x:=x,$0].^z ``` Then the bit subtraction -| is using two complement. Result is truncated to receiver length, so it must not be negative: ``` -|y|n x|n:=(x:=self\~$0)size.^(x+|'1'+|($1*n,(y collect:[:c|c/$1])))last:n ``` Then a test <| for bit less than: ``` <|y|m n|m:=self size.n:=y size.^m<n or:[m=n and:[self<y]] ``` Then the bit division /| (by subtraction) - this will also raise a zero divide exception when appropriate: ``` /|z| x y q t n|y:=z\~$0.x:=self\~$0.y='0'and:[1/0].n:=0max:x size-y size.q:=''.[n>=0]whileTrue:[t:=y,($0*n).n:=n-1.q:=q,(x<|t ifTrue:[$0]ifFalse:[x:=x-|t\~$0.$1])].^q ``` And finally the operation encoding - we reuse <@ to access right to left 0-based: ``` y:y o:o|x|x:=self.^({[x/|y].[x*|y].[x-|y].[x+|y]}<@o)`1\~$0 ``` The small test suite: ``` self assert: ('01010' y:'10101' o:0) = '11111'. self assert:('11110' y:'01010' o:1) = '10100'. self assert:('0010' y:'1000' o:2) = '10000'. self assert:('1011010' y:'0010001' o:3) = '101'. ``` The longer test suite: ``` | n | n := 100. 0 to: n do: [:i|0 to:n do:[:j | self assert: (i printStringBase:2)+|(j printStringBase:2)\~$0=(i+j printStringBase:2)]]. 0 to: n do: [:i|0 to:n do:[:j | self assert: (i printStringBase:2)*|(j printStringBase:2)\~$0=(i*j printStringBase:2)]]. 0 to: n do: [:i|0 to:i do:[:j | self assert: (i printStringBase:2)-|(j printStringBase:2)\~$0=(i-j printStringBase:2)]]. 0 to: n do: [:i|1 to:n do:[:j | self assert: (i printStringBase:2)/|(j printStringBase:2)\~$0=(i//j printStringBase:2)]]. ``` And the score is given by: ``` {Object>>#`. SequenceableCollection>>#<@. Association>>#`} , ({#`. #*. #&. #|. #/. #,} collect:[:selector | Character>>selector]) , ({#\~. #+|. #-|. #*|. #/|. #<|. #y:o:} collect:[:selector | String>>selector]) detectSum: [:method | method getSource size]. ``` Which is 921 chars... --- We can do much better if we use Boolean instead of Integer. They can be easily transformed in character: Implement in True: ``` c^$1 ``` And in False: ``` c^$0 ``` Now transform a binary Character in Boolean, implement in Character: ``` b^self=$1 ``` Now logical operations are expressed much simply in Character: ``` &x^(x b&self b)c |x^(x b|self b)c /x^(x b xor:self b)c ``` Plus the two operations to repeat and concatenate: ``` *n^String new:n withAll:self ,s^self*1,s ``` Now, the message size is long, let's create a shorter binary message in String: ``` \n^self size-n ``` We shorten the message for stripping leading chars in String: ``` ~c|x|(x:=self)\1<1or:[c~=(x at:1)or:[^(x last:x\1)~c]] ``` Now we'd better implement binary >= rather than < for division, let's call it >~ in String: ``` >~y^self\0>(y\0)or:[self\0=(y\0)and:[self>=y]] ``` Now back to the operations, we will call them + - \* / even if we have to override existing methods in String (they are presumably not used): ``` y:y o:o|x|x:=self.^({[x/y].[x*y].[x-y].[x+y]}<@o)value~$0 +y|x z c m n|(m:=(x:=self)\1)<=(n:=y\1)or:[^y+x].c:=$0.z:=''.0to:m do:[:i|z:=c/(x<@i)/(y<@i),z.c:=c|(y<@i)&(x<@i)|(c&(y<@i))].m+1to:n do:[:i|z:=c/(y<@i),z.c:=c&(y<@i)].c=$0or:[^c,z].^z -y|n x|n:=(x:=self~$0)\0.^(x+'1'+($1*n,(y collect:[:c|c/$1])))last:n *y|z|z:='0'.0to:y\1do:[:i|(y<@i)b and:[z:=self,($0*i)+z]].^z /z| x y q t|y:=z~$0.x:=self~$0.y='0'and:[1/0].q:=''.(0max:x\0-(y\0))to:0by:-1do:[:n|t:=y,($0*n).q:=q,(x>~t and:[x:=x-t~$0.$1b])c].^q ``` The score is now ``` methods := {SequenceableCollection>>#<@. True>>#c. False>>#c} , ({#b. #*. #&. #|. #/. #,} collect:[:selector | Character>>selector]) , ({#\. #~. #+. #-. #*. #/. #>~. #y:o:} collect:[:selector | String>>selector]). methods detectSum: [:method | method getSource size]. ``` That is 742 chars Another snippet to browse our code alltogether: ``` methods do: [:e | e methodClass organization classify: e selector under: '*CodeGolfBinaryArithmetic']. SystemNavigation default browseMessageList: (methods collect: [:e | MethodReference class: e methodClass selector: e selector]) name: 'CodeGolfBinaryArithmetic' ``` We can further reduce the division to repeated subtraction (slower): ``` /z|x y|y:=z~$0.x:=self~$0.y='0'and:[1/0].x>~y or:[^'0'].^x-y/y+'1' ``` We can also omit 1/0 for ZeroDivide exception, anyway the result will be infinite on a computer with infinite memory after an infinite time: ``` /z|x y|y:=z~$0.x:=self~$0.x>~y or:[^'0'].^x-y/y+'1' ``` We can also reduce addition to a recursive form: ``` +y|x|(x:=self)\0>0or:[^y].y\0>0or:[^x].^x<@0&(y<@0)*1+(x first:x\1)+(y first:y\1),(x<@0/(y<@0)) ``` And we now are at 570 chars... Not bad for Smalltalk. ]
[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 1 year ago. [Improve this question](/posts/5391/edit) An IDE developer has hired you to write a program that generates (by printing to stdout) **n** lines of randomly generated code. They will use your program to create sample code for use in marketing their newest compiler. **Rules:** Your randomly generated output code: * must not be the same each execution (for the same **n** parameter) * must be written in the same language as your program * must be able to be successfully compiled without errors or warnings (including "variable not used" messages, if your language includes them) * should use a variety of the language's built-in features * should (where appropriate) follow the language's most popular style guide. For example, [PEP-8](http://www.python.org/dev/peps/pep-0008/) for Python * should, if n is larger than 20, have functions. Functions should be limited to a length that follows the language's style guide * does not have to have comments (but the developer will be impressed if it does!) * may include a single blank line between code blocks for clarity You can use an external dictionary to allow generation of function/variable names, and lists of standard functions/libraries for your language. If your program uses these, please include a link (to a pastebin if your dictionary is custom written for this task) Please include a few sample outputs to demonstrate your program's capabilities. **Winning:** The winning program should implement all the above features, and generate realistic code without sacrificing execution time or program length (to a huge degree - this isn't golf). The winner will be chosen by community vote from entries received before **1st May 2012**. Voting should be based upon realism, variety, creativity and adherence to the criteria above. Good luck! [Answer] Did it in Brainfuck! I had a bit of trouble generating random numbers. I hoped something simple like a [LFSR](http://en.wikipedia.org/wiki/Linear_feedback_shift_register) could give me a fairly decent looking sequence, but I found it looped too quickly and gave boring output. I resorted to using a RNG found [here,](http://esolangs.org/wiki/Brainfuck_algorithms#x_.3D_pseudo-random_number) which actually takes quite a long time to run. Since BF has no capacity to get any source of entropy from the operating system, I first have the user input any text (I pound on they keyboard) to seed the RNG. After that it takes the number of lines and outputs random BF, using 16 hard-coded subsequences. ``` get random seed input till newline (10) >>>+[,[<+>>+>>>>>>+++<<<<<<<-]>[<+>-]<----------] get number of lines <<<,[->> Map: n nesting seed lineCount _ _ _ _ _ _ randh randl mod by 32 to get char count for this line [>+>+<<-]>>[<<+>>-]>++++[<++++++++>-]<< [->-[>+>>]>[+[-<+>]>+>>]<<<<<] >[-]>>[-]<[<<+>>-] loop that many times <<[-< generate next 'random' number >>[-]>[-]>[-]>[-]>[-]>[-]>[<<<<<<+>>>>>>-]>[<<<<<<+>>>>>>-]<<<<+++++++ [<+++++++++++>-]<[<<[>>>>>>+<<<+<<<-]>>>[<<<+>>>-]<<[>>>>>+<<<+>+<<<-] >>>[<<<+>>>-]<[>>>>+[<<<+>+>>-]<<[>>+<<-]+<[>-<[-]]>[>+<-]<<-]<-]+++++ +[>++++++++<-]>-[<<[>>>>>+<<<<+<-]>[<+>-]>-]<<<[-]>[-]+++++[<+++++>-]< [>>>>>>>+[<<<<<<+>+>>>>>-]<<<<<[>>>>>+<<<<<-]+<[>-<[-]]>[>>>>+<<<<-]<< -]++++++[>>>>>>+++++++++<<<<<<-]>>>>>>[<<<<<<<<+>>+>>>>>>-]<<<<<<[>>>> >>+<<<<<<-]<< seed is now next number in sequence copy and mod 16 [>>+>+<<<-]>>>[<<<+>>>-]>++++[<++++>-]<< [->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[-]< now we have bottom 4 bits of data; pick an output sequence: #00: + [<+<+>>-]<[>+<-]+<[>-<[-]]>[-[-]>[-]< >++++++[<+++++++>-]<+.[-]]> #01: + -[<+<+>>-]<[>+<-]+<[>-<[-]]>[-[-]>[-]< >++++++[<+++++++>-]<+.[-]]> #02: - -[<+<+>>-]<[>+<-]+<[>-<[-]]>[- [-]>[-]< >+++++[<+++++++++>-]<.[-]]> #03: [->-[>+>>]>[+[-<+>]>+>>]<<<<<] -[<+<+>>-]<[>+<-]+<[>-<[-]]>[-[-]>[-]< >+++++++[<+++++++++++++>-]<. >+++++[<--------->-]<-. +++++++++++++++++. -----------------. >+++++[<+++++++++>-]<+. >++++[<------->-]<-. >+++[<------>-]<-. >+++[<++++++>-]<+.. >+++++[<++++++>-]<+. >+++++[<------>-]<-. >++++[<+++++++>-]<+. >++++++[<-------->-]<. >++++++[<++++++++>-]<. >+++++[<--------->-]<-. +++++++++++++++. -----------------. >+++[<++++++>-]<+. >+++++[<++++++>-]<+. >+++++[<------>-]<-. >+++[<------>-]<-. >+++[<++++++>-]<+.. >+++++[<++++++>-]<+. >++++[<-------->-]<-.....>++++[<++++++++>-]<+.[-]]> #04: < -[<+<+>>-]<[>+<-]+<[>-<[-]]>[- [-]>[-]< >++++++[<++++++++++>-]<.[-]]> #05: < -[<+<+>>-]<[>+<-]+<[>-<[-]]>[- [-]>[-]< >++++++[<++++++++++>-]<.[-]]> #06: > -[<+<+>>-]<[>+<-]+<[>-<[-]]>[- ----[>+<----]>---.[-]<]> #07: x y z -[<+<+>>-]<[>+<-]+<[>-<[-]]>[-[-]>[-]< >++++[<++++++++>-]<. >++++++++[<+++++++++++>-]<. >++++++++[<----------->-]<. >++++++++[<+++++++++++>-]<+. >++++++++[<----------->-]<-. >+++++++++[<++++++++++>-]<.[-]]> #08: [ -[<+<+>>-]<[>+<-]+<[>-<[-]]>[- [-]>[-]< >+++++++[<+++++++++++++>-]<.[-]<<<<+>>>> ]> #09: [ -[<+<+>>-]<[>+<-]+<[>-<[-]]>[- [-]>[-]< >+++++++[<+++++++++++++>-]<.[-]<<<<+>>>> ]> #10: ++[>+<------]> -[<+<+>>-]<[>+<-]+<[>-<[-]]>[- [-]>[-]< >++++++[<+++++++>-]<+.. >++++++[<++++++++>-]<. >++++[<------->-]<-. >+++[<------>-]<-.+++++++++++++++++. ---------------......>++++++[<++++++++>-]<. >+++++[<------>-]<-.[-]]> #11: +<->++ -[<+<+>>-]<[>+<-]+<[>-<[-]]>[- [-]>[-]< >++++++[<+++++++>-]<+. +++++++++++++++++. ---------------. +++++++++++++++++. >+++[<------>-]<-..[-]]> #12: . -[<+<+>>-]<[>+<-]+<[>-<[-]]>[-[-]>[-]< >+++++[<+++++++++>-]<+.[-]]> #13: , -[<+<+>>-]<[>+<-]+<[>-<[-]]>[-[-]>[-]< >++++[<+++++++++++>-]<. [-]]> #14: [<+<+>>-] -[<+<+>>-]<[>+<-]+<[>-<[-]]>[- [-]>[-]< >+++++++[<+++++++++++++>-]<. >+++++[<------>-]<-. -----------------. +++++++++++++++++. -----------------. >+++[<++++++>-]<+..-----------------. >++++++[<++++++++>-]<.[-]]> #15: [-] -[<+<+>>-]<[>+<-]+<[>-<[-]]>[-[-]>[-]< >+++++++[<+++++++++++++>-]<. >+++++[<--------->-]<-. >++++++[<++++++++>-]<.[-]]> [-]<<< ] >+++++++[<+++++++++++++>-]<++<<[>>.<<-]>>[-]<<++++++++++.[-]< ] ``` Output for input ``` qqq 10 ``` is ``` [<+<+>>-]<[-] x y z.< x y z<.++[>+<------]>[[-]+<. x y z++[>+<------]>.+<->++[->-[>+>>]>[+[-<+>]>+>>]<<<<<][+[<+<+>>-] x y z[<+<+>>-][<+<+>>-][<+<+>>-]++[>+<------]>+<->++]] -[->-[>+>>]>[+[-<+>]>+>>]<<<<<][<+<+>>-][-][ x y z++[>+<------]>,[-][->-[>+>>]>[+[-<+>]>+>>]<<<<<]-] <[->-[>+>>]>[+[-<+>]>+>>]<<<<<] +,++[>+<------]>-[[-]+<->++[[->-[>+>>]>[+[-<+>]>+>>]<<<<<],++[>+<------]>[->-[>+>>]>[+[-<+>]>+>>]<<<<<]++[>+<------]>.[+ x y z+<]]] ++[>+<------]>++-[-]-[-]+,[->-[>+>>]>[+[-<+>]>+>>]<<<<<][->-[>+>>]>[+[-<+>]>+>>]<<<<<][->-[>+>>]>[+[-<+>]>+>>]<<<<<]+,+[<++[>+<------]>,-+<->++] -[<+<+>>-]-., x y z[ x y z<[<+<+>>-]< x y z<[+<->+++<->++-++[>+<------]>+<->+++[[<-[-][+<->++]]]]] [<+<+>>-]++[<+<+>>-]-<<[-]+<->++<[] ,[->-[>+>>]>[+[-<+>]>+>>]<<<<<]++[>+<------]>++<->+++<->++[<+<+>>-]< ++[>+<------]>[<+<+>>-][+<->+++<->++[[->-[>+>>]>[+[-<+>]>+>>]<<<<<]<[<+<+>>-]++[>+<------]> x y z x y z<..[[-][<+<+>>-],[<+<+>>-]+,]]] -, x y z<<[<[->-[>+>>]>[+[-<+>]>+>>]<<<<<].[,<-]] ``` and it runs in about 2 minutes on my box. Output contains entirety of BF syntax, including comments, and it well formed. ]
[Question] [ It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, [visit the help center](/help/reopen-questions). Closed 10 years ago. This comes from one of my favorite interview questions, though apparently it is now a fairly well-known puzzle. I have no way of knowing, but if you have already heard the answer it would be polite to let others try instead. ### Task: Write a function that takes as input a singly-linked list and returns true if it loops back on itself, and false if it terminates somewhere. Here's some example code in C as a starting point so you can see what I mean, but feel free to write your answer in whatever language you like: ``` struct node { void *value; struct node *next; }; int has_loops(struct node *first) { /* write your own loop detection here */ } ``` ### Hints: There is a way to make this function run in O(n) time with a constant amount of extra memory. Good on you if you figure it out, but any working answer deserves some upvotes in my book. [Answer] ## C, non-golfed The idea is to have to pointers p1 and p2 that traverse the list. p2 moves twice as fast as p1. If p2 reaches p1 at some point then there is a loop. Here is the C code (not tested, though). ``` struct node { void *value; struct node *next; }; int has_loops(struct node *p) { struct node *p1 = p, *p2 = p->next; if (!p2) return 0; while (p1 != p2) { // p1 goes one step p1 = p1->next; if (!p1) return 0; // p2 goes two steps p2 = p2->next; if (!p2) return 0; p2 = p2->next; if (!p2) return 0; } return 1; } ``` [Answer] Since the solution is already in the open, I think it's fair to step in now with Brent's algorithm, which is the one I'm familiar with from integer factorisation. ``` #define bool int #define false 0 #define true 1 bool has_loops(struct node *first) { if (!first) return false; struct node *a = first, *b = first; int step = 1; while (true) { for (int i = 0; i < step; i++) { b = b->next; if (!b) return false; if (a == b) return true; } a = a->next; if ((step << 1) > 0) step <<= 1; } } ``` [Answer] ## Ada The "Floyd's Cycle-Finding Algorithm" is the best solution. It's also called "The Tortoise and the Hare Algorithm". linked\_lists.ads: ``` generic type Element_Type is private; package Linked_Lists is type Node is private; type List is private; function Has_Loops (L : List) return Boolean; private type List is access Node; type Node is record Value : Element_Type; Next : List; end record; end Linked_Lists; ``` linked\_lists.adb: ``` package body Linked_Lists is function Has_Loops (L : List) return Boolean is Slow_Iterator : List := L; Fast_Iterator : List := null; begin -- if list has a second element, set fast iterator start point if L.Next /= null then Fast_Iterator := L.Next; end if; while Fast_Iterator /= null loop -- move slow iterator one step -- guaranteed to be /= null, since it is behind fast iterator Slow_Iterator := Slow_Iterator.Next; -- move fast iterator one step -- guaranteed to be valid, since while catches null Fast_Iterator := Fast_Iterator.Next; -- move fast iterator another step -- null check necessary if Fast_Iterator /= null then Fast_Iterator := Fast_Iterator.Next; end if; -- if fast iterator arrived at slow iterator -> loop detected if Fast_Iterator = Slow_Iterator then return True; end if; end loop; -- fast iterator arrived end, no loop present. return False; end Has_Loops; end Linked_Lists; ``` here is the implementation of the Brent algorithm: ``` package body Linked_Lists is function Has_Loops (L : List) return Boolean is Turtle : List := L; Rabbit : List := L; Steps : Natural := 0; Limit : Positive := 2; begin -- is rabbit at end? while Rabbit /= null loop -- increment rabbit Rabbit := Rabbit.Next; -- increment step counter Steps := Steps + 1; -- did rabbit meet turtle? if Turtle = Rabbit then -- LOOP! return True; end if; -- is it time to move turtle? if Steps = Limit then Steps := 0; Limit := Limit * 2; -- teleport the turtle Turtle := Rabbit; end if; end loop; -- rabbit has reached the end return False; end Has_Loops; end Linked_Lists; ``` [Answer] ## Haskell Naive algorithm: ``` import Data.Set (Set) import qualified Data.Set as Set type Id = Integer data Node a = Node { getValue :: a, getId :: Id } hasLoop :: [Node a] -> Bool hasLoop = hasLoop' Set.empty hasLoop' :: Set Id => [Node a] -> Bool hasLoop' set xs = case ns of [] -> False x:xs' -> let ident = getId x set' = Set.insert ident set in if Set.member ident set then True else hasLoop' set' xs' ``` Floyd's Cycle-Finding Algorithm: ``` import Control.Monad (join) import Control.Monad.Instances () import Data.Function (on) import Data.Maybe (listToMaybe) type Id = Integer data Node a = Node { getValue :: a, getId :: Id } next :: [a] -> Maybe [a] next [] = Nothing next (_:xs) = Just xs nexts :: [a] -> [a] -> (Maybe [a], Maybe [a]) nexts xs ys = (next xs, next $ next ys) hasLoop :: [Node a] -> Bool hasLoop = uncurry hasLoops' . join nexts hasLoop' :: Maybe [Node a] -> Maybe [Node a] -> Bool hasLoop' (Just xs) (Just ys) | on (==) (getId . listToMaybe) xs ys = True | otherwise = uncurry hasLoop' $ nexts xs ys hasLoop' _ Nothing = False hasLoop' Nothing _ = False -- not needed, but there for case completeness ``` [Answer] # D This is a solution I thought of myself. It runs in O(n) and uses O(1) memory. What I'm doing is simply iterating through the list and reversing all the pointers. If the list contains a cycle, you'll eventually end up at the beginning of the list and otherwise you end up at the end, which is somewhere else if your list is longer than 1. Now you've determined the result you can restore the list by simply reversing the pointers again. Here is my code and a test: ``` import std.stdio; // The list structure. struct node(T) { T data; node!T * next; this(T data) {this.data = data; next = null;} } bool hasLoop(T)(node!T * first) { // List shorter than two nodes has no loops. if(!first || !first.next) { return false; } // Keep iterating through the list, while reversing the pointers. node!T * previous = null, current = first; while(current) { auto next = current.next; current.next = previous; previous = current; current = next; } // If the last node was the beginning of the list, there was a cycle. // Otherwise, there are none. bool result = previous == first; // Do the reversal again to restore the list to its original state. current = previous; previous = null; while(current) { auto next = current.next; current.next = previous; previous = current; current = next; } // Done! return result; } // Test unittest { // Build a list. int[] elems = [1,2,3,4,5,6,7,8,42]; auto list = new node!int(elems[0]); auto curr = list; foreach(x; elems[1..$]) { curr.next = new node!int(x); curr = curr.next; } // Outcomment the line below to test for a non-cycle list. curr.next = list.next.next.next; // Do cycle check. writeln(hasLoop(list) ? "yes" : "no"); // Confirm the list is still correct. curr = list; for(int i = 0; i < elems.length; ++i, curr = curr.next) { assert(curr.data == elems[i]); } } ``` ]
[Question] [ Write a program/script that decompresses and passes any compressed data appended at the end of the binary/file as standard input to a program specified as arguments. ``` $ gzip --to-stdout input >> your_solution $ your_solution program args... ``` should have the same effects as: ``` $ program args... < input ``` [Answer] **zsh: (20 chars)** *Edit:* because zsh doesn't re-parse arguments like bash, I can lose the `"`s and it will still work with spaces in args ``` #!/usr/bin/zsh tail -n+3 $0|zcat|$@ ``` **Bash (25 24 chars not including shebang line)** ``` #!/bin/bash tail -n+3 "$0"|zcat|"$@" ``` [Answer] **C (251 chars)** Way too long to win, but I wanted to do one in a compiled language to make things interesting. (It turned out to be quite straightforward actually). It's probably very compiler-dependent (I used GCC 4.4.3 with the default settings on 32-bit Linux) ``` #include<stdio.h> #define q(x)FILE*x=x##open( #define w strcpy(o+b o,s=7462;char b[99];main(int i,char**a){q(f)*a,"r");while(--s)fgetc(f); for(o=0;++s<i;o++[b]=32)w,a[s]),o+=strlen(a[s]);w,"|zcat");q(p)b,"w"); for(;~(i=fgetc(f));fputc(i,p));fclose(p);} ``` [Answer] ## Bash (OP solution) This is an example I came up with: ``` cat $0 | awk 'NR > 1' | zcat | $* ; exit ``` ]
[Question] [ Unsurprisingly, [fibonacci primes](https://en.wikipedia.org/wiki/Fibonacci_prime) are primes that are also Fibonacci numbers. There are currently 34 known Fibonacci primes and an additional 15 probable Fibonacci primes. For the purpose of this challenge, the Fibonacci numbers are the sequence \$F\_n\$ defined as \$F\_1 = 1\$, \$F\_2 = 1\$, and \$F\_n = F\_{n-1} + F\_{n-2}\$, and a number is considered prime if it passes a probabilistic prime test with a probability of being incorrect of less than \$2^{-32}\$. For example, since a \$k\$ round Miller-Rabin test has an error probability of \$4^{-k}\$, a 16 round Miller-Rabin test is sufficient to prove primality for the purpose of this challenge. ## Submissions: The goal of this challenge is to write a full program that calculates every Fibonacci prime and its index in the Fibonacci series as fast as possible. Submissions shall be a full program, complete with instructions for building and running it. Submissions must be in a language freely available for noncommercial use and capable of running on Windows 10, and users must be prepared to provide installation instructions for that language. External libraries are permitted, with the same caveats that apply to languages. Primes will be output by writing them as base 10 integers to stdout in ascending order in the format ``` index,prime\n ``` where `\n` is the newline character. The numbers can have extraneous leading/trailing whitespace other than the newline character. ## Scoring The programs will be run on an Intel(R) Core(TM) i5-8365U CPU with 8 threads, avx-2 support, and 24 Gigabytes of ram. The largest prime that can be correctly reached in one minute wins. Tiebreaker is the time taken to reach the largest value. Programs that tamper with my computer or the testing program will be disqualified. Programs that error or otherwise fail to produce the correct output will be judged based on the furthest Fibonacci prime reached before they failed. ## Results Sorry for the delay, getting Anders Kaseorg's entry to build properly wound up being way harder than it needed to be. ``` Results: anders_kaseorg: num: 27 time: 44.6317962s aleph_alpha: num: 24 time: 22.6188601s example: num: 12 time: 23.2418081s ``` see also: [A005478](https://oeis.org/A005478), [A001605](https://oeis.org/A001605) The test program can be found [here](https://github.com/Aiden2207/fibonacci_primes). Additionally, there is an example program [here](https://github.com/Aiden2207/fibonacci_primes/tree/master/competitors/example). [Answer] # Rust, \$F\_{14431}\$ in ≈ 58 s (Unofficial estimate based on the expected CPU performance ratio.) After special-casing \$F\_3, F\_4\$, this tests every prime-indexed Fibonacci number with the GMP [`mpz_probab_prime_p`](https://gmplib.org/manual/Number-Theoretic-Functions#index-mpz_005fprobab_005fprime_005fp) function, which performs a [Baillie–PSW](https://en.wikipedia.org/wiki/Baillie%E2%80%93PSW_primality_test) test and `rep - 24` [Miller–Rabin](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test) iterations. Since Baillie-PSW has no proven error bound, I pass `24 + 16` to ensure 16 Miller–Rabin iterations. Build with `cargo build --release` and run `target/release/fibprimes`. **`Cargo.toml`** ``` [package] name = "fibprimes" version = "0.1.0" edition = "2021" [dependencies] pariter = "0.5.1" rug = { version = "1.16.0", features = ["integer"], default-features = false } ``` **`src/main.rs`** ``` use pariter::IteratorExt; use rug::{integer::IsPrime, Integer}; use std::iter; fn main() { println!("3,2"); println!("4,3"); let mut fib0 = Integer::from(1); let mut fib1 = Integer::from(2); let mut n = Integer::from(3); for (n, fib) in iter::from_fn(move || { let n1 = Integer::from(n.next_prime_ref()); while n != n1 { fib0 += &fib1; fib1 += &fib0; n += 2; } Some((n.clone(), fib1.clone())) }) .parallel_filter(|(_, fib)| fib.is_probably_prime(24 + 16) != IsPrime::No) { println!("{n},{fib}"); } } ``` [Answer] # C + [PARI/GP](http://pari.math.u-bordeaux.fr/)'s C library, \$F\_{9677}\$ in 25s on my computer ``` #include <pari/pari.h> void f(long n) { GEN a = fibo(n); if (ispseudoprime(a, 16)) pari_printf("%d,%Ps\n", n, a); return; } int main() { pari_init(8000000, 500000); f(3); f(4); long n; forprime_t iter; u_forprime_init(&iter, 5, ULONG_MAX); while (n = u_forprime_next(&iter)) f(n); return 0; } ``` If you are using Ubuntu or Debian, you need to install the package `libpari-dev`. For Arch Linux, `pari-gp` is enough. Compiles with `gcc -O3 filename.c -lpari`. [Answer] # Python, gmpy2, \$F\_{9677}\$ in 27s on my computer. Same trick as [@Anders Kaseorg's Rust answer](https://codegolf.stackexchange.com/a/248750/110802). ``` import time import gmpy2 from gmpy2 import mpz # from itertools import count import time # set the precision for probable prime test gmpy2.get_context().precision = 24 + 16 def next_prime(n): candidate = n + 1 if n % 2 == 0 else n + 2 while not gmpy2.is_prime(candidate): candidate += 2 return candidate def fib_prime_gen(): fib0, fib1 = mpz(3), mpz(5) n = mpz(5) yield n, fib1 while True: fib0, fib1 = fib0 + fib1, (fib1 << 1) + fib0 n += 2 # print(f"{n=} {fib1=}") if gmpy2.is_prime(fib1): yield n, fib1 print("3,2") print("4,3") start_time=time.time() for n, fib in fib_prime_gen(): print(f"{n},{fib}") if n>=9677: break print(f"F9677 in {time.time()-start_time} seconds.") ``` ]
[Question] [ Design a function or program that, when run normally, outputs the triangular numbers. However, when any single character is deleted, the program/function should not function in the original programming language, but instead produce the triangular numbers in one other programming language. ## Scoring Your score will be the number of characters in your program for which the program is not valid in your second chosen language. Lowest score wins, tiebreaker is byte count. ## Specific Rules You may infinitely output triangular numbers, produce a list of the first N with a positive integer input N, or produce the Nth triangular number. Each of the programs may have different behavior in this respect. Your original program may run in the second language, but it can't produce the correct output. Your programs may also output in different bases/use different indexing/use different output formats, as long as that format would be valid in a [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge. No more than 20% of your characters, rounded down, may be invalid. An invalid character is any character that, when removed, creates no program or function that outputs triangular numbers in your second chosen language. Any time you remove a character from the original code, it should break it. Separate versions of programming languages ARE permitted to be treated as different languages. [Answer] # [Perl 5](https://www.perl.org/) `-M5.010` + [A Pear Tree](https://esolangs.org/wiki/A_Pear_Tree), score 0, tiebreak score 96 bytes ``` $_='{length==86&&6&&say$T0+=++$b9F;redo}{print$tYC+=++$nKy;redo}#{print$tYC+=++$nKy;redo}#';eval ``` [Try it online! (Perl)](https://tio.run/##K0gtyjH9/18l3la9Oic1L70kw9bWwkxNDYiKEytVQgy0bbW1VZIs3ayLUlPya6sLijLzSlRKIp3B4nnelRBxZZwS6tapZYk5////yy8oyczPK/6v62uqZ2BoAAA "Perl 5 – Try It Online") [Try it online! (A Pear Tree)](https://tio.run/##S9QtSE0s0i0pSk39/18l3la9Oic1L70kw9bWwkxNDYiKEytVQgy0bbW1VZIs3ayLUlPya6sLijLzSlRKIp3B4nnelRBxZZwS6tapZYk5//8DAA "A Pear Tree – Try It Online") A Pear Tree was designed for [polyglot](/questions/tagged/polyglot "show questions tagged 'polyglot'") challenges and [radiation-hardening](/questions/tagged/radiation-hardening "show questions tagged 'radiation-hardening'") challenges. I think, however, this is the first time I've used it on a challenge that falls into both categories. This was annoyingly time-consuming to verify – my normal [radiation-hardening](/questions/tagged/radiation-hardening "show questions tagged 'radiation-hardening'") verifier programs don't handle infinite loops well, and yet an infinite loop is shorter to write than a "loop up to input" is in Perl, so I ended up having to check all the irradiated programs manually. The `-M5.010` argument to Perl is a version selection argument that's basically standard in golfing at this point (and used to be allowed without penalty even back when we penalised for command-line arguments) – I would add it out of habit even if it didn't do anything (although it's required here). ## Explanation ### Perl Most of the program is stored in a string, `$_`, which is immediately evaluated: ``` $_='…';eval $_='…' initialize variable $_ eval evaluate {$_} as a program ``` (`$_` is chosen as the variable because it's the default variable that most commands use when an operand is missing, so this helps out the tiebreak score a little.) The program itself does the following: ``` {length==86&&6&&say$T0+=++$b9F;redo}{…}#… { ;redo} infinite loop say print $T0 the value of $T0 += after adding $b9F the value of $b9F to it ++ after adding 1 to that && but only if length the length {of $_} ==86 is 86 && and 6 6 is truthy {…} unreachable code #… comment ``` The actual calculation of the triangular numbers is very simple (although confusing because there are two assignments inside the expression) – `$T0` holds the triangular number itself, and `$b9F` its index, and we repeatedly add 1 to `$b9F` and then add `$b9F` to `$T0` in order to produce the sequence of triangular numbers. Perl variables are initialised with `undef`, which acts like 0 when you increment it or add numbers to it. (The variable names don't matter to the Perl program, and are as weird as they are due to how A Pear Tree works.) The unreachable code – part of the A Pear Tree program – is syntactically valid, but never runs because there's an infinite loop immediately before it. The `length==86` check is used to ensure that none of the irradiated versions of the program print the triangular numbers in Perl. Deleting most things outside the long string literal, or its delimiters, produces a syntax error. Deleting characters from `eval` is not a syntax error, but the resulting program does nothing when run, because the string is never evaluated. Some deletions inside the string produce syntax errors; these are caught by `eval` (thus no error message is printed), but prevent the string being evaluated. For other deletions inside the string, the `length==86` check will prevent anything actually being printed (it will either be intact, or be corrupted into something falsey), so the code still doesn't output the triangular numbers. The check for 6 being truthy is mostly irrelevant – it was added purely so that I could have two `&&`s in there, thus preventing the scenario in which a lone `&&` (short-circuiting AND) gets irradiated into `&` (bitwise AND) and causes the `say` statement to run uncondtionally. (With the two `&&`s, if either of them gets corrupted into `&`, the other still prevents the `say` statement running because its left-hand side will be falsey.) ### A Pear Tree To write an A Pear Tree program, you need to decide which substrings of the program are going to be checked for corruption by the interpreter – the interpreter will rotate the largest such part to the start before running the program (and error out if there is no such portion). The substrings in question are marked implicitly by changing irrelevant internal details of them in such a way that their CRC32 is 0. In this program, there are three such sections with a CRC32 of 0 – the entire program, and the two `{print$tYC+=++$nKy;redo}#` substrings. In a non-irradiated run of the program, the largest section is the program itself, so it runs unrotated, and is has effectively identical control flow to the Perl. However, `say` is not a keyword in A Pear Tree (the "print with newline" builtin is called `print` there, in one of its very minor differences from Perl), so the program hits an error when it tries to execute `say` (which is caught by the `eval` and the program exits naturally). It would be possible to exploit other differences between the languages (e.g. `$\` is falsey in Perl but truthy in A Pear Tree), but using the existence/nonexistence of `say` is terser. If you delete any character from the program, the program as a whole will no longer have a CRC32 of 0, so one of the `{print$tYC+=++$nKy;redo}#` substrings (whichever one didn't get irradiated, or the first one if they're both intact) is rotated to the start, followed by the rest of the program. However, the `#` at the end of the substring comments the rest of the program out, so we just end up with a small loop that calculates triangular numbers. This is identical to the triangular number calculation part of the Perl code, except for the variable names and the use of `print` rather than `say`. (Incidentally, although A Pear Tree often allows you to omit the `$` before a variable name, it doesn't allow this after the `++` operator and wouldn't save bytes after the `print`, so for once all the `$`s are present.) In order to mark the appropriate substrings of the code, I changed the variable names (and other details like the specific truthy constant in the Perl code – obviously, any truthy constant would work for Perl, not just `6`, but `6` worked best for A Pear Tree), which is why they're so weird. ]
[Question] [ Your task is, given a array of numbers, that is strictly increasing, output the crate stack. The input is an array of positive integers which represents which layer has how many crates there are. So the first number is the top layer and so on. The sum of the array is the size of the crate. Since the array order follows this rule `layer 1>layer 2>layer 3...`, we have to make sure every layer above the bottom one is centered with respect to the whole width of the layer below it. If it can't be centered, place it so that it's as close as possible to the center (you can choose it to be shifted left or right). ## Testcases ``` [1] -> * [1,2] -> *** * * *** ****** * ** * ****** [2,3] -> ********** * ** * * ** * * ** * ********** *************** * ** ** * * ** ** * * ** ** * *************** [2,3,4] -> ****************** * ** * * ** * * ** * * ** * * ** * * ** * * ** * ****************** *************************** * ** ** * * ** ** * * ** ** * * ** ** * * ** ** * * ** ** * * ** ** * *************************** ************************************ * ** ** ** * * ** ** ** * * ** ** ** * * ** ** ** * * ** ** ** * * ** ** ** * * ** ** ** * ************************************ ``` Leading spaces and trailing spaces are allowed This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins! [Answer] # JavaScript, ~~225~~ 219 bytes -7 thanks to Arnauld's suggestion ``` s=d=>{j=console.log;o=(p,g)=>p.repeat(g);a="*";[t]=d.slice(-1);if(t==1)return j(a);b=t*-~t/2-2;b=b<1?1:b;d.map(i=>{h=o(" ",(t*b-i*b)/2);c=`${h+o(o(a,b+2),i)}${o(` ${h+o(`*${o(" ",b)}*`,i)}`,b)} ${h+o(o(a,b+2),i)}`;j(c)})} ``` [Try it online!](https://tio.run/##ZY1BboMwEEX3nAKhLGYcQ2Q3qzqTHiSKZBtcYkQxAqcbRK9OsdpFpa7mvf/1NZ35NHM9@TGWQ2jcNtPW0HXpqA7DHHpX9aFVgWDkLdJ1rCY3OhOhRWWoYIW6xTs11dz72kEpUPl3iEQCJxef05B3YFBZiqz8iidZyp3tRbyJV6ua6sOM4PdnDwpQ5AWHyGzpmcWTRFWTPiyPY4AAhtujRO5xPSwBdPaTa5Ys7SyuTKdaJ8z@z7TqoMYV122Gm@C55PnLHVWW7Pf@iRLy/Lzb9g0 "JavaScript (Node.js) – Try It Online") Unminified for your enjoyment: ``` function stack(arr) { String.prototype.o = function(p) { return this.repeat(p); } const a = "*"; const [t] = arr.slice(-1); if(t == 1) return console.log(a); let sum = ((t * t + t) / 2) - 2; if(sum < 1) sum = 1; arr.forEach(i => { const spaces = " ".o((t * sum - i * sum) / 2); const crate = `${spaces + a.o(sum + 2).o(i)}${`\n${spaces + `*${" ".o(sum)}*`.o(i)}`.o(sum)}\n${spaces + a.o(sum + 2).o(i)}`; console.log(crate); }); } ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 128 bytes ``` lambda n:(s:=sum(n))and'\n'.join('\n'.join((n[-1]-N)*s//2*' '+N*('*'+'* '[0<m<s-1]*(s-2)+'*'*(s>1))for m in range(s))for N in n) ``` [Try it online!](https://tio.run/##VcpBDoIwEEDRvafobmYKiBQXhoBH4ALAogZRjB1IiwtPX2tMVHY/L39@LteJ88Ns/VC1/q7NqdeCC3RF5R4GmUhzDy3D9jaNjL9CbpKsS2qSLk2VBAFRLREkRCAFNLvSlC4MEl2iKBiEOmZEw2SFESMLq/lyRveR@i1MfrYjLzhgo2KRx2LfEW2@lgVbgVrB/xnUvwA "Python 3.8 (pre-release) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` O'*Ž9¦.Λ¶¡¸Iи€øJ€»».c ``` [Try it online](https://tio.run/##ATQAy/9vc2FiaWX//08nKsW9OcKmLs6bwrbCocK4SdC44oKsw7hK4oKswrvCuy5j//9bMiwzLDRd) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GpeSZV1BaYqWgZK/DpeRfWgLh6Pz3V9c6utfy0DK9c7MPbTu08NAOzws7HjWtObzDC0ge2n1ot17yf51D2@y5QIZwlWdk5qQqFKUmpihk5nGl5HMpKOjnF5ToQ@yCUmjW2yiogNXmpf6PNozlijbUMQKSRjrGEFLHJJYLAA) or [try it online with step-by-step debug lines](https://tio.run/##XZG9TsMwEIB3nuLUhR9FrQQsgBBibBcQPwuIwXWu8UmOHdkOoYy8BhMLE3NVCbEEdUU8Ay8SbCetqkpRpNx93/1FWzYmbJreUBWlO4ZeclrPzrZ612UOTiBQCIPTGfovAzshVlHqxEAgZcKBnkRurJ92g33R6pelFTHOBTOMO69WXmQq1ILUsCrA23sbdEoGuSOt7BJbFg/44uuofm@NW0sqCzmL/m0QgZmszFE5mwA3yByum/2f126tQpID/2gFCitJCmMrBpJsXCaGglPP6rdWusLCFwzW6iIWWK5L1a5PeWfMh7/zVrmjYuAMU7bQfkJkXJyArVhRhLGNruyAa1nmVgXv7@Xju/NGmlTEfRvljxamCsioTd8I7NLj6Wr@rkT9uc48opk6EbptkEvsXKUwIcWknAL3dzNM0jOGW/hfHRc1aEsZu/d50jT3@8lBcvjwDw). **Explanation:** ``` O # Sum the (implicit) input-list '* '# Push "*" Ž9¦ # Push compressed 2460 .Λ # Use the (modifiable) Canvas builtin with these three options ¶¡ # Split this box by newlines ¸ # Wrap it in a list Iи # Repeat it each of the inputs amount of times € # Map over each list of boxes: ø # Zip/transpose; swapping rows/columns J # Join each inner row together to a single string €» # Join all inner lines by newlines » # Join each vertical line of boxes by newlines .c # Centralize all lines # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž9¦` is `2460`. As for some additional information about the modifiable Canvas builtin `.Λ`: It takes 3 arguments to draw an ASCII shape: 1. Length of the lines we want to draw 2. Character/string to draw 3. The direction to draw in, where each digit represents a certain direction: ``` 7 0 1 ↖ ↑ ↗ 6 ← X → 2 ↙ ↓ ↘ 5 4 3 ``` `O'*Ž9¦` creates the following Canvas arguments: 1. Length: the sum of the input (e.g. for `[2,3,4]` this would be `9`) 2. Character: `"*"` 3. Directions: `[2,4,6,0]`, which translates to \$[→,↓,←,↑]\$ [Try just the Canvas portion online.](https://tio.run/##yy9OTMpM/f/fX13r6F7LQ8v0zs3@/z/aSMdYxyQWAA) Step 1: Draw 9 characters (`"*********"`) in direction 2/`→`: ``` ********* ``` Step 2: Draw 9-1 characters (`"********"`) in direction 4/`↓`: ``` ********* * * * * * * * * ``` Step 3: Draw 9-1 characters (`"********"`) in direction 6/`←`: ``` ********* * * * * * * * ********* ``` Step 4: Draw 9-1 characters (`"********"`) in direction 0/`↑`: ``` ********* * * * * * * * * * * * * * * ********* ``` After which we can use this string since we're using the modifiable Canvas builtin `.Λ`, instead of the Canvas builtin `Λ` that would output directly. [See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` FLθ«J⊘קθιΣθ×ιΣθF§θι«BΣθ*MΣθ← ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwyc1L70kQ6NQU1OhmovTqzS3ICRfwyMxpyw1RSMkMze1WMOxxDMvJbVCo1BHIVNTRyG4NBekGsiCSGcihKy5OMFmougAm8vplF@hAVGmo6CkpQRSyumbX5YKF7TySU0rAQnXctX@/x8dbaRjrGMSG/tftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FLθ« ``` Loop over each layer. ``` J⊘קθιΣθ×ιΣθ ``` Jump to the top left corner of the last box in that layer. ``` F§θι« ``` Loop over each box in the layer. ``` BΣθ* ``` Draw the box of the appropriate size. ``` MΣθ← ``` Move to the previous box. [Answer] # JavaScript (ES6), ~~132 128 120~~ 119 bytes Non-centered crates are shifted to the right. ``` f=(a,x=W=a.every(n=>w+=N=n,w=y=0)+w*N)=>(q=W-a[y/w|0]*w)?` * `[--x?(X=x+q/2)%w<2|-~y%w<2&&X>=q&X<W:++y&&2]+f(a,x||W):'' ``` [Try it online!](https://tio.run/##dc3BCoIwHIDxu0/Rpbm5TW11Ev/6Bl4niOAwjUI0NZwD6dUtr2GnD36X76EmNZbD/fnibXet1rUGrNgMEpRbTdVgcAuRppBAyzQY8AnVTkIgwj1IrjLj6cXPHU3i4uBYRcb5HOMUZtp7ghx1KBb@NlsRSiPoURrKgFKDkMhpvZ2WRZLAtteya8euqdymu@EaZ6ecEOvXmNjV846Kf8ouX18/ "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: a, // a[] = input array // and also using: x = // (x, y) = current position W = // W = total row width, w = crate width a.every(n => // for each value n in a[]: w += N = n, // add n to w and save n in the global scope w = y = 0 // start with w = 0 and y = 0 ) // end of every(), which returns 1 + w * N // add the last value multiplied by w ) => // ( q = W - // define q as the total row width less the a[y / w | 0] * w // total width of the crates on this row ) ? // if q is not NaN: ` *\n`[ // character lookup: --x ? // decrement x; if it's not 0: (X = x + q / 2) // define X as x + q / 2 % w < 2 | // if we're over a vertical crate edge -~y % w < 2 // or over a horizontal crate edge && // and X >= q & X < W // we're over the crates in this row, // then put a '*', else put a space : // else: ++y && 2 // increment y and put a linefeed ] + // end of character lookup f(a, // append the result of a recursive call x || W) // make sure to restart with x = W if x = 0 : // else: '' // stop the recursion ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 19 bytes ``` ∑×2460ø^↵vẋƛ∩Ṡ;føĊ⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiJHDlzI0NjDDuF7ihrV24bqLxpviiKnhuaA7ZsO4xIrigYsiLCIiLCJbMiwzLDRdIl0=) ]
[Question] [ # Introduction In a standard\* (e.g. not 2020) tax year, estimated payments are due quarterly according to the schedule outlined in [Publication 505](https://www.irs.gov/pub/irs-pdf/p505.pdf). | Payment Period | Due Date | | --- | --- | | January 1 – March 31 | April 15 | | April 1 – May 31 | June 15 | | June 1 – August 31 | September 15 | | September 1 – December 31 | January 15 | \* Saturday, Sunday, holiday rule, fiscal year taxpayers, and January payment exceptions can be ignored for the purpose of this question; use the standard table provided. # Challenge Input: A date/timestamp, either provided as input to your solution (function parameter or stdin) as a string (at a minimum specifying a specific year, month, an day of month) or native `Date` object (or equivalent) or the current (dynamically updated) date/time based on the clock of the executing machine. Output: The most specific payment period, one of `Q1`, `Q2`, `Q3`, or `Q4` as a string, either printed to stdout/console or programmatically returned from the function, to which a timely payment made on the input date would be applied. | Input | Output | | --- | --- | | January 16 - April 15 | Q1 | | April 16 - June 15 | Q2 | | June 16 - September 15 | Q3 | | September 16 - January 15 | Q4 | A day shall commence at 00:00 (midnight) and cover time periods up to but not including 00:00 (midnight) of the following day. The last moment of a given day, to a ms granularity is `23:59:59.999`. [Answer] # JavaScript (ES6), 53 bytes Expects a string in `"DD-MM-YYYY"` format. ``` s=>"Q"+"4243131"[[d,m]=s.split`-`,(m*24|d>15)*9%23%7] ``` [Try it online!](https://tio.run/##hY/RaoMwFIbv@xRHoZrUKE3UjdHp3R5g9FKEBqOrQ40koTC27tVdTDvY3S6S/Pn5z3fOeecXrhvVzyaepGiXrlh0UfqvfuRnLEtpSv2qEmSsC53oeejNKT4RNO5Y9iVKmuPd05al28d66aRCs2ovUEAYEhjlZM5W08NdPlvN7p8owvC5AahyAnQ9DwRYXieW8cKbMxL8A4rSRQAEN60FWS8x8mhUP70hnMxcHA1XBjECewwRhHFob4f/J8f2jIYHx1attugOrT3wzfI8t0UA7vEK@N3KZjEEATRy0nJok0Fa/q3mr@XGtW3gu4R1orVsTV3x5rr8AA "JavaScript (Node.js) – Try It Online") --- ### 39 bytes If we can just take the month and the day. ``` m=>d=>"Q"+"4243131"[(m*24|d>15)*9%23%7] ``` [Try it online!](https://tio.run/##TY8xb4MwEIX3/IoDKWAHgrCBVFVqT@3SoVXVMcpgYZOkAhwBSlW16V@nh0WkDj6/O7/36fyhLqovu9N5WLdWm7ESYyOkFtJ/8yM/53nGMubvSLPi@Y@WrKCr@yXPlnf7sbIdOXfmAgLCMIbGtsMRNdvO8gE1n5soovC9ANgVMbDpbGLgxT5BxpMqj0SrLxDSWQC0GgyCWvMJjygJTzm78deAEt00Gezz@@sLoUlfn0pDUoSmdOsAnekxXxEXoRN8fvA8t3AA7vIE3D6ACQpBAKVte1ubpLYHMmf@j9xmEYTwK7FELja5rnRxHf8A "JavaScript (Node.js) – Try It Online") --- ### 35 bytes As suggested by [@ovs](https://codegolf.stackexchange.com/users/64121/ovs), using a larger lookup table with a much simpler formula is actually shorter. ``` m=>d=>"Q"+"_4111223334444"[m+=d>15] ``` [Try it online!](https://tio.run/##TY/Ba4MwFMbv/SueHjQhVkysu7TJabv0sDJ2LGUEE9cWNUWlY5TuX7fPYGGBl3wv@b4fL2d91X3ZnS7DsnXGjpUcG6mMVOFHyMKvFedciDzPV7jCfcOkUbw4jJXryKWzV5AQxwk0rh2OqPl6lhvUYm4Yo3BbAOyLBPhULwmI4pAi402XR2L0L0jlLQBGDxZBrf2BV5REZII/@UtAiW6aDm77uXsnNO3rU2lJhtCMrj2gsz3mK@IjdILPD0HgB47AH4GE5wcwQSGKoHRt72qb1u6bzJn/V34yBjH8KdyYj02uO13cxwc "JavaScript (Node.js) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~72~~ 63 bytes ``` \d+ $* 1+-(1{1,5}(1)*)-1{1,15}(1)* 11$3$2$1 (111)*1+ Q$#1 0|5 4 ``` [Try it online!](https://tio.run/##Tc@9CgIxEATgfl/DFLmLgUz@7u4x7G0ELWwsxE599mjQZAJbzH4MC3u/PK63UynHsxE1C4zVeGKf3hrTPNma8VsEUEF5BdHAd4eRg9pB3CtJLMU7D@vqSItIwpz/0VfusWmgBmocTkRyYjlR81DO5IXlhbpSV@o2nNg6w/VyjU1B5XvgezXmDw "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input in `YYYY-MM-DD` format. Explanation: ``` \d+ $* ``` Convert to unary. ``` 1+-(1{1,5}(1)*)-1{1,15}(1)* 11$3$2$1 ``` Add 2, 3 or 4 to the month depending on whether the month is greater than 5 or the day is greater than 15 or not. ``` (111)*1+ Q$#1 ``` Subtract 1 from the month, then integer divide it by 3 and prefix Q to the result. (This is to avoid zero width matches.) ``` 0|5 4 ``` Change `Q0` and `Q5` to `Q4`. [Answer] # [R](https://www.r-project.org/), ~~65~~ 62 bytes ``` function(d)paste0("Q",1+sum(c(3,5,8)<el(format(d-15,"%m"):1))) ``` [Try it online!](https://tio.run/##dctBCsIwEEDRvccYEGYwKZlog5W68wIeIbQJCKYtTXr@VOk2Wf//1uyf2W/TkD7zhCMtNianEN4g@BK3gANeRSvu1Lsv@nkNNuEouRVwDkAPJqLs0cbmZZND0EqzVLffAESnUjDFYGrC1ERXE11RaKm4KI7wF3kH "R – Try It Online") Expects input in R's native Date class. Subtract 15 days from the input, extract the month (as a string such as `"04"`), and convert to numeric with `el(...:1)` (see [this tip](https://codegolf.stackexchange.com/a/12837/86301)). We then get the result by adding 1 for each of the values 3, 5, and 8 which are smaller than the result. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` ≔I⪪S-θ§12344÷⁻§θ¹⁺›¹⁶⊟θ›⁶⊟θ³ ``` [Try it online!](https://tio.run/##RcxBCoMwEAXQfU8RspqAARPFjStpobgoCJ4gaLCBEDUZpbdPp4u2m/nw@H@mp4nTanzOXUpuCXA1CWHcvEPow3bgiNGFBUTBuOSCYhftZSBD6LAPs30BV7qqa16wPuDNnW628HDhSL/CXjBFy8GT3aM1aCOohmDdYP/8/OLfCCu6os1Zl1rJspGqyfL0bw "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the form `YYYY-MM-DD`. Explanation: ``` ≔I⪪S-θ ``` Input the date, split it on `-` and cast to integer. ``` §12344÷⁻§θ¹⁺›¹⁶⊟θ›⁶⊟θ³ ``` Take the month, subtract 1 each if the day is less than 16 or the month is less than 6, divide by 3, then cyclically index into the string `12344`, thus casting `-1` and `4` to `4`. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 109 bytes ``` lambda n,i=int:'Q'+['?111223334444'[i(k:=(S:=n.split('-'))[1])],'1234'[i(k)//3-1]][k in'1469'and(i(S[0])<16)] ``` [Try it online!](https://tio.run/##VY5BjsIwDEWv4p0dUSiOAUFFNWcYsQxZBJVCBKRVyIbTd0KrkcALy3r@39/9K127INs@Dm19HO7ucWochMLXPqQKf3Fm8IeZtRaRVS40nm5VTYeqDotnf/eJcI5KGbbKFshaJokqS5mzteYGPiCvNjt0oSFPB7O0as8bZQfTx5xCLT1TpMa9FMwgH8sd3uTRhXSd2FoLjhO0XYS34tNS/oPJoUbROOdsiC5czsQFsEybbPviovMvfw "Python 3.8 (pre-release) – Try It Online") Way too long. The OP has confirmed very kindly that this is the only solution of mine which is valid. ]
[Question] [ Two dimensional chiral objects are not chiral in three dimensional space. This is because you can flip them over which is equivalent to taking the mirror image unlike in two dimensions where only rotations in the plane of the object are allowed which cannot reproduce the effect of a mirror operation. In this challenge, we will be deciding whether three dimensional texts are chiral. ## Some definitions * **Three dimensional text**: A rectangular three dimensional array of characters. In this challenge, programs will only need to handle nonwhitespace printable ASCII (`!` through `~`). * **Mirror operation**: The operation of reversing the order of characters along a single axis of the three dimensional text. Rotations can be thought of intuitively, but here is an explicit definition for those who will eventually ask. * **90-degree rotation**: The operation of transposing each plane perpendicular to a specific axis (say \$i\$), then applying a mirror operation to an axis other than \$i\$. * **Rotation**: A succession of 90-degree rotations. * **Chiral**: A three dimensional text is chiral if after applying any single mirror operation, there does not exist a rotation of the new text that reproduces the original text. A text is not chiral if after applying a single mirror operation the new text can be rotated back to the original text. A slightly more concise definition of chirality is lack of existence of an improper rotation under which an object is invariant. ## Task In whatever format you prefer, take a three dimensional text as input. Output one of two consistent values, one indicating that the text is chiral and one indicating that it is not. Shortest code wins. ## Examples In each section, the vertical pipes (`|`) separate the test cases. Within each test case, layers of the three dimensional texts are separated by blank lines. **Not chiral** ``` Z--Z | i~ | Qx | a | abaLIa ---- | >> | xx | b | N#)*@" Z--Z | | | | }-3}#k | >> | QQ | d | ../..' Z--Z | ~i | QQ | e | ---- | | | | Z--Z | | | f | | | | g | ``` **Chiral** ``` Z--Z | *k | Qxxx | a* ---- | <0 | xxxx | ** Z--- | | | | l7 | QQQQ | ** Z--- | GB | QQQQ | a* ---- | | | Z--Z | q~ | | ** | ]J | | *a ``` [Answer] # [Haskell](https://www.haskell.org/), ~~97~~ ~~96~~ 95 bytes * -1 byte thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi) ``` f s=all(r s/=)$foldr($)s<$>mapM(\_->[id,g,map g])[1..6] g=r.foldr(zipWith(:))e r=reverse e=[]:e ``` [Try it online!](https://tio.run/##dZJdS8MwGIXv@ytKN7AJTeYQFMYaxBtRpjC8ENaGkdGsC@tiTTopwvzr9W3qpPMjF82Tc05KD283wm5lUTTN2rexKIrQ@HYUo@H6pchMOER2OmQ7UT6E6ZKwRGVRHsHRzzlKxpReci@PDe3C76p8VtUmnCAkPRMb@SaNlZ6MEz6RjdLlvrKx58NKkiRYELIIooDAgs2dePS3zN2lCC6pDxAZc0nYolbo2fMapLp29nwODI@eLUBZOTMDko7WQPlJaCVmd23ycYDwdRoAHcjFYbAFoHREaXrWj//6XnKsQf6vgduXTc9dcnwFfHvj@LWtx@9PK9Vdqe9aX8V@VMMgYuwiuGXRYyyOUe7thNJxO9BlmFrCOoLJPFVmpuleF0pLiyxjpVG6CuGvQMDOD1Kd6gB1g2w@AQ "Haskell – Try It Online") ## Explanation Ok, this is a bit mathy. It is well known that the group of rotations as described in the challenge (i.e. the group generated by rotations of 90 degrees around one of the three principal axes) is isomorphic to the symmetric group \$S\_4\$, as described [here](https://en.wikipedia.org/wiki/Octahedral_symmetry#The_isometries_of_the_cube). It is also well known that \$S\_4\$ is generated by the elements \$(1\, 2\, 3\, 4),(1\, 3\, 2\, 4)\$. What I am trying to say is this: fix two *distinct* axes, and call the 90 degrees rotations about those axes \$r\_1\$ and \$r\_2\$. Then we can generate all the rotations by repeatedly applying \$r\_1\$ and \$r\_2\$. A bit of [bruteforce](https://tio.run/##LY29DoMgFEZ3n4ImDDZB4t8oTh3bJ6A3DY1YSeFKkCYOvjvVtOPJl/OdSS1vbW1Kxvk5RHJRUfGrWWLmdXDEk1XI9XQym@kKD9lIUFiNrzhx/DzpONsh5PQsK1azhrXQ0d4pf8vvj6KXZmDHyX8s4UflThVrAHaLc4TMKYPCB4ORTloNEjfsCllyDuzIibqFlL4) shows that we only need up to 6 applications of \$r\_1\$ and \$r\_2\$. Thus we have the following algorithm: given a three-dimensional text \$s\$, we apply all possible rotations to \$s\$ and check whether any of those matches \$s\$ flipped along an axis. The rotations are generated by composing up to six 90 degrees rotations about two fixed axes. --- ``` g=r.foldr(zipWith(:))e e=[]:e ``` `g` is a 90 degrees rotation of a 2D list (also works on 3D lists, as those can be seen as 2D lists of 1D lists). The `foldr(zipWith(:))e` is simply `transpose` from `Data.List`, but [shorter](https://codegolf.stackexchange.com/a/111362/82619). --- ``` f s=all(r s/=)$foldr($)s<$>mapM(\_->[id,g,map g])[1..6] ``` `f` checks whether its argument `s` is chiral. * `mapM(\_->[id,g,map g])[1..6]` generates a list of all sequences of length 6 whose elements are any of `id` (the identity transformation, i.e. do nothing), `g` (90 degrees rotation about an axis), `map g` (90 degrees rotations about a different axis). * given a list `[f1,f2,...,f6]` of transformations, `foldr($)s` computes `f1(f2(...f6(s)...)`, and `(r s/=)` checks whether the result is equal to `s` reversed (i.e. a mirror image of `s`). So what `f` does is check if any rotation of `s` matches its mirror image, returning `False` if it does and `True` otherwise. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 28 bytes ``` ~⊂∘⌽∊(⊢∪2 0 1∘⍉¨∪⌽∘⍉⍤2¨)⍣≡∘⊂ ``` [Try it online!](https://tio.run/##fVBNS8NAEL33VwR7mGZxY1oPgkgRL6KIkGvBw9qaEhqotj1EJDkUCWl0xR4Er34cQu9eBC/5KfNH4kytH6nissy@ee/NwFt16svOufL7Xdn21XDotQu8ufP6GN/ahUs1wnSMyT1ev2GS1jB9xGTWMGyjzqSe5Bn1c5E71M@NPDNRP@Hkgal0XBQj2nKB@oWoAUEX9esm9HuAV5fgKs8HIkgehBV7hDrDeEq3Bi0pW2CApEPPvDP/ZstzXkRCs8lmqgZE3rLDCYgOAnY4DkEqPxx6lmegjonvnFBxu/ClrfJfxFNS1cGeIvGwaortFQKhXA@rPQKWtWZZAFCp/5tFLrLIX1lKc4JXbtls9jcI7u4wPOOER/vLZicIPoJ9RluEm8crOZUgQQh2CYbqGwoF5js "APL (Dyalog Classic) – Try It Online") [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 36 bytes ``` {^*({?x,((++:')'x),(|+:)'x}/,x)?,|x} ``` [Try it online!](https://tio.run/##fZBfT8IwFMXf/RSkmKzt2oHxwaTXgPHFaIzJXsERanRkGcFIeLhkdF993hWsf5j0oT29Pb@295R6tVg1TW6qmeTVGBXncWwiEaFQfBcbEm6gUIzVDl2zMdX5dFuvTd5DmL@XwOe5LZaAsIW1yNzZZso5m2g9YcA0DVr8TkB3WcAw20NFTcXRyDtpAVYXdNzrHAFKkYyIHkpT0jSdhhRn9oWMr2805Qv2j7kDso/3lpinvpA3z4yU05euX5JIkkGSRN9Xhe8dday/gtDHQVwcINleeT30zuUV6btbrz/agLKHX/0FKEXcRxHCOMTREUiArCSLlB6QrbY/tLR/X2o@AQ "K (ngn/k) – Try It Online") ]
[Question] [ If you cannot see this post, you can use [this image](https://i.stack.imgur.com/ZBOMa.png) Your task is to create a markdown parser that outputs Unicode. It should support 𝗯𝗼𝗹𝗱, 𝘪𝘵𝘢𝘭𝘪𝘤, 𝙼𝚘𝚗𝚘𝚜𝚙𝚊𝚌𝚎, and 𝗎̲𝗇̲𝖽̲𝖾̲𝗋̲𝗅̲𝗂̲𝗇̲𝖾̲. Every alphabetical character should be converted into Math Sans. This includes the characters before an underline character. Underlines: Add a `̲` character (code point 818) after each character. Underlines can be combined with anything else. There should be no way to escape a control character. ### The following combinations should be supported: `𝖠𝖡𝖢𝖣𝖤𝖥𝖦𝖧𝖨𝖩𝖪𝖫𝖬𝖭𝖮𝖯𝖰𝖱𝖲𝖳𝖴𝖵𝖶𝖷𝖸𝖹𝖺𝖻𝖼𝖽𝖾𝖿𝗀𝗁𝗂𝗃𝗄𝗅𝗆𝗇𝗈𝗉𝗊𝗋𝗌𝗍𝗎𝗏𝗐𝗑𝗒𝗓` (code point 120224 to 120275 Math Sans) ``` `𝙰𝙱𝙲𝙳𝙴𝙵𝙶𝙷𝙸𝙹𝙺𝙻𝙼𝙽𝙾𝙿𝚀𝚁𝚂𝚃𝚄𝚅𝚆𝚇𝚈𝚉𝚊𝚋𝚌𝚍𝚎𝚏𝚐𝚑𝚒𝚓𝚔𝚕𝚖𝚗𝚘𝚙𝚚𝚛𝚜𝚝𝚞𝚟𝚠𝚡𝚢𝚣` ``` (120432 to 120483 Math Monospace) `*` `𝘈𝘉𝘊𝘋𝘌𝘍𝘎𝘏𝘐𝘑𝘒𝘓𝘔𝘕𝘖𝘗𝘘𝘙𝘚𝘛𝘜𝘝𝘞𝘟𝘠𝘡𝘢𝘣𝘤𝘥𝘦𝘧𝘨𝘩𝘪𝘫𝘬𝘭𝘮𝘯𝘰𝘱𝘲𝘳𝘴𝘵𝘶𝘷𝘸𝘹𝘺𝘻` `*` (120328 to 120379 Math Sans Italic) `**` `𝗔𝗕𝗖𝗗𝗘𝗙𝗚𝗛𝗜𝗝𝗞𝗟𝗠𝗡𝗢𝗣𝗤𝗥𝗦𝗧𝗨𝗩𝗪𝗫𝗬𝗭𝗮𝗯𝗰𝗱𝗲𝗳𝗴𝗵𝗶𝗷𝗸𝗹𝗺𝗻𝗼𝗽𝗾𝗿𝘀𝘁𝘂𝘃𝘄𝘅𝘆𝘇` `**` (120276 to 120327 Math Sans Bold) `***` `𝘼𝘽𝘾𝘿𝙀𝙁𝙂𝙃𝙄𝙅𝙆𝙇𝙈𝙉𝙊𝙋𝙌𝙍𝙎𝙏𝙐𝙑𝙒𝙓𝙔𝙕𝙖𝙗𝙘𝙙𝙚𝙛𝙜𝙝𝙞𝙟𝙠𝙡𝙢𝙣𝙤𝙥𝙦𝙧𝙨𝙩𝙪𝙫𝙬𝙭𝙮𝙯` `***` (120380 to 120431 Math Sans Bold Italic) `__` `𝖠̲𝖡̲𝖢̲𝖣̲𝖤̲𝖥̲𝖦̲𝖧̲𝖨̲𝖩̲𝖪̲𝖫̲𝖬̲𝖭̲𝖮̲𝖯̲𝖰̲𝖱̲𝖲̲𝖳̲𝖴̲𝖵̲𝖶̲𝖷̲𝖸̲𝖹̲𝖺̲𝖻̲𝖼̲𝖽̲𝖾̲𝖿̲𝗀̲𝗁̲𝗂̲𝗃̲𝗄̲𝗅̲𝗆̲𝗇̲𝗈̲𝗉̲𝗊̲𝗋̲𝗌̲𝗍̲𝗎̲𝗏̲𝗐̲𝗑̲𝗒̲𝗓̲` `__` (818 Math Sans with Combining Low Line after each character) `__`` `𝙰̲𝙱̲𝙲̲𝙳̲𝙴̲𝙵̲𝙶̲𝙷̲𝙸̲𝙹̲𝙺̲𝙻̲𝙼̲𝙽̲𝙾̲𝙿̲𝚀̲𝚁̲𝚂̲𝚃̲𝚄̲𝚅̲𝚆̲𝚇̲𝚈̲𝚉̲𝚊̲𝚋̲𝚌̲𝚍̲𝚎̲𝚏̲𝚐̲𝚑̲𝚒̲𝚓̲𝚔̲𝚕̲𝚖̲𝚗̲𝚘̲𝚙̲𝚚̲𝚛̲𝚜̲𝚝̲𝚞̲𝚟̲𝚠̲𝚡̲𝚢̲𝚣̲` ``__` (Math Sans Monospace with Combining Low Line) Underline should also support Math Sans Italic, Math Sans Bold, and Math Sans Bold Italic The final output should not contain the characters used to format the text. ### Nesting Some things can be nested. Underlines can nest with any character and can be put in the inside or outside of another control character. Both of these will have an underline. ``` **Underlines __inside the bold__** __Bold **inside the underline**__ ``` Other things such as bold, monospace, bold italic, and italic can't nest because there are no characters for it. ``` **This is `not valid` input and will***never be given* ``` ### Ambiguous Formatting Characters Formatting characters that can be ambiguous will never be given. `**` is valid because it is bold, but `****` will never be given because it is undefined. At the end of formatting characters, there will always be another character between the next formatting delimiter of the same character. `*format***ing**` will not be given because there should be a character before the next `*format* **ing**` delimiter using `*`s, however `*format*__ing__` could be given because they are different characters used in the delimiter. ``` **Which is bold ***and which is italic?* <-- Invalid, will never be given **Oh I see** *now.* <-- Valid ``` ### Escaping Nothing can escape. There is no way to use any of the control characters except for a singular underscore ``` *There is no way to put a * in the text, not even \* backslashes* <-- All of the asterisks will be italic Even __newlines don't interrupt__ formatting <-- newlines don't interrupt will all be underlined Because the singular _underscore is not a formatting character, it_is allowed_ and will not be removed ``` ### Example I/O Example I ``` *This* is_a **test** of __the ***markdown*** `parser`__ Multi-line `__should be__ supported`. Nothing `can\` escape. ``` Example O ``` 𝘛𝘩𝘪𝘴 𝗂𝗌_𝖺 𝘁𝗲𝘀𝘁 𝗈𝖿 𝗍̲𝗁̲𝖾̲ ̲𝙢̲𝙖̲𝙧̲𝙠̲𝙙̲𝙤̲𝙬̲𝙣̲ ̲𝚙̲𝚊̲𝚛̲𝚜̲𝚎̲𝚛̲ 𝖬𝗎𝗅𝗍𝗂-𝗅𝗂𝗇𝖾 𝚜̲𝚑̲𝚘̲𝚞̲𝚕̲𝚍̲ ̲𝚋̲𝚎̲ 𝚜𝚞𝚙𝚙𝚘𝚛𝚝𝚎𝚍. 𝖭𝗈𝗍𝗁𝗂𝗇𝗀 𝚌𝚊𝚗\ 𝖾𝗌𝖼𝖺𝗉𝖾. ``` This input is not valid and it doesn't matter what your program outputs: ``` *This **is not valid** input* because it nests italic and bold *Neither `is this`* because it nests italic and monospace *This***Is not valid** Either because it can be interpreted different ways ``` As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest solution in bytes wins. [Answer] # [Stax](https://github.com/tomtheisen/stax), 75 73 74 70 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç╜ÿPÜV►♀b7╛i┴?τ\⌂:Té√╖■♠(µ`ómƒÜKx▬∙═τ½εxÅr∩!E#î⌡╕B┴zäÅéë┘S²↔óh₧≡6ÿ╖iô├ ``` [Run and debug it online](https://staxlang.xyz/#p=80bd98509a56100c6237be69c13fe75c7f3a5482fbb7fe0628e660a26d9f9a4b7816f9cde7abee788f72ef2145238cf5b842c17a848f8289d953fd1da2689ef03698b76993c3&i=*This*+is_a+**test**+of+__the+***markdown***+%60parser%60__+Multi-line+%60__should%0Abe__+supported%60.+Nothing+%60can%5C%60+escape.%0A**Underlines+__inside+the+bold__**%0A__Bold+**inside+the+underline**__%0A**Oh+I+see**+*now.*%0A%60__mark__down%60&a=1) The basic approach is store the 4 types of formatting in a bit field, and then get the correct character offset from a lookup using the integer value. Only 8 values are in the lookup. The high bit denoting underline is handled separately. Here's a commented ungolfed version. ``` m Map mode: for each line of input, run the rest of the program, then output "\*\*|__|."|F Find all regex matches using pattern. This splits the string into individual characters except for ** and __, which stay together. These will be called "atoms" of the input. { begin a block VAVa+ Construct "ABC..XYZabc..xyz" "_*``_****__"_I Get the index of the current atom in "_*`_****__" 0|MY Take the maximum with zero, then store in register y. This gives {*: 1, `: 2, **: 4, __: 8} and 0 for all else. x|^X Xor with the x register and write back. It stores bitflags for 4 modes. "&6mU*9*9 0E*9 !"!@ Index into codepoint lookup table using x. c52+|r Build range of 52 consecutive values starting at codepoint. \$ Build translation string by combination with the alphabetic string. |t Perform translation on the current atom. 818+ Add codepoint 818 to the current atom. x8<T Remove it again if x<8. This is iff underline mode is off. y!* Multiply by the logical not of y. If the atom is for formatting, this eliminates output for this atom m map over atoms using the enclosed block ``` [Run this one](https://staxlang.xyz/#c=m++++++++++++++++++++%09Map+mode%3A+for+each+line+of+input,+%0A+++++++++++++++++++++%09%09run+the+rest+of+the+program,+then+output%0A%22%5C*%5C*%7C__%7C.%22%7CF++++++++%09Find+all+regex+matches+using+pattern.+This+splits+the+string+into+%0A+++++++++++++++++++++%09%09individual+characters+except+for+**+and+__,+which+stay+together.%0A+++++++++++++++++++++%09%09These+will+be+called+%22atoms%22+of+the+input.%0A%7B++++++++++++++++++++%09begin+a+block%0A++VAVa%2B++++++++++++++%09Construct+%22ABC..XYZabc..xyz%22%0A++%22_*%60%60_****__%22_I++++%09Get+the+index+of+the+current+atom+in+%22_*%60_****__%22%0A++0%7CMY+++++++++++++++%09Take+the+maximum+with+zero,+then+store+in+register+y.%0A+++++++++++++++++++++%09%09This+gives+%7B*%3A+1,+%60%3A+2,+**%3A+4,+__%3A+8%7D+and+0+for+all+else.+%0A++x%7C%5EX+++++++++++++++%09Xor+with+the+x+register+and+write+back.+It+stores+bitflags+for+4+modes.%0A++%22%266mU*9*9+0E*9+%21%22%21%40%09Index+into+codepoint+lookup+table+using+x.%0A++c52%2B%7Cr+++++++++++++%09Build+range+of+52+consecutive+values+starting+at+codepoint.%0A++%5C%24+++++++++++++++++%09Build+translation+string+by+combination+with+the+alphabetic+string.%0A++%7Ct+++++++++++++++++%09Perform+translation+on+the+current+atom.%0A++818%2B+++++++++++++++%09Add+codepoint+818+to+the+current+atom.%0A++x8%3CT+++++++++++++++%09Remove+it+again+if+x%3C8.++This+is+iff+underline+mode+is+off.%0A++y%21*++++++++++++++++%09Multiply+by+the+logical+not+of+y.++If+the+atom+is+for+formatting,+%0A+++++++++++++++++++++%09this+eliminates+output+for+this+atom%0Am++++++++++++++++++++%09map+over+atoms+using+the+enclosed+block%0A&i=*This*+is_a+**test**+of+__the+***markdown***+%60parser%60__+Multi-line+%60__should%0Abe__+supported%60.+Nothing+%60can%5C%60+escape.%0A**Underlines+__inside+the+bold__**%0A__Bold+**inside+the+underline**__%0A**Oh+I+see**+*now.*%0A%60__mark__down%60&a=1) [Answer] # [Python 3](https://docs.python.org/3/), ~~267~~ ~~253~~ ~~243~~ ~~239~~ ~~235~~ ~~229~~ ~~226~~ 224 bytes ``` import re def f(s): m=u=0;a='__','**','*','***','`' for c in re.findall(r'__|\*+|`|.|\n',s): if c in a:m,u=[a.index(c)-m,m,u,1-u][c=='__'::2] else:print([c,chr(120159+52*m+ord(c)-6*(c>'`'))][c.isalpha()]+'̲'*u,end='') ``` [Try it online!](https://tio.run/##JVBJTsQwELznFa25eMmimUGDRFD4AZy4zYwS44VYJLblRYCUV/EO/hSc4dKqrq7qarX7jqM1d@uqZ2d9BC8LIRUoHEhbwNylbv/IOtT3qEKUbuUGtjqgApT1wEGb7GuUNoJNE/ZZvVxouQxLs1wMqm6rQKt/JWvnKnVn1mS5/MKc1HOVmepQp@uZd7estj1es0VOQbbOaxPxmVd89Phw3B9OD@XpSOfSerG57ynmT/kYQrK90YFNbmSYXEv0@4NoqqQRHUJkVXi329HXUQcKOvQMKI0yRErBKuj7OMrM0Jn5D2E/TYYwOOaD9EPfw3Oaoq4nbSTkNow2TaJ4k3kSktseJ8XQwIuNozbvMHBmLgPIwJmTTY4l6x8 "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 87 bytes ``` JḤ ØṖḟØAḟØa⁷;e€@Ọ¬ =Œua6+“¡ẓƬ’a@Ç+©O3ḷr1”*ẋ“`”ṭðO®œṣ+Ça¥¥€Ñ¦Ẏ©µ"“ƈ4hẊ‘ṪỌµœṣ⁾__p€Ñ¦818Ọ¤ ``` [Try it online!](https://tio.run/##LY1BS8MwGIbv/RXBY4qDochAhHkVdBePQhLXaKu1LU2KeOu8TFQEHcgEZYibMKniZayt4CFh@x/JH6nZ8PLxft/7fO97Qn3/oqp2VD60ZF8VjyofyP72chLdmW5SfZk11c@tyKyt2UNCNmydPotXVfbmmU6fSFN2bTFural8Gtd1@gJVeWMIbKQqPuV3S3zNeqp4s2WXiJEYmTh5L95VeSfGYrJi0PnVuqvKa52a@o9F02T5oDu/CEX/eKPeWDjDqqrgvusxCDyGCICQU8YhBOERQIi71FzgGYlPnfA8MBLgiMSMxhghsJv43Fv1vYACszI3THzHOqTGYUkUhTGnDq6BvZC7XnAMcJsEBxhQ1iYRrf0B "Jelly – Try It Online") ]
[Question] [ Inspired by a restriction on [What do you get when you multiply 6 by 9? (42)](https://codegolf.stackexchange.com/questions/124242/) By order of the President, we are no longer permitted to use confusing fake numbers (i.e. numbers other than integers from 0 to 99 inclusive), and are instead to use only ***real*** numbers, that is, those that are not fake. Unfortunately, most maths are very unpatriotic at present and thus it is necessary to revolutionalize a new, revised, mathematics for the glory of the State. Your task is to create a program or function which takes as its input two numbers and provides as its output their product. Your program, obviously, must be consistent with Minitrue's standards for programmatic excellence. Specifically: * You may use ***real*** numbers in your code; users of fake numbers will be referred to Miniluv * If a fake number is provided as input, you are to raise an error to that effect raised only in this case. If your chosen language is incapable of error, you are to write a consistent Truthy or Falsy value to a different output stream than normal, this value being written to that output stream only in this case. * Your program must *never* output any fake numbers; users of fake numbers will by referred to Miniluv * Your program must output consistently with pre-Ministry math texts, except where those texts are influenced by thoughtcrime (i.e. where the input or output would be a fake number). In those cases, you are free to define whatever truth you think best furthers the Party's goals, provided your output is consistent with above principles. * Your input is guaranteed to be either two real numbers, two fake numbers, or one real and one fake number This is code golf; the shortest code in bytes wins. Some test cases: ``` Input: 0, 3 Output: 0 Input: 2, 5 Output: 10 Input: 9, 11 Output: 99 Input: 10, 10 Output*: 5 Input: -1, 0 Output*: ERROR: THOUGHTCRIME COMMITTED Input: 2, 2.5 Output*: ERROR: THOUGHTCRIME COMMITTED Input: 99, 2 Output*: 5 Input: -1, 53 Output*: ERROR: THOUGHTCRIME COMMITTED ``` Test cases with an 'Output\*' indicate that there are multiple valid outputs for that test case. Please note that while your output in the case of a fake product from real numbers may be an error, it cannot be the *same* error as for fake input (unless both cases trigger), as explained in rule #2. [Answer] ## Python 2, ~~41~~ ~~38~~ ~~41~~ 39 bytes ``` lambda a,b:a*b%-~99/(chr(a)<'d'>chr(b)) ``` -2 bytes from xnor. Uses `-~99` to get 100 legally. Relies on `u<v>w` is equivalent to `u<v and v>w`. If `a` or `b` are not integers `chr` throws a TypeError. If either are less than 0, `chr` throws a ValueError. If a or b are greater than or equal to 100 (ord('d')), then the denominator will evaluate to 0, and throws a ZeroDivisionError. Otherwise, the denominator will evaluate to 1; and returns the modded product. [Answer] # [Python](https://docs.python.org/), ~~54~~ 52 bytes ``` lambda a,b:[v for v in(a,b,a*b%-~99)if'd'>chr(v)][2] ``` An unnamed function raising an error if either of the inputs are **fake** otherwise returning the product of the inputs modulo 100 (always **real** and correct if the product itself is **real**). **[Try it online!](https://tio.run/##TY1BDoIwEEXXcIq6MG3JYMDiAhK8CLIo0AYiAimFyMarYwuYuJk/M2/@n2HRdd@xVaaPteWvouKIQ5FkM5K9QjNqOmJm4F5x9j9xTBuJK3wva0VmmmfXfLVnWozaXCJCAggoEAbRVhkzEoCxAQl3ifalH4IfbjAMrON6uZmO0sR1BtV0muCmGyadYNjCqetotRjoKDFOrUYpksQ7iHiXYtAWHlbJn@KELWlH8bdXgrc2cc@gv1d0/QI)** ### How? First creates a tuple of the inputs and their product modulo **100** using `(a,b,a*b%-~99)` where `~x` computes `-1-x` and `%` is the modulo operator. Then traverses that tuple creating a list of those values which are **real** numbers. The test for **real**-ness is performed by first attempting to cast each value, `v`, to characters with `chr(v)` - which will raise a `ValueError` if `v` is not a non-negative integer less than **256**, then checking the value is less than **100** by a less-than-comparison, `<`, to the **100th** character, `'d'`. If both `a` and `b` are **real** the list will have three entries (the product modulo 100 is alway **real**), otherwise it will have less. The `[...][2]` attempts to get the item at the second index (third item), raising an `IndexError` if it does not exist. Thus either input being **fake** results in either a `ValueError` or `IndexError`, while both inputs being **real** always succeeds and returns a **real** number, and if that product is itself **real** it is the returned value. [Answer] # JavaScript (ES6), ~~61~~ 57 bytes ``` g=x=>x<0|x>99|x%1!=0 f=(a,b)=>g(a)|g(b)|g(a*b)?f(a,b):a*b ``` Similar to the Haskell answer, creates a validation function, called `g`. `g` returns false iff `x` is not a fake number. `f` checks if the either number or the product is fake. If either number or the product is fake, it calls `f` again, which will hit a StackOverflow relatively quickly. Otherwise, it returns the product. Same length, with currying: ``` g=x=>x<0|x>99|x%1!=0 f=a=>b=>g(a)|g(b)|g(a*b)?f(a)(b):a*b ``` ``` g=x=>x<0|x>99|x%1!=0 f=(a,b)=>g(a)|g(b)|g(a*b)?f(a,b):a*b //Note that once one console.log crashes, none of the rest will execute console.log(f(0,3)) console.log(f(2,5)) console.log(f(9,11)) console.log(f(10,10)) console.log(f(-1,0)) console.log(f("Hello"," World")) console.log(f("Help","")) console.log(f(2,2.5)) ``` [Answer] # [Python 3](https://docs.python.org/3/) ~~111~~ ~~101~~ ~~75~~ ~~77~~ 59 bytes **EDIT**: -10 bytes because of Python's "ternary" operator **EDIT 2**: -26 bytes because of `lambda` and really obfuscating with the ternary operator. **EDIT 3**: +2 bytes because `range` is exclusive. Thanks @ovs for catching that **EDIT 4**: -18 bytes thanks to @ovs's suggestion ``` lambda a,b,s={*range(99+1)}:{a,b}-s and c or max({0,a*b}&s) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFRJ0mn2LZaqygxLz1Vw9JS21Cz1qoaKFqrW6yQmJeikKyQX6SQm1ihUW2gk6iVVKtWrPm/oCgzr0QjTcNQx0hTkwvOM9AxNEXmGxvrWGpq/gcA "Python 3 – Try It Online") Raises a Zero Division Error for fake numbers, returns `0` for a fake product Works by first checking if `a` and `b` are in the range of real numbers. If not, try to access the undefined variable `c`, resulting in an error. Otherwise, return either `0` or `a * b` depending on whether `a * b` is fake or real. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~(16?) 17~~ (13?) 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁶Pḟ0r99¤Ȧ$?Dṫ-Ḍ ``` Monadic link taking a list of numbers, yielding the **real** answer if the inputs and the result are **real**, yielding the product modulo **100** if the inputs are **real** but the product would not be, and raising a `TypeError` if either of the inputs are **fake**. **[Try it online!](https://tio.run/##ASYA2f9qZWxsef//UMmTO@KBtjDhuJ8wcjk5wqTIpiQ/K////1szMywzXQ)** 13 byte possible alternative (debatable), works in a similar fashion, but uses: ``` ⁶Pḟȷ2Ḷ¤Ȧ$?%ȷ2 ȷ2 - literal 100 (interpreted as 10 raised to the power of 2) Ḷ - lowered range -> [0,1,2,...99] (all the *real* numbers) ȷ2 - literal 100 (again) % - modulo ``` ### How? ``` ⁶Pḟ0r99¤Ȧ$?Dṫ-Ḍ - Main link: list of numbers, [a1, a2] ? - if: - ...the if condition: $ - last two links as a monad: ḟ - filter discard if in: ¤ - nilad followed by link(s) as a nilad: 0 - literal zero 99 - literal ninety-nine r - inclusive range -> [0,1,2,...99] - all the *real* numbers Ȧ - any and all (for our purposes: 0 if empty, 1 otherwise [since zeros were filtered out]) - ...then: ⁶ - literal space character - ...else: P - product of [a1, a2] D - convert to a list of it's decimal digits (Type Error ṫ- - tail from index -1 (keep only the last two (or less) digits) Ḍ - convert back to a number ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~74~~ 69 bytes *-5 bytes thanks to @Adnan* ``` lambda a,b,h=99+1:a*b%h if type(a)==int==type(b)and 0<=a<h>b>=0else c ``` [Try it online!](https://tio.run/##dU07C4MwGNz7K76lmNhYfECtYtw6F1ytQ6IJEXyhGSrib0/VTh16y93BPYZZq74LjKQv07CWVwwY4UTRKLp4MbP5WUEtQc@DQAxTWnea0sNxzLoK3ISyRKU8pa5oJgGlkf0IWkwa6g7y3Cd@UBDI/YCEOzseuR0ivBPPdYsiPsEGPc5fsWMYtxdkLSs4KSyrdd0mW6bRvkoksnfGGB958S7FoP90H1n2zH7qGJsP "Python 3 – Try It Online") [Answer] # [Perl 6](https://perl6.org), ~~57 54~~ 41 bytes ``` {all(@_ X~~Int,$(0..99))??+([*](@_)~~0..99)&&[*] @_!!die} ``` [Try it](https://tio.run/##lY/NasJAFIX3eYqjWE00jhklQpQ2gpWahQ2EFAoqYuPYBpIomaRFrHmx7vpi6dS/uim0m4H5vjn3nlmzOGjnKWd4bROvK4UblL3VguE6386DQO7N8JhlVpSoJVkjxDAUxTRr8rg6FUrJsgMrlwVAb1YoLHy2y5erGIEfMS4rnx/EW4VPcqNSr5iTRW08IeKcmg1hxppKp@LBfRqy2PewlYB17EcJyDJMOihetQhHsSvwm5@8IIk32Hd7L81Qv8EkZjwNkn0O4PMNDuA7sAMLxKd@VKlAQsb5/JnttbTLrWidii2aihbsNDlcpCNtqtDPlJ6xoYLSMzeME6diCtWOotqBfhJ1quKCDxzHdjpwh/bD3dDtO9ZogL49GlmuO7i92N0k@j9DhqjW/KWA3vrjsC8 "Perl 6 – Try It Online") ``` {all(@_ X~~Int,$/=0..99)??+([*](@_)~~$/)&&[*] @_!!die} ``` [Try it](https://tio.run/##lY9fa4JQHIbv/RRv4UrLjloYWDSDLZYXTRAHg4podtoEtfDoRrT8YrvbF3Nn/Vs3g@3mwO95zvv7s6ZJ2C4yRvHaJn5XiDao@KsFRa/YzsNQ6s/wmOd2nCqi2tMIMU3ZsurSuDblSs5zUZUrFV6hPyuVFgHdFctVgjCIKZPkzw/ir6InSa02qtZkUR9PCH@nlsrNWFP0Kf9wn0U0CXxsBWCdBHEKsozSDspXLcJQ7nL8FqQvSJMN9ou9izM0rjFJKMvCdJ8D2HyDA/gO7EBDftGPEkskoozNn@leC7vCjtcZn6IpaMHJ0kMhHGlTgXGm@hmbCnT9zE3zxHXeRdeOotaBcRINXcEFH7iu43bgDZ2Hu6F349qjAW6c0cj2vMHtxewmMf4ZMvlqzV8WMFp/bPYF "Perl 6 – Try It Online") ``` {all(@_ X~~Int,0..99)??[*](@_)%10²!!die} ``` [Try it](https://tio.run/##lY/LasJAGIX3eYqjaL00jhklQpQ2BSs1CxsIKRRUxMaxDSRRMpMWsfpQ3Xbni6XTeKmbQrsZmO@b8/9nliwOWmnCGV5bxOso4QoX3mLGcJWup0FQvpngcbu1IqFqhBhGxTSH1bGklSLVdh@53Mxnm3S@iBH4EePlyu6TeIvwqVwv1UrmaHY5HBF5js26NENNpWP54D4JWex7WCvAMvYjATIPRRv5YpNw5DsSv/niBSJeIevyXpigdo1RzHgSiCwH8OkKe/Ad2IAF8hM/qpAjIeN8@swyrWxSK1omcoumogk7EfuLcqANFfqJ0hM2VFB64oZx5FROodpBVNvQj6JGVZzxnuPYThtu336467tdxxr00LUHA8t1e7dnuxtE/2fIkNUavxTQm38c9gU "Perl 6 – Try It Online") Throws an error with the message of `Died` if given a non-**Real** number. (left intentionally vague to confuse the perpetrator, which gives more time to collect them for re-education) The first two examples return `0` rather than produce a non-**Real** number. The third one constrains its result to a **Real** number using the modulus operator. ## Expanded: ``` { # bare block lambda with implicit parameter list of 「@_」 all( # check if all tests pass @_ # the input X~~ # cross 「X」 smartmatched 「~~」 with the following Int, # All **Real** numbers are Ints 0..99 # Range of all **Real** numbers ) ?? # if all inputs are **Real** numbers [*](@_) # reduce using &infix:« * » operator % # modulus 10² # 10 to the power of 2 !! # die if any input was not a **Real** number die } ``` Note that `10²` is parsed as `10` followed by a postfix operator. [Answer] # Haskell, 67 bytes ``` v a=not$0<=a&&a<=99 a#b|(v a)||(v b)=error""|v$a*b=error""|True=a*b ``` [Answer] # [Haskell](https://www.haskell.org/), ~~35~~ 41 bytes ``` a#b|all(`elem`[0..99])[a,b]=mod(a*b)$1+99 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P1E5qSYxJ0cjITUnNTch2kBPz9IyVjM6UScp1jY3P0UjUStJU8VQ29Lyf25iZp6CrUJKPpdCQVFmXomCioKxsgmCY2igbGiEImdg8B8A "Haskell – Try It Online") Example usage: `3#4` returns `12`, while *fake* numbers like `3.5#4`, `300#4` and `(-3)#4` all yield the error `non-exhaustive pattern in function #`. Non-fake inputs whose product would be greater than 99 result in the product modulus 100. **Edit:** Thanks to Jonathan Allan for pointing out that I initially missed a part of the challenge. [Answer] # [Ruby](https://www.ruby-lang.org/), 52 bytes Returns `NoMethodError` if the input has a fake number. ``` ->a,b{a.chr;b.chr;(r=0..99)===a&&r===b ?a*b%-~99:+p} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9cuUSepOlEvOaPIOglMahTZGujpWVpq2traJqqpFQGpJAX7RK0kVd06S0sr7YLa/wUKaXrJiTk5ClqpZYk5GumpJcWa/6MtLXVMYgE "Ruby – Try It Online") [Answer] # Java 8, 58 bytes ``` (x,y)->new Long(0>x||x>99||0>y||y>99?"":x*y>99?"0":x*y+"") ``` [Try it online!](https://tio.run/##bY/BboJAEIbvPMWE09IiwaOa4kGxmJSaIJ6aHkaYRSwsZFksRHx2XNtDLz39XyaZ/5s54wUn5/RrTApsGggxF1cjF4okx4Rgcy0qkQFnegRowyOO1uJm1O2xyBNoFCodlypPodS7bK9kLrKPT0CZNdbViE@SMHUaUmvi2BbqIBJss5Pyu4RqlVciQJEWJBlTNlkTb983ikqnapVT6ypVCEZaq0UioYrDe1seSW4qWeJfByzB9KNoF80hDnaH1yBeRdvQh9UuDLdx7K9NmANZ1sLYAIeXkXV2r12CvuFN/8dcrxuGzpvNhsH1@mHoNS5Nc949/ZL7g8@maY2Lfw7kDmdT1566D8PtNt4B) Throws a NumberFormatException for fake inputs, returns 0 for fake outputs. I added a small easter egg to the TIO example that prints "ERROR: THOUGHTCRIME COMMITTED" if a NumberFormatException is thrown, just for fun. [Answer] # [R](https://www.r-project.org/), 70 bytes Probably a cleverer way to do this all the conditionals. ``` function(a,b)`if`(`if`(a<0|a>99|b<0|b>99|a%%1>0|b%%1>0,,a*b)>99,5,a*b) ``` [Try it online!](https://tio.run/##K/pflJqYE1CUn1KaXKJgo6vwP600L7kkMz9PI1EnSTMhMy1BA0wk2hjUJNpZWtYkARlJIEaiqqqhHZANpnR0ErWSNIHCOqZgFrKxGgY6xpqcygoGXMiCRjqmIEFDVFFLHUNDkLClJYqwoYGOoQFI3BRFWNdQByzqGhTkH4RmupGeKXYpoBuNsBplaozQ8B8A "R – Try It Online") ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/124071/edit). Closed 6 years ago. [Improve this question](/posts/124071/edit) A [narcissist program](https://esolangs.org/wiki/Narcissist) is a program that only accepts its own source code. A [bigotous program](https://esolangs.org/wiki/Bigot) is a program that only accepts the source code of programs semantically equivalent to itself. A gang member is somewhere in between. In particular, we will define a **gang** as set of programs `G`, which may or may not be in the same programming language, such that each program, when executed, will only accept members of its gang, and reject everything else (since they all do the same thing, this means that are semantically equivalent). A gang member is a program that is part of a gang, and the set of programs that it accepts is its gang. So, a narcissist program is a gang of size 1, and a class of bigots is a maximally sized gang (every equivalent program gets to be part of the gang). Your job is to create a gang of programs. It must be of size at least 2, and can have programs in different languages (you can even count the same program multiple times if it's a polyglot). Your score is (average length of gang member)/(# of unique programming languages), which you are trying to minimize (so you are rewarded for using different languages). It is considered cheating to use built in language features that allow a program to access its own code. Note: We'll define acceptance v.s. rejection via <https://codegolf.meta.stackexchange.com/a/12685/16842> or <https://codegolf.meta.stackexchange.com/a/12684/16842>, your choice. [Answer] # 0 points (average length 0 bytes, 2 unique language) I'm assuming we can define acceptance and rejection as the output of two different values. The gang size is 2 (the languages are **05AB1E** and **2sable**), and the program is the empty program. For some reason, both an empty **05AB1E** program and an empty **2sable** program appear to outputs `2` (plus a newline in the case of 2sable) when the input is not empty (i.e. a different program; rejection). They output nothing if there is no input (i.e. the same program; acceptance). Since I "can even count the same program multiple times if its a polygot", these are two programs. *(I know neither 05AB1E nor 2sable at all and just tried golfing languages in TIO until I found some that seemed to work, so this answer might be wrong if they output something else for some specific inputs.)* [Answer] # 140.75 points (average length 281.5 bytes, 2 unique languages) These programs use cryptographic hashing to identify the gang members, and the first line of each program is identical and encodes the hash of the remainder of each program. Each program then compares the first line to the given list and the hash of the remainder, and returns `true`/`True` if it's accepted and `false`/`False` if it's rejected. **JavaScript (Node.js)**, 338 bytes ``` x=["69fa7652b24a3aa2a56122db2f3ce27395a3be0a6e6eed00b01592b9","604e0bb526a9af96f90a964c3849be96862bb3d31b9fcfbc83d6c7aa"] c=[] process.stdin.on('data',d=>c.push(d)).on('end',_=>console.log((d=Buffer.concat(c)).slice(0,121)=='x='+JSON.stringify(x)&&x.some(y=>y==require('crypto').createHash('sha224').update(d.slice(121)).digest('hex')))); ``` **Python 2**, 225 bytes ``` x=["69fa7652b24a3aa2a56122db2f3ce27395a3be0a6e6eed00b01592b9","604e0bb526a9af96f90a964c3849be96862bb3d31b9fcfbc83d6c7aa"] import hashlib,sys,json I=sys.stdin print I.read(121)=='x='+json.dumps(x,separators=',:')and hashlib.sha224(I.read()).hexdigest()in x ``` [Answer] # ∞ points (Average length ∞, 1 unique language) I might not win the challenge, but I sure have the biggest gang. (Watch out!) ``` main=interact$ \x->if length(lines x)==1&&take 279x==quine q++"--"then"Yarr!"else"It's one of them PyRulez guys!";quine s=s++show s;q="main=interact$ \\x->if length(lines x)==1&&take 279x==quine q++\"--\"then\"Yarr!\"else\"It's one of them PyRulez guys!\";quine s=s++show s;q="-- ``` The language is Haskell. You can keep adding any letter to the end of the program except newlines. Outputs `Yarr!` for gang members and `It's one of them PyRulez guys!` [for everything else](https://codegolf.stackexchange.com/a/124100/43037). --- # 141.9 points (Average length 141.9 bytes, 1 unique language, 255 gang members) ``` f x=elem '\n'x||take 141x/=k q++"--"||length x>142;k s=s++show s;q="f x=elem '\\n'x||take 141x/=k q++\"--\"||length x>142;k s=s++show s;q="-- ``` [Answer] ## 0 points (Average length 24 bytes, ∞ unique languages) This is noncompeting since [the MetaGolfScript family is banned](https://codegolf.meta.stackexchange.com/a/5076/16842), but I thought it would be fun to post it anyways. The languages are MetaGolfScript-`N`, for every natural number `N`. There is one program in each language, which all have the following source code: ``` {s ":p`:s;p" + =}:p`:s;p ``` ]
[Question] [ ## Challenge Given a number, `x` where `-1 ≤ x ≤ 1`, and the integers `a` and `b`, where `b > a`, solve the equation `sin(θ) = x` for `θ`, giving *all* solutions in the range `a° ≤ θ ≤ b°`. ## Rules `x` will have a maximum of three decimal places of precision. The output, `θ`, must also be to three decimal places, no more, no less. Your output may be as a list or separated output. You may use built-in​ trig functions. You may not use radians for `a` and `b`. You will never be given invalid input. Output may be in any order. ## Examples ``` x, a, b => outputs 0.500, 0, 360 => 30.000, 150.000 -0.200, 56, 243 => 191.537 0.000, -1080, 1080 => 0.000, 180.000, 360.000, 540.000, 720.000, 900.000, 1080.000, -1080.000 -900.000, -720.000, -540.000, -360.000, -180.000 ``` ## Winning Shortest code in bytes wins. [Answer] # Fortran 95 (gfortran), 180 bytes ``` #define G >=i)write(*,'(f9.3)') #define H read(*,*) program a H x H i H j o=ASIN(x)*57.2957 p=o-180+o q=o-360*999 do r=q-p if(r<=j.and.r G r if(q>=j)exit if(q G q q=q+360 enddo end ``` Structure ungolfed: ``` program a implicit none real :: x integer :: i integer :: j real :: o real :: r real :: q real :: p read(*,*) x read(*,*) i read(*,*) j o=ASIN(x)*57.2957 p=o-180+o q=o-360*999 do r=q-p if(r<=j.and.r >=i) then write(*,'(f9.3)') r endif if(q>=j) then exit endif if(q >=i) then write(*,'(f9.3)') q endif q = q + 360 end do end program a ``` [Answer] ## Mathematica, 60 bytes ``` NumberForm[t/.NSolve[Sin[t/180Pi]==#&&#2<=t<=#3,{t}],{9,3}]& ``` input > > [0, -1080, 1080] > > > output > > {-1080.000,-900.000,-720.000,-540.000,-360.000,-180.000,0.000,180.000,360.000,540.000,720.000,900.000,1080.000} > > > [Answer] # APL, ~~51~~ ~~46~~ ~~40~~ 39 bytes [*3 bytes saved thanks to @KritixiLithos*](https://chat.stackexchange.com/transcript/message/37696773#37696773) [*~~6~~ 7 bytes saved thanks to @Adám*](https://chat.stackexchange.com/transcript/message/37698973#37698973) ``` {3⍕⍵/⍨1E¯6>|⎕-1○○⍵÷180}⊢+1E3÷⍨(⍳1001×-) ``` Called as a dyad with `a` as left argument and `b` as right argument, prompts for `x`. Requires `⎕IO←0`. **How?** ``` ⊢+1E3÷⍨(⍳1001×-) ⍝ build the range a to b with step of 0.001 1001×- ⍝ 1001 * (b - a) ⍳ ⍝ range 1E3÷⍨ ⍝ divide every element by 1000 ⊢+ ⍝ add a back {3⍕⍵/⍨1E¯6>|⎕-1○○⍵÷180} ⍝ filter the solutions ○⍵÷180 ⍝ convert to radian - π * ⍵ / 180 1○ ⍝ compute sine |⎕- ⍝ distance from x 1E¯6> ⍝ small enough ⍵/⍨ ⍝ compress with the original list 3⍕ ⍝ format to 3 decimal places ``` [Answer] # PHP>=7.1, 88 Bytes ``` for([,$s,$f,$t]=$argv;$f<=$t;$f+=.001)round(sin(deg2rad($f)),5)!=$s?:printf("%.3f_",$f); ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/181dbe0f689ec98b8826a984742482518da08990) [Answer] # Python 2, 100 bytes ``` from math import* x,a,b=input() while a<=b: if round(sin(pi*a/180),5)==x:print a a=round(a+.001,3) ``` [**Try it online**](https://tio.run/nexus/python2#LY1RCoMwEES/zSkWvxIb7aZWEdscJraKCzWGGKm3t7EtDDM8GGYWnabpPvh5gsmEEWhysw8Z26SRnSbr1sAFe4/06sHcddeyhAbw82qffCHLHWXmrBoUshJab63zZAMYlhj9K5lTgahkKfZ49B9Sbb/1D76I27e@Y1EhSogqa2Q5FpcDq1rC5VoyjAMRc4VNjMM/) [Answer] # Axiom, ~~266~~ ~~215~~ 210 bytes ``` g(y,a,b)==(r:List Float:=[];t:=y+truncate((a-y)/360)*360;repeat(t>b=>break;if t>=a then r:=append(r,[t]);t:=t+360);r) f(x,a,b)==(abs(x)>1 or a>b=>[];y:=asin(x)*180/%pi;z:=180-y;sort(append(g(y,a,b),g(z,a,b)))) ``` ungolf and test ``` -- g/180=r/pi => r=pi*g/180 --y+k*360=a -- a-y -- k=------ -- 360 -- find all angles of the same class of angles [y+k*360] in interval [a,b] gg(y,a,b)== r:List Float:=[] t:=y+truncate((a-y)/360)*360 --truncate(1.9)=1, truncate(-3.1)=-4 is ok repeat t>b=>break if t>=a then r:=append(r,[t]) t:=t+360 r -- ff returns the list of solution y of sin(y)=x with y in the interval [a,b] ff(x,a,b)== abs(x)>1 or a>b =>[] y:=asin(x)*180/%pi -- z and y are the only 2 solutions in one 360 Len interval z:=180-y sort(append(gg(y,a,b),gg(z,a,b))) (6) -> f(0.5, 0, 360) (6) [30.0,150.0] Type: List Float (7) -> f(-0.2, 56, 243) (7) [191.5369590328 1548769] Type: List Float (8) -> f(0.0, -1080, 1080) (8) [- 1080.0, - 900.0, - 720.0, - 540.0, - 360.0, - 180.0, 0.0, 180.0, 360.0, 540.0, 720.0, 900.0, 1080.0] (14) -> m:=f(-0.1, -2035, -243) (14) [- 1974.2608295227 33214, - 1805.7391704772 66786, - 1614.2608295227 33214, - 1445.7391704772 66786, - 1254.2608295227 33214, - 1085.7391704772 66786, - 894.2608295227 332137, - 725.7391704772 667863, - 534.2608295227 332137, - 365.7391704772 667863] Type: List Float (15) -> map(x+->sin(%pi*x/180), m) (15) [- 0.0999999999 9999999987, - 0.1000000000 0000000016, - 0.0999999999 9999999986 2, - 0.1000000000 0000000028, - 0.0999999999 9999999985 4, - 0.1000000000 0000000018, - 0.0999999999 999999999, - 0.1000000000 0000000019, - 0.0999999999 9999999989 2, - 0.1000000000 0000000014] Type: List Float ``` [Answer] # [R](https://www.r-project.org/), 74 bytes ``` function(x,a,b,u=seq(a,b,.001))sprintf("%.3f",u[abs(sinpi(u/180)-x)<1e-6]) ``` [Try it online!](https://tio.run/##FYzBCoMwEETv/QoRhF3YpBtTg4f6JdKDFhdySdUY8O/TBIaZxzvMmWXKksL38r8ANy20UpridkAlzWwQ4376cAm0nbbSUpqXNUL0YfeQnmZkVDe@zabcB7MA64GZmhLrGB8CinVfzeCo6V@2Ki7HxSjDY5namP8 "R – Try It Online") The tolerance `1e-6` was chosen to fit the second test case, so is somewhat arbitrary. This answer takes advantage of R's vectorized functions. ]
[Question] [ Just curious if someone can provide a short example of code that causes a compiler's optimizer to behave incorrectly: * without optimization (or at lower optimization), code takes X seconds to run * with optimization (or at higher optimization), code takes Y seconds to run where Y > X In other words, the optimizer's cost model causes it to make a poor decision with a specific case, even though (presumably) it makes good decisions in general. This is meant for C (with gcc the comparisons should be between `-O0`, `-O1`, `-O2`, `-O3` in increasing order of optimization), but any compiled language should work. [Answer] # C (gcc 6.2.0-5ubuntu12 x86\_64), 58 bytes ``` typedef struct{long a,b}s;s f(long*c){return(s){*c,c[1]};} ``` Compiled with -O1, we get the following assembly code (minus boilerplate): ``` f: movq 8(%rdi), %rdx movq (%rdi), %rax ret ``` With -O3, it looks like this: ``` f: movdqu (%rdi), %xmm0 movaps %xmm0, -24(%rsp) movq -24(%rsp), %rax movq -16(%rsp), %rdx ret ``` This is obviously worse (the first version copies from memory to registers directly, the second version copies from memory into the wrong register, back into scratch space in memory, and then from there into the correct registers, which is just doing more work for no gain). This is a pretty longstanding example of a silly gcc miscompilation. In older versions of gcc, the -O3 code was even worse (containing a full function setup/teardown sequence, stack protection checks, and the like); it seems to have improved somewhat in the more recent versions. Incidentally, clang produces code almost identical to gcc's -O1 at any positive optimization level (the only difference is that sometimes the two assignments are done in the other order). ]
[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 2 years ago. [Improve this question](/posts/76965/edit) Okay, I propose a shortest-key-logger challenge. As explained by the gentleman at "[Are key-logger questions allowed?](http://meta.codegolf.stackexchange.com/questions/8866/are-key-logger-questions-allowed)", strict rules have to be imposed in order to make this challenge valid for PPCG. 1. The key-logger has to run on Windows, Linux or Mac OSX (any programming language is welcome). 2. Upon execution, it has to show the message: "I'm gonna log you" (either in a console or using GUI). 3. The keys that are relevant for logging in this challenge are letters (case is not important) and numbers, all others such as symbols, control keys and whitespace are optional and can be ignored. 4. All relevant key presses that occur during runtime (even when the application is not in focus) have to be saved in a log file that can be read and verified using any text editor (even an esoteric one, as long as I can verify it using that text editor). Anyone up for it? Whatdayatink? [Answer] # Bash, 90 bytes This works on Ubuntu, and requires `evtest`. It picks a device that is a keyboard, and saves `evtest`'s output to the file `l`. If you want a more formatted output, I can do that with more bytes. ``` echo I\'m gonna log you sudo evtest /dev/input/by-path/`ls /dev/input/by-path/|grep kbd`>l ``` ]
[Question] [ Let \$\mathbb{B} = \mathbb{Z}\_2 = \{0, 1\}\$ be the set of booleans. A *symmetric boolean function* in \$n\$ arguments is a function \$f\_S : \mathbb{B}^n \to \mathbb{B}\$ that checks if the number of its true arguments is in \$S\$, i. e. a function \$f\_S\$ such that $$f\_S(\alpha\_1, \alpha\_2, \ldots, \alpha\_n) = \left(\sum\_{1 \le i \le n}\alpha\_{i}\right) \in S$$ or equivalently $$f\_S(\alpha\_1, \alpha\_2, \ldots, \alpha\_n) = |\{ i : \alpha\_i \}| \in S. $$ These functions are called symmetric boolean function because they are all the boolean function that do not depend on argument order. The set of boolean numbers forms a [*field*](https://en.wikipedia.org/wiki/Field_%28mathematics%29), conventionally denoted \$GF(2)\$, where multiplication is logical and (\$\wedge\$) and addition is exclusive or (\$\oplus\$). This field has the properties that \$-\alpha = \alpha\$, \$\alpha / \beta = \alpha \wedge \beta\$ (for all \$\beta \neq 0\$), \$\alpha \oplus \alpha = 0\$ and \$\alpha \wedge \alpha = \alpha\$ for all \$\alpha\$ in addition to the field properties. For convenience, I am going to write \$\oplus\$ as \$+\$ and leave out \$\wedge\$ in the next paragraphs. For example, I will write \$\alpha \oplus \beta \oplus \alpha \wedge \beta\$ as \$\alpha + \beta + \alpha\beta\$. Every boolean function can be expressed as a polynomial over the field of boolean numbers. Such a polynomial is called a *[Zhegalkin polynomial](https://en.wikipedia.org/wiki/Zhegalkin_polynomial),* the representation is canonical, i. e. there is exactly one polynomial that represents a given boolean function. Here are some examples for boolean functions and their corresponding Zhegalkin polynomials: * \$\alpha \vee \beta = \alpha + \beta + \alpha\beta\$ * \$\alpha \wedge \neg\beta = \alpha + \alpha\beta\$ * \$(\alpha \to \beta) \oplus \gamma = 1 + \alpha + \gamma + \alpha\beta\$ * \$\neg(\alpha \wedge \beta) \vee \gamma = 1 + \alpha\beta + \alpha\beta\gamma\$ * \$f\_{\{1, 4\}}(\alpha, \beta, \gamma, \delta) = \alpha + \beta + \gamma + \delta + \alpha\beta\gamma + \alpha\beta\delta + \alpha\gamma\delta + \beta\gamma\delta + \alpha\beta\gamma\delta\$ where the triple terms \$(\alpha\beta\gamma + \alpha\beta\delta + \alpha\gamma\delta + \beta\gamma\delta)\$ are required because otherwise we would have \$f(1,1,1,0) = 1\$, and \$3 \not\in \{1, 4\}\$. One observation we can make is that due to symmetry, the Zhegalkin polynomial for a symmetric boolean function always has the form $$f\_S(\alpha\_1, \alpha\_2, \ldots, \alpha\_n) = \sum\_{i \in T\_{S,n}}t\_{n,i}$$ where \$\sum\$ denotes summation with exclusive or and \$t\_{n, i}\$ is the sum of all product terms that use \$i\$ out of the \$n\$ arguments to \$f\_S\$ and \$T\_{S,n} \subseteq \{0, 1, \ldots, n\}\$ is a set describing those \$t\_{n, i}\$ we need to construct \$f\_S(\alpha\_1, \alpha\_2, \ldots, \alpha\_n)\$. Here are some examples for \$t\_{n, i}\$ so you can get an idea what they look like: * \$t\_{4, 1} = \alpha + \beta + \gamma + \delta\$ * \$t\_{3, 2} = \alpha\beta + \alpha\gamma + \beta\gamma\$ * \$t\_{4, 4} = \alpha\beta\gamma\delta\$ * for all \$n\$: \$t\_{n, 0} = 1\$ We can thus describe an \$f\_S\$ in \$n\$ arguments completely by \$n\$ and \$T\_{S, n}\$. Here are some test cases: * \$T\_{\{1, 4\}, 4} = \{1, 3, 4\}\$ * \$T\_{\{2, 3, 4\}, 4} = \{2, 4\}\$ * \$T\_{\{2\}, 4} = \{2, 3\}\$ * \$T\_{\{1, 2\}, 2} = \{1, 2\}\$ (logical or) * \$T\_{\{2, 3\}, 3} = \{2\}\$ (median function) The task in this challenge is to compute \$T\_{S, n}\$ given \$S\$ and \$n\$. You can choose an appropriate input and output format as you like. This challenge is *code-golf,* the shortest solution in octets wins. As a special constraint, your solution must run in polynomial time \$O(n^k)\$ where \$n\$ is the \$n\$ from the input. [Answer] ## Dyalog APL, 15 bytes ``` {2|⍺⌹⍉∘.!⍨0,⍳⍵} ``` Matrix division, basically. Takes input like `0 0 1 1 1 {2|⍺⌹⍉∘.!⍨0,⍳⍵} 4` for T4({2,3,4}). ``` { } Dyadic function: ⍵ Right argument 4 ⍳ Index vector 1 2 3 4 0, Append 0 0 1 2 3 4 ∘. Outer product —————————— ⍨ |With itself 1 0 0 0 ! |By binomial coeff. 2 1 0 0 ⍉ Matrix transpose 3 3 1 0 Result at this step: -> 4 6 4 1 ⍺ Left argument ⌹ Matrix division (A⌹B is A^-1 B, not A B^-1) (implicitly converts ⍺ to column vector) 2| Modulo 2 ``` Since the transposed matrix of binomial coefficients is lower triangular with determinant 1, its inverse will only contain integers. So to matrix-divide over **F2** we can just matrix-divide over the reals, then mod by 2. Matrix division is an O(n^3) operation, and calculating each of the O(N^2) binomial coefficients is well below O(n^3), so this runs in O(N^5). Try it [on TryAPL](http://tryapl.org/?a=0%201%200%201%201%7B2%7C%u237A%u2339%u2349%u2218.%21%u23680%2C%u2373%u2375%7D4%20%u235DT_%7B1%2C3%2C4%7D%2C4&run). [Answer] # R, 115 bytes ``` function(S,n)which(abs(solve(sapply(1:n,function(k)(sapply(1:n,function(j)choose(j,k)%%2))),is.element(1:n,S)))==1) ``` The key is realizing that the sum of t's that evaluate to a T value is just the choose function. A slightly ungolfed version that doesn't calculate in polynomial time is below, but illustrates the derivation of the t's a little better (just run the middle line). ``` function(S,n)which(abs(solve( sapply(1:n,function(k)(sapply(1:n,function(j)sum(apply(combn(c(rep(T,j),rep(F,max(0,k-j))),k),2,all))%%2))), is.element(1:n,S)))==1) ``` [Answer] ## CJam (25 24 bytes) ``` {_,{1$_,,2$~f&:!.*:^t}/} ``` This is an anonymous function which takes an array of `0` or `1` which serves as an indicator function for \$S\$ and returns an array of `0` or `1` which serves as an indicator function for \$T\$. E.g. to find \$T\_{\{1, 4\}, 4}\$ you pass `[0 1 0 0 1]` and it returns `[0 1 0 1 1]`. [Online demo](http://cjam.aditsu.net/#code=%5B%5B0%201%200%200%201%5D%5B0%200%201%201%201%5D%5B0%200%201%200%200%5D%5B0%201%201%5D%5B0%200%201%201%5D%5D%0A%0A%7B_%2C%7B1%24_%2C%2C2%24~f%26%3A!.*%3A%5Et%7D%2F%7D%0A%0A%25%60) ### Explanation Recall that \$t\_{n,i}\$ is the sum of all product terms that use \$i\$ out of the \$n\$ arguments to \$f\_S\$. Suppose that \$s\$ of the \$n\$ arguments are true. Then we have three cases for \$t\_{n,i}(\alpha\_0, \ldots, \alpha\_{n-1})\$: * \$i > s\$ : none of the terms is true, so \$t\_{n, i}(\alpha\_0, \ldots, \alpha\_{n-1}) = 0\$ * \$i = s\$ : exactly one of the terms is true, so \$t\_{n, i}(\alpha\_0, \ldots, \alpha\_{n-1}) = 1\$ * \$i < s\$ : there are \$\binom{s}{i}\$ terms which are true, so \$t\_{n, i}(\alpha\_0, \ldots, \alpha\_{n-1}) = \binom{s}{i} \bmod 2\$ If we let \$\sigma\$ be the indicator function for \$S\$ and \$\tau\$ be the indicator function for \$T\_{S, n})\$, we therefore get the matrix identity $$\begin{pmatrix}1 & 0 & 0 & \ldots & 0 \\ \binom{1}{0} & 1 & 0 & \ldots & 0 \\ \binom{2}{0} & \binom{2}{1} & 1 & \ldots & 0 \\ \vdots & \vdots & \vdots & \ddots & 0 \\ \binom{n}{0} & \binom{n}{1} & \binom{n}{2} & \ldots & 1 \end{pmatrix} \begin{pmatrix}\tau(0) \\ \tau(1) \\ \tau(2) \\ \vdots \\ \tau(n) \end{pmatrix} = \begin{pmatrix}\sigma(0) \\ \sigma(1) \\ \sigma(2) \\ \vdots \\ \sigma(n) \end{pmatrix} $$ which is dead easy to solve because the coefficient matrix is already in row-reduced echelon form. Note that this is quite a well-known matrix, because it's the binomial coefficients modulo 2, which famously forms a Sierpiński triangle. I calculate them using [Lucas' theorem](https://en.wikipedia.org/wiki/Lucas%27_theorem) and bit-twiddling as `2$~f&:!` ]
[Question] [ This question is inspired by [retrograde music](http://en.wikipedia.org/wiki/Retrograde_(music)). Retrograde music is a piece of music that can both be played normally (from the beginning to the end) as reversed (from the end the beginning). A similar thing exists in literature, this is called a [semi-palindrome](http://en.wikipedia.org/wiki/Palindrome#Semordnilaps), e.g. "roma" and "amor". Your task is to write a retrograde program. If executed normally it has to encode a string with the [morse](http://en.wikipedia.org/wiki/Morse_code) code, decode it when executed reversed. # Task You're to write a program or function that accepts a string and outputs it's morse code encoding (STDIN and STDOUT are used in case of a program, a function receives it's input as a function argument and returns a string). However, when you run the reverse of the program, it works the same except it decodes the input. Note that you don't have to use the same programming language. The reversing of the program is done manually. # Details * Comments are not allowed in your program, as they would make this task very easy. * You have to use the [international morse code](http://www.sckans.edu/~sireland/radio/code.html). This includes letters, numbers and some punctuation. See the link for a complete list. No prosigns or special characters have to be supported. There's one exception mentioned in the edit. * You have to represent dots and dashes with `.` and `-`. * Letters are separated with (spaces), words are separated with `/` (slashes). * You can choose to use either use lower or uppercase. However, you have to be consistent (if your program only uses uppercase, the reversed program must do so too). * You can assume the program will only receive valid input. # Example Input of the normal program or output of the reversed program: ``` MORSE CODE? ``` Output of the normal program or input of the reversed program: ``` -- --- .-. ... . / -.-. --- -.. . ..--.. ``` # Score Because I want to reward both clever (short) algorithms and creativity, Your score will be based upon your votes and the program length. Concretely, it will be `100 * amount of votes / program length (in bytes)` **EDIT**: The morse code site I mentioned uses the same code for opening and closing parentheses, however it's not my intention to let you implement a feature for recognizing this. So you have to use these more modern morse codes for the parentheses: ``` ( = -.--. ) = -.--.- ``` [Answer] # Perl 5: too long to care (740 though) Just wanted to see if it will be possible to write this in a language with non single character statements. The result is not pretty, but works. Most of the code is used in both decoder and encoder, but the `eval+'{code}'` trick shows a loophole which could be used to write completely separate code for decoder and encoder. Fixed all known problems. Supports both lower and upper case input with all punctuation characters mentioned on the page linked in the question. Encoder: ``` ;;$^;s,.*,reverse+uc,e; tr,+?.(),+~=<>,+rt; 1while+s/E/#_/s+s/T/`_/s+s! !{_!s+elihw1; 1while+s/A/`#_/s+s/N/#`_/s+s/I/##_/s+s/M/``_/s+elihw1; 1while+s/O/```_/s+s/D/##`_/s+s/R/#`#_/s+s/S/###_/s +s/G/#``_/s+s/U/`##_/s+s/W/``#_/s+s/K/`#`_/s+elihw1; 1while+s/B/###`_/s+s/C/#`#`_/s+s/P/#``#_/s+s/Q/`#``_/s +s/F/#`##_/s+s/H/####_/s+s/V/`###_/s+s/J/```#_/s +s/X/`##`_/s+s/L/##`#_/s+s/Y/``#`_/s+s/Z/##``_/s+elihw1; 1while+s/1/````#_/s+s/2/```##_/s+s/3/``###_/s+s!<!#``#`_!s +s/4/`####_/s+s/5/#####_/s+s/6/####`_/s+s/7/###``_/s +s/8/##```_/s+s/9/#````_/s+s/0/`````_/s+s!/!#`##`_!s+elihw1; 1while+s/~/##``##_/s+s/=/`#`#`#_/s+s/,/``##``_/s +s/:/###```_/s+s/'/#````#_/s+s/"/#`##`#_/s +s/-/`####`_/s+s!>!`#``#`_!s+elihw1; tr,+{`#_,+/\-\. ,+rt; ;;$^;s,.*,reverse,e; s/ //s ``` Decoder: ``` s// /s ;e,esrever,*.,s;^$;; ;tr+, .\-\/+,_#`{+,rt ;1while+s!_`#``#`!>!s+s/_`####`/-/s+ s/_#`##`#/"/s+s/_#````#/'/s+s/_```###/:/s+ s/_``##``/,/s+s/_#`#`#`/=/s+s/_##``##/~/s+elihw1 ;1while+s!_`##`#!/!s+s/_`````/0/s+s/_````#/9/s+s/_```##/8/s+ s/_``###/7/s+s/_`####/6/s+s/_#####/5/s+s/_####`/4/s+ s!_`#``#!<!s+s/_###``/3/s+s/_##```/2/s+s/_#````/1/s+elihw1 ;1while+s/_``##/Z/s+s/_`#``/Y/s+s/_#`##/L/s+s/_`##`/X/s+ s/_#```/J/s+s/_###`/V/s+s/_####/H/s+s/_##`#/F/s+ s/_``#`/Q/s+s/_#``#/P/s+s/_`#`#/C/s+s/_`###/B/s+elihw1 ;1while+s/_`#`/K/s+s/_#``/W/s+s/_##`/U/s+s/_``#/G/s+ s/_###/S/s+s/_#`#/R/s+s/_`##/D/s+s/_```/O/s+elihw1 ;1while+s/_``/M/s+s/_##/I/s+s/_`#/N/s+s/_#`/A/s+elihw1 ;1while+s!_{! !s+s/_`/T/s+s/_#/E/s+elihw1 ;tr+,><=~+,)(.?+,rt ;e,cu+esrever,*.,s;^$;; ``` Usage ``` $ perl -lp retr.pl <<<"(Morse) Code?" -.--. -- --- .-. ... . -.--.- / -.-. --- -.. . ..--.. $ perl -p0e '$_=reverse' retr.pl >rter.pl $ perl -lp rter.pl <<<"-.--. -- --- .-. ... . -.--.- / -.-. --- -.. . ..--.." (MORSE) CODE? ``` Explanation: ``` ;;$^;s,.*,reverse+uc,e; # parses as $^; s/.*/reverse uc/e # and in decoder as e; cu + esrever; *.; s/^$// # reverse and uppercase input, no-op in decoder tr,+?.(),+~=<>,+rt; # parses as tr/+?()/+=<>/ + rt # in decoder as tr/,><=~/,)(.?/ , rt # equivalent to y/?.()/~=<>/ and y/><=~/)(.?/ in decoder 1while+s/T/`_/s+elihw1; # parses as while(+s/T/`_/+elihw1){1} # => while(s/T/`_/s+0){} # equivalent to s/T/`_/g and s/_`/T/g in decoder s/ //s # remove leading space / add leading space ``` [Answer] # CJam, ~~349~~ 284 bytes This is the encoder from plaintext to International Morse code: ``` L;"q['[,65>A,841306689079511650 64b:c]s"~"*S/as/'res]c:b46 056115970986603148,A>56,['[/,'c:+f34b4i%Ws;\\";L 2750763932992480612976738964894343100372667569857057816704667471637641979761595859190213443543359288493237588430216583759463627409436875398907 L;"\\;4b43f+:c',/erS/'/*S*"~"/Sq";L ``` The reverse string of which is: ``` L;"qS/"~"*S*/'/Sre/,'c:+f34b4;\\";L 7098935786349047263649573856120348857323948829533453443120919585951679791467361747664076187507589657662730013434984698376792160842992393670572 L;"\\;sW%i4b43f+:c',/['[,65>A,841306689079511650 64b:c]ser'/sa/S*"~"s]c:b46 056115970986603148,A>56,['[q";L ``` which decodes an International Morse Code representation back to plain text. (New lines just for show) This supports capital alphabets `A-Z`, number `0-9` and `.,:?'-/()"` punctuation marks, where Morse Code for `(` and `)` is same. How it works: The trick here is simple, CJam supports evaluation of any random string as a code using the operator `~`. So if you have something like `"code in a string"~"another code in a string"`, then when running normally, the first string will be evaluated while the second one will remain a string. But when running the reverse of the code, the second string will be evaluated, while the first will remain a string. So now you just have to make sure that you have your code in the above format along with a logic to remove the second string while running in normal fashion and the first string while running the reverse code. This gives us something like: ``` ];"code for encoding to morse"~"reverse of code for decoding from morse";] ``` whose reverse will be ``` ];"code for decoding from morse"~"reverse of code for encoding to morse";] ``` This works like: ``` ]; "Create an empty array and pop it from stack"; "code 1"~ "Put a string with code 1 and evaluate it"; "code 2"; "Put the string for code 2 and pop it from stack"; ] "Wrap everything in an array. Noop as last operation"; ``` The reverse of it is just code 1 replaced by reverse of code 2 and vice-versa, so it works in a similar manner. Now the actual code which encodes/decodes is a simple transliteration from the plaintext to morse and vice-versa. [Try it online here](http://cjam.aditsu.net/) [Answer] # CJam, 286 bytes, no eval Original (Morse encoder): ``` L;"'*S/as/'res]c:b46 056115970986603148,A>56,['[/,'c:+f34b4i%Ws;\;";q['[,65>A,841306689079511650 64b:c]s'";L 2750763932992480612976738964894343100372667569857057816704667471637641979761595859190213443543359288493237588430216583759463627409436875398907 L;"'/Sq;";\;4b43f+:c',/erS/'/*S*'";L ``` Reversed (Morse decoder): ``` L;"'*S*/'/Sre/,'c:+f34b4;\;";qS/'";L 7098935786349047263649573856120348857323948829533453443120919585951679791467361747664076187507589657662730013434984698376792160842992393670572 L;"'s]c:b46 056115970986603148,A>56,['[q;";\;sW%i4b43f+:c',/['[,65>A,841306689079511650 64b:c]ser'/sa/S*'";L ``` This is just a trivial tweak of [Optimizer's solution](https://codegolf.stackexchange.com/a/44380) to eliminate the string eval (`~`), in response to [a meta post](http://meta.codegolf.stackexchange.com/a/4655) asserting that "[the] use of eval statements is what makes this abuse possible". Accordingly, as it's mostly not my own code, I have marked it as Community Wiki. Instead of Optimizer's trick of placing the eval operator `~` between two quoted strings, like this: ``` L;"encoder"~"reversed decoder";L ``` my version relies on the fact that, in CJam, *any* character following a single quote (`'`) is interpreted as a character literal: ``` L;"'reversed decoder;";encoder'";L ``` Relevant CJam speed-tutorial: `L` is an empty string, `"..."` is a double-quoted string, `'"` is a literal double quote, and `;` pops the most recent value off the stack. Thus, this code first pushes an empty string, pops it, pushes the string `'reversed decoder;`, pops it, executes `encoder`, pushes another double quote, pops it, and pushes an empty string (which has no effect on the output). **Update:** Saved 8 bytes by a trivial (in hindsight) optimization. With the further saving from eliminating needless backslashed, this is now just two bytes longer than Optimizer's original eval-based solution. ]
[Question] [ The goal is to take CSS rules from a regular CSS file and apply them to their respective targets in an HTML file, but by placing the rules in the `style=""` attribute (using the [`<style>` tag](http://www.w3schools.com/tags/tag_style.asp) would be too simple) and removing the `class=""` and `id=""` attributes. Rules: * Only ids `#id` and classes `.class` selectors must be supported, without more complex rules (parent selector `#a #b` or multiple classes `.a.b`, etc.) * Reducing rules is not required, for example the rules `#a{color:red} .b{color:blue}` applied to `<div id="a" class="b"></div>` can output `<div style="color:blue;color:red;"></div>` and the browser will only use the last rule (hereby red) * The paths to input files can be transmitted by command line arguments or hard-coded in the script/program * You can't call an external library, you can only include classes or functions built in the language (or from another language if needed) * [Standard “loopholes”](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) are forbidden * You program must produce the expected result but also works with other input files (to avoid hard-coded solution) * The output does not need to be saved to any file * Shortest code wins ## Inputs: ### CSS file ``` #h1 {color:Red;} #bigger {font-size:1.1em;} .code {font-family:Monospace;} .golf {background-color:LightGreen;} ``` Only ids and classes are used in order to keep it simple. ### HTML file ``` <!DOCTYPE html> <html> <head><title>Hello World!</title></head> <body> <h1 id="h1">Hello World!</h1> <ol> <li class="code">Code</li> <li id="bigger" class="golf">Golf</li> <li class="code golf">Code golf</li> </ol> </body> </html> ``` ## Expected output: ``` <!DOCTYPE html> <html> <head><title>Hello World!</title></head> <body> <h1 style="color:Red">Hello World!</h1> <ol> <li style="font-family:Monospace;">Code</li> <li style="font-size:1.1em;background-color:LightGreen;">Golf</li> <li style="font-family:Monospace;background-color:LightGreen;">Code golf</li> </ol> </body> </html> ``` [Example on jsfiddle](http://jsfiddle.net/BpaYe/). [Answer] # JavaScript - 589 (573) It's 573 when processed by a minifier. Not smaller then the Python version, but processes CSS using DOM objects instead of text strings. This should be able to process more complex CSS selectors also. But then the `id` and `class` attributes are not handled at the moment. ``` x=document x.write('<link rel="stylesheet" href="'+c+'"/>') window.onload=function(){ var s,p,n,t,i,j,r=x.styleSheets[0].cssRules,d=x.getElementById('i').contentWindow.document for(i=0;i<r.length;i++){s=r[i].selectorText p=r[i].cssText.match(/\{\s*(.*?)\s*\}/) n=d.querySelectorAll(s) for(j=0;j<n.length;j++){t=n[j].getAttribute('style')==null?'':n[j].getAttribute('style') n[j].setAttribute('style',(t+p[1]).replace(': ',':')) n[j].removeAttribute(s.charAt(0)=='#'?'id':'class') }}alert(new XMLSerializer().serializeToString(d))} x.write('<iframe src="'+h+'" id="i"></iframe>') ``` Runs in Firefox if you put the script, the files to process and this web page in the same folder: ``` <html><body> <script type="text/javascript"> var c='css2inline.css', h='css2inline-input.html' </script> <script type="text/javascript" src="a.js"></script> </body></html> ``` Replace `c` and `h` with CSS and HTML files, open this page and an alert shows the HTML. **Note** The resulting HTML is a serialization of the DOM tree. That causes the result to be not exactly formatted as requested, but it represents the same HTML. Your call to say if you find it correct or not. Expanded: ``` // Add CSS to current document. x = document x.write('<link rel="stylesheet" href="'+c+'"/>') window.onload = function(){ var s,p,n,t,i,j, r = x.styleSheets[0].cssRules, // Get the HTML to process. d = x.getElementById('i').contentWindow.document // Loop through CSS rules. for(i = 0; i < r.length; i++){ // Get CSS selector from rule. s = r[i].selectorText // Get text with CSS properties. p = r[i].cssText.match(/\{\s*(.*?)\s*\}/) // Get DOM nodes matching the CSS selector. n = d.querySelectorAll(s) // Add CSS properties to style of selected nodes. for(j = 0; j < n.length; j++){ // Preserve current value. t = n[j].getAttribute('style') == null ? '' : n[j].getAttribute('style') // Add rule properties. n[j].setAttribute('style',(t + p[1]).replace(': ',':')) // Remove id/class attribute from element. n[j].removeAttribute(s.charAt(0) == '#' ? 'id' : 'class') } } // Output serialized document. alert(new XMLSerializer().serializeToString(d)) } // Create document with input HTML. x.write('<iframe src="'+h+'" id="i"></iframe>') ``` [Answer] # Python - ~~508~~, ~~501~~, 483 The idea is to read all the rules then apply them by using xpath functions, too bad it can't select nodes with multiple classes (I didn't find own to target `class="code golf"`). ## Golfed ``` import sys,xml.etree.ElementTree as E r=E.parse(sys.argv[2]) def a(e,f):e.set('style',(e.attrib.get('style')or'')+f) for l in open(sys.argv[1]): s=l.replace("\n",'').split(' ');b=s[0];c=s[1][1:-1] if(b[:1])=='#': for e in r.findall('.//*[@id=\''+b[1:]+'\']'):a(e,c);e.attrib.pop('id') else: for e in r.findall('.//*[@class]'): d=e.attrib.get('class').split(' ') if b[1:]in d: a(e,c);e.set('class',' '.join(d[1:])) if len(d) == 1: e.attrib.pop('class') E.dump(r) ``` ## Usage `python script.py input.css input.html` ## Ungolfed code ``` import sys, xml.etree.ElementTree as ET root = ET.parse(sys.argv[2]) # append rules to style="" attribute def a(e,f): e.set('style',(e.attrib.get('style')or'') + f) # CSS file for l in open(sys.argv[1]): split = l.replace("\n", '').split(' ') selector = split[0] rules = split[1][1:-1] # #id if (b[0:1]) == '#': for e in root.findall('.//*[@id=\''+selector[1:]+'\']'): a(e,rules) # remove id e.attrib.pop('id') # .class else: for e in root.findall('.//*[@class]'): d=e.attrib.get('class').split(' ') if selector[1:] in d: a(e,rules) e.set('class', ' '.join(d[1:])) # remove class if len(d) == 1: e.attrib.pop('class') ET.dump(root) ``` [Answer] ### bash + sed ~~133~~ ~~185~~ 179 ``` sed -re 's/ass="([^"]*) ([^"]*)"/ass="\1" class="\2"/g;'"$( sed -re 's/^#/id§/;s/^\./class§/; s/(.*)§(\S*) \{(.*)\}/s@\1="\2"@style="\3"@g/' $CSS )"';s/yle="(.*)" style="/yle="\1/g' $HTML ``` ``` sed -re 's/class="([^"]*) ([^"]*)"/class="\1" class="\2"/g; '"$(sed -re 's/^#/id /;s/^\./class /; s/(\S*) (\S*) \{(.*)\}/s@\1="\2"@style="\3"@g/' $CSS )"';s/style="(.*)" style="/style="\1/g' $HTML ``` In this (specific) case, this will render: ``` <!DOCTYPE html> <html> <head><title>Hello World!</title></head> <body> <h1 style="color:Red;">Hello World!</h1> <ol> <li style="font-family:Monospace;">Code</li> <li style="font-size:1.1em;background-color:LightGreen;">Golf</li> <li style="font-family:Monospace;background-color:LightGreen;">Code golf</li> </ol> </body> </html> ``` [Answer] # Lua - ~~340~~ 335 ``` f='(%w+)'a={}b={}for l in io.lines(arg[2])do i=l:sub(1,1)t=i=='#'and a or b k,v=l:match(f..' {(.-)}')t[k]=v end for l in io.lines(arg[1])do c=''g='class="(.-)"'h='style="'l=l:gsub('id='..f,function(v)l:gsub(g,function(e)c=e:gsub(f,b)end)return h..a[v]..c..'"'end)l=l:gsub(g,function(e)return #c<1 and h..e:gsub(f,b)..'"'end)print(l)end ``` **Usage:** execute from the command line `lua script.lua input.html input.css` ]
[Question] [ Inspired by [ecofont](http://www.ecofont.com/). ![](https://i.stack.imgur.com/llpql.jpg "Thanks to RobIII for suggesting adding this image. Ecofont converts solid figure into figure with holes") Given a string containing `#` and , output it more eco-friendly by cutting out circles, while keeping it "recognizable" (defined later, in the Circles section). `#` represents black, and represents white. This program is supposed to do something like this: Input: ``` #################### #################### #################### #################### #################### #################### #################### #################### #################### #################### #################### ``` Sample output (rather bad score): ``` #################### #### ############### ## ############# ## #### ######## # # ###### ## ## ###### ## # ##### #### #### ###### ######### ###### ########### ######## #################### ``` ### Circles These are the only valid circles (`#`s indicating characters that would be cut out): ``` # ### ##### ### # # ##### ##### ####### ##### ##### # ``` Every circle cut out must be of the same radius. By "recognizable", I mean that there must be a gap of at least one pixel / point between each circle, and each circle and the edge of the shape (outside of the `#` region): Again, `#` indicates characters that would be cut out, not characters that would be left behind ``` # # ##### ##### ##### ##### ############## ##### ##### ##### ##### # # ``` Is invalid, but: ``` # ##### ##### ####### # ##### ##### ##### ##### # ####### ##### ##### # ``` Is valid. Note that corners are considered touching. That is, in ``` # # ``` the two "pixels" are considered touching, thus circles cannot touch in that way. Also, just to restate it, if we have a shape like: ``` ######## ######## ######## ######## ######## ######## ######## ######## ``` Cutting circles like this is invalid (they both touch the edge of the figure): ``` #### # ### #### # ## ## ## # #### ### # #### ## ##### ``` ### Scoring Your score is the total number of `#`s left from the specified inputs. Lowest score wins. Input #1: ``` ################################################## ################################################## ################################################## ################################################## ################################################## ################################################## ################################################## ################################################## ################################################## ################################################## ################################################## ################################################# ################################################# ################################################# ################################################# ################################################ ################################################ ################################################ ############################################### ############################################### ############################################## ############################################## ############################################## ############################################# ############################################ ############################################ ########################################### ########################################### ########################################## ######################################### ######################################### ######################################## ####################################### ###################################### ###################################### ##################################### #################################### ################################### ################################## ################################ ############################### ############################## ############################ ########################### ######################### ####################### ###################### ################### ################# ############## ``` Input #2: ``` ##################### ####################### ####################### ######################### ######################### ########################### ############################ ############################# ############################## ############################### ################################ ################################# ################################## #################################### ################# ################ ################# ################# ################# ################ ################# ################# ################# ################ ################# ################# ################# ################# ################# ################# ################## ################# ################# ################# ################# ################# ################# ################# ################# ################# ################# ################# ################# ################# ################## ################# ################# ################## ################## ################# ################# ################# ################## ################# ################# ################# ################## ################# ################# ################## ################## ################## ################# ################# ############################################################### ################################################################ ################################################################# ################################################################### ################################################################### ##################################################################### ###################################################################### ###################################################################### ######################################################################## ######################################################################## ########################################################################## ################## ################### ################### ################## ################## ################### ################### ################## ################## ################### ################### ################## ################### ################### ################### ################## ################### ################### ################### ################### ################### ################### ################### ################## ################### ################### #################### ################### ################### ################### #################### ################### ################### ################### #################### ################### ################### ################### #################### ################### ################### ################### #################### ################### #################### ################### #################### ################### ################### ################### ``` Input #3: ``` ############## ##################### ######################### ############################# ################################# ################################### ##################################### #################################### ################################## ################################ ############################# ########################## ####################### ###################### ########################## ############################# ############################### ################################## #################################### ##################################### ################################### ################################# ############################# ########################## ##################### ############### ``` Note: Tailoring specifically to the samples is not allowed. [Answer] # PHP \*\*WARNING : spaghetti english and spaghetti code ahead \*\* Okay, not sure I understood everything but here's my try. So what is done ? * Convert text input to an image. " " = white pixel, "#" = red pixel. Example : ![enter image description here](https://i.stack.imgur.com/PW4IG.png) * Draw holes inside image, cheking to not collide on a previous one. Example : ![enter image description here](https://i.stack.imgur.com/Gw7CJ.png) * Convert back image to text (not sure about this red dot in the bottom right corner but, he, yolo) ``` <?php /* Check collision between white pixels in 2 images. */ function checkCollision ($img1, $img2, $width, $height, $circle_x, $circle_y, $circle_size) { $start_x = $circle_x - round($circle_size / 2); if ($start_x < 0) return false; $stop_x = $circle_x + round($circle_size / 2); if ($stop_x > ($width - 1)) return false; $start_y = $circle_y - round($circle_size / 2); if ($start_y < 0) return false; $stop_y = $circle_y + round($circle_size / 2); if ($stop_y > ($height - 1)) return false; $color_white = array("red" => 255, "green" => 255, "blue" => 255, "alpha" => 0 ); for ($y = $start_y; $y < $stop_y - 1; $y++) for ($x = $start_x; $x < $stop_x - 1; $x++) { $pixel_img1 = imagecolorsforindex($img1, imagecolorat($img1, $x, $y)); $pixel_img2 = imagecolorsforindex($img2, imagecolorat($img2, $x, $y)); if ($pixel_img1 == $pixel_img2 && $pixel_img1 == $color_white) return false; } return true; } $input = file_get_contents("input.txt"); $lines = explode("\n", $input); $image_width = strlen($lines[0]); $image_height = count($lines); $circle_size = 5; /* Creating an image matching dimensions and some colors. */ $img = imagecreatetruecolor($image_width, $image_height); $color_red = imagecolorallocate($img, 255, 0, 0); $color_white = imagecolorallocate($img, 255, 255, 255); /* Filling the freshly created image. '#' is replaced by a red pixel, ' ' by a white one. */ for ($y = 0; $y < $image_height; $y++) { $line = $lines[$y]; for ($x = 0; $x < strlen($line); $x++) if ($line[$x] == '#') imagesetpixel($img, $x, $y, $color_red); else imagesetpixel($img, $x, $y, $color_white); } /*Try to draw a circle on any red pixel then check if it not collides with any other white space before commiting */ for ($y = 0; $y < $image_height; $y++) for ($x = 0; $x < $image_width; $x++) { $img_tmp = imagecreatetruecolor($image_width, $image_height); imagecopy($img_tmp, $img, 0, 0, 0, 0, $image_width, $image_height); imagefilledellipse($img_tmp, $x, $y, ($circle_size + 2), ($circle_size + 2), $color_white); if (checkCollision ($img, $img_tmp, $image_width, $image_height, $x, $y, ($circle_size + 2))) imagefilledellipse($img, $x, $y, $circle_size, $circle_size, $color_white); } /* Convert image to text */ $output = ""; $color_white = array("red" => 255, "green" => 255, "blue" => 255, "alpha" => 0 ); for ($y = 0; $y < $image_height; $y++) { for ($x = 0; $x < $image_width; $x++) { $pixel_img = imagecolorsforindex($img, imagecolorat($img, $x, $y)); if ($pixel_img == $color_white) $output = $output . " "; else $output = $output . "#"; } $output = $output . "\n"; } file_put_contents("output.txt", $output) ?> ``` Spent a lot of time because I didn't know I could not just copy a GD ressource doing $a = $b.. (it creates a ref) # Example : ## Input : ``` ############## ##################### ######################### ############################# ################################# ################################### ##################################### #################################### ################################## ################################ ############################# ########################## ####################### ###################### ########################## ############################# ############################### ################################## #################################### ##################################### ################################### ################################# ############################# ########################## ##################### ############### ``` ## Output : ``` ############## ##################### ########## ###### ####### ########### #### ######## ######## ### ## ######### ######## ### #### ########### ######## ### ###### ############# ##### ### ######################## ##### ### ###################### ##### ######## ############# ###### ######## ######### ####### ######## ##### ############# ### ### ############ ### ### ###### #### ########## ##### #### ############## #### #### ###### ########## #### ########### ############# #### ########### #### ########## ########## ###### #### ########## ######## ###### #### ######## ###### ########### ######## ##### ############# ####### #### ##################### ##################### ############### ``` I hope this hit the target. It's obvious that we can do it better and more properly but maybe it would help the others to understand what this code challenge is about. # Score ## Input 1 : > > Before : 2030 "#" > > After : 1575 "#" > > 455 removed > > > ## Input 2 : > > Before : 2955 "#" > > After : 2370 "#" > > 585 removed > > > ## Input 3 : > > Before : 748 "#" > > After : 618 "#" > > 130 removed > > > ## Total : > > "#" input : 5733 > > "#" left : 4563 (~80%) > > "#" removed : 1170 (~20%) > > > # FINAL SCORE : 4563 ;\_; [Answer] # Python 2.7 Expects the input file to be passed via the command line, e.g. ``` python thisscript.py input1.txt ``` I implemented ~~5~~ 2 options to run: * Using the small shape * Using the large shape * ~~Alternating between the small and large shape~~ * ~~Alternating between the small and large shape randomly~~ * ~~Completely random~~ I just scan the input starting from the top left and a shape is cut away as soon as possible. The shapes themselves can be modified quite easily. ``` import sys,random,copy def char2val(c): if (c=='#'): return 1 # this is the shape itself elif (c=='o'): return 2 # this is the boundary, for collision detection else: return 0 def val2char(v): if (v==0): return ' ' else: return '#' # convert string to array for processing def str2arr(s): arr = [] for line in s.split('\n'): arr.append( [ char2val(c) for c in line ] ) return arr # convert array to string for output purposes def arr2str(arr): s="" for i in range(len(arr)): for j in range(len(arr[i])): s+=val2char(arr[i][j]) s+="\n" return s # check if a cut we want to make is a valid one def validate_cut(arr,shape,r,c): valid = True for i in range(len(shape)): for j in range(len(shape[i])): if shape[i][j] == 1: #hard cut here valid = ( 0 < i+r < len(arr)-1 ) and ( 0 < j+c < len(arr[i+r])-1) # bounds check valid = valid and ( arr[i+r][j+c]==1) # site must be cut-able elif shape[i][j]==2: #edge of shape valid = ( 0 <= i+r <= len(arr)-1 ) and ( 0 <= j+c <= len(arr[i+r])-1) # bounds check, edge allowed to lie on border valid = valid and arr[i+r][j+c]!=0 # edge cannot go into cut/empty space if not valid: return False return valid def cut(arr,shape,r,c): # cut shape from arr, @ position r,c for i in range(len(shape)): for j in range(len(shape[i])): if (shape[i][j] > 0): arr[i+r][j+c] -= shape[i][j] def run(inarr,opt=0): arr = copy.deepcopy(inarr) for r in range(len(arr)): for c in range(len(arr[r])): if (opt==0): shape = c1arr elif (opt==1): shape = c2arr else: raise Exception("run option not supported!") if validate_cut(arr,shape,r,c): cut(arr,shape,r,c) return arr # global variables for the shapes,... # \# are the shapes themselves # o is the boundary used for collision detection c1 = \ "\ ooo \n\ oo#oo \n\ oo###oo\n\ o#####o\n\ oo###oo\n\ oo#oo \n\ ooo \ " c2 = \ "\ ooo \n\ ooo#ooo \n\ o#####o \n\ oo#####oo\n\ o#######o\n\ oo#####oo\n\ o#####o \n\ ooo#ooo \n\ ooo \ " c1arr = str2arr(c1) c2arr = str2arr(c2) def main(): #input processing random.seed('117') f = file(sys.argv[1],"r") inp = f.read().rstrip('\n') #input string inarr = str2arr(inp) #convert string to array #run the algorithm arr0 = run(inarr,opt=0) arr1 = run(inarr,opt=1) minarr = arr0 if arr2str(arr0).count('#') < arr2str(arr1).count('#') else arr1 #output print arr2str(minarr) print " %d # of %d remaining " % (arr2str(minarr).count('#'),inp.count('#')) main() ``` The results are ## Input1 ``` 1102 # of 2030 remaining ``` ## Input2 ``` 1766 # of 2955 remaining ``` ## Input3 ``` 514 # of 748 remaining ``` Full output for input3: ``` ############## ##### ##### ######### ###### ### #### ##### ### ### # ## ###### #### ### ### ## ####### #### ### ## ## #### ######### ### ## ###### #### ## ########### ## ## ## ### ## ############ ## ### ### ## ######## #### ### ### #### ###### ##### ## ## ## ####### #### ####### ## ## ######## ### ## ### #### ## ## ## ## #### # ## ## ## ## ###### ## ##### ### ######## ### ## #### ### ## ###### #### #### ## ## ## ######### ## ##### ## ## ## ######## ### ##### ##### ## ######## ### ####### ## #### ## ###### ########### ## ####### ###### ########### ####### ##### ########## ############# ######### ########### ############### ``` ## Total score: 3382 ]
[Question] [ **This question already has answers here**: [Transform number into 7-segment display pattern [closed]](/questions/19196/transform-number-into-7-segment-display-pattern) (17 answers) Closed 10 years ago. Write a program that prints the current time in a digital watch. Rules: * The program must use the local timezone. * Time is expressed between 00:00 to 23:59 (with only hours and minutes). * The program must follow the output rules. * The smallest program wins. Output (see example): * Each digit is represented by 4×3 matrix of the characters `␣` (space), `|` (pipe) and `_` (underscore). * There are two spaces between two digits. * The `:` (column) is represented with a 1x3 matrix [`␣`,`.`,`.`] and is separated with the digits on both sides by 2 spaces. * A newline at the end of the output is tolerated. List of digits: ``` __ __ __ __ __ __ __ __ | | | __| __| |__| |__ |__ | |__| |__| |__| | |__ __| | __| |__| | |__| __| ``` Example output: (for 21:08) ``` __ __ __ __| | . | | |__| |__ | . |__| |__| ``` Go! EDIT: corrected the spaces for `:` and `1` [Answer] ## PHP, 229 174 ``` <?php $s=" |.. w\$km<]_d\x7F}";for($r=3;$r--;print' ')foreach(str_split(date('H:i'))as$c)echo$c>'9'?$s[$r+2]:$s[($d=ord($s[$c+5])>>$r*3)/2&1].($d&1?@__:' ').$s[$d/4&1],' '; ``` `$s` is a lookup table that encodes several things. The first two characters are the vertical segments, when off or on. The next three characters are the characters of the colon on each of the three rows. The character codes of the remaining characters encode in binary the state of the segments of each digit. --- Old version, 229 chars: ``` <?php foreach([strtr(decbin(735),[' ',' __ ']).' ','| | | __| __||__||__ |__ ||__||__|.','|__| ||__ __| | __||__| ||__| __|.']as$r){foreach(str_split(date('H:i'))as$c)echo substr($r,ord($c)-48<<2,4).' ';echo' ';} ``` Useful fact: the ASCII code of `:` is one greater than the ASCII code of `9`, so `0123456789:` are contiguous. [Answer] # C# (407 418) ``` namespace System{using z=String;using w=Console;class P{static void Main(){var t=DateTime.Now.ToString("HH:mm");int k=0;z b="17",d=b+23,e=b+3459,f="56",g=e+2680;Action<z,z,z>q=(l,m,r)=>{foreach(var c in t){if(c==':')w.Write(k++>0?".":" ");else{h(c,l);h(c,m,"_");h(c,m,"_");h(c,r);}w.Write(" ");}w.Write("\n");};q(g,"14",g);q(d,b+0,f);q(e,b+4,"2");}static void h(char x,z m,z y="|"){w.Write(m.Contains(""+x)?" ":y);}}} ``` Edit: digits are now 4x3 instead of 3x3. this adds 11 characters. [Answer] # Perl - 289 ~~291 302~~ ``` use POSIX;$_=$p=(strftime"%H:%02M\n",localtime)=~s;.;$& ;rg;s;\S;$&eq':'?'a':$&-1&&$&-4?'abba':'aaaa';eg;$_.=$p;s;\d|:;(caacaaacabbcabbccbbccbbacbbaaaaccbbccbbcd=~/.{0,4}/g)[-48+ord$&];eg;$_.=$p;s;\d|:;(cbbcaaaccbbaabbcaaacabbccbbcaaaccbbcabbcd=~/.{0,4}/g)[-48+ord$&];eg;y;a-d; _|.;;print ``` * `strftime"%H:%02M\n",localtime` - obtain local time in H:MM format * `s;.;$& ;rg` - intersperse with double spaces the time is saved in `$p` for later usage * `s;\S;$&eq':'?'a':$&==1||$&==4?'aaaa':'abba';eg` - replace `:` with `a`, 1 and 4 with `aaaa` and other digits with `abba` (later `a` will turn into , `b` - into `_`, `c` - `|`, `d` - `.`) `$_.=$p` append `$p` (spaced time) * `s;\d|:;(caacaaacabbcabbccbbccbbacbbaaaaccbbccbbcd=~/.{0,4}/g)[-48+ord$&];eg` + `/.{0,4}/g` - turn the preceding string into an array of 4-char strings + `-48+ord$&` - turn char code into an index, `0` becomes 0, `1` becomes 1, `:` becomes 10 * then append `$p` again and run a similar substitution * `y;a-d; _|.;` - replace `abcd` with `_|.` [Answer] # JavaScript, 192 **Disclaimer:** This one is a JavaScript port of @Boann's answer. ``` for(o='',D=(o+(new Date)).substr(16,5),s=' |.. w$km<]_d\x7F}',r=3;r--;o+='\n')for(i=0;c=D[i++];o+=c>'9'?s[r+2]:(s[(d=(s[+c+5]).charCodeAt(0)>>r*3)/2&1]+(d&1?'__':' ')+s[d/4&1])+' ');alert(o) ``` # JavaScript (ES6), 256 ``` for(t=[v='',v,v],d=(v+(new Date)).substr(16,5),i=0;c=d[i++];)for(j=3;j--;t[j]+='0 00 00000 +|22 1 1|1|__ |__ 2|1|1.+|12 |__ 1 2 1|1 2|1 1.'.replace(/\d/g,e=>!+e?' __ ':e^2?'__|':' |').split('+')[j].substr(+c==c?c*4:40,4)+' ');alert(t.join('\n')) ``` Ungolfed: ``` for( // Create an array containing 3 empty strings. t=[v='',v,v], // Convert current date to a string and extract the time part. d=(v+(new Date)).substr(16,5), i=0; // Read current time digit. // Break the loop when the end of string is reached. c=d[i++]; ) for( // Iterate 3 times in order to fill each line. j=3; j--; // Append current character. t[j]+='0 00 00000 +|22 1 1|1|__ |__ 2|1|1.+|12 |__ 1 2 1|1 2|1 1.'.replace( // Unpack the above string. // Convert each digit into a substring as follow: /\d/g,e=> // 0: Convert current digit into a number and negate it. // Must be done because !'0' equals false. !+e?' __ ' // 1: Convert current digit into a number and check if different than 2. // Since we have handled the 0, we just read a 1. :e^2?'__|' // 2: Last case. :' |' // Split the unpacked string in 3 lines. ).split('+')[j] // Get the 4 characters representing the current digit. .substr( // Convert current digit into a number and compare it with itseft. // The comparison fails if the digit convertion results in NaN (:). +c==c?c*4:40,4 // Add 2 spaces between each digits )+' ' ); // Join lines. // Output ASCII time. console.log(t.join('\n')) ``` [Answer] ## Javascript (444, 436, 417, 402) ``` s="\n";q=[];[0x6606,0x66666,0xfee89,0xff877,0x8e78f,0xef8fe].forEach(function(n){for(i=0;i<20;++i)q.push(1&(n>>i))});function f(j){s+=q[j]?'|':' ';s+=q[j+1]?'_':' ';s+=q[j+2]?'_':' ';s+=q[j+3]?'|':' '}function g(n,l){f(4*Math.floor(n/10)+40*l);s+=" ";f(4*(n%10)+40*l)}d=new Date;h=d.getHours();m=d.getMinutes();p=" . ";g(h,0);s+=" ";g(m,0);s+="\n";g(h,1);s+=p;g(m,1);s+="\n";g(h,2);s+=p;g(m,2);s ``` **How it works :** Each line of a number is encoded with 4 bits, `0` is a space, `1` is `_` (for 2nd and 3rd character) or `|` (for 1st and last character). For example, `5` is `0110`, `0001`, `0111`. The goal is to create an array of 120 booleans (10 numbers \* 3 lines \* 4 bits) containing all the numbers. [Answer] **Ruby (239 ~~335~~)** ``` 0.upto(2){|h|s=(0..3).map{|i|'041655023022615032031055011012'.gsub(/./){[' __ ','|__|',' __|','|__ ','| |',' |',' '*4][$&.to_i]}.scan(/.{12}/)[Time.new.strftime('%H%M').split('')[i].to_i][h*4..h*4+3]}*' ';s[9]=' '+' ..'[h]+' ';puts s} ``` Edit: Shorted with @manatwork syntax ~~The idea is pretty straightforward: make the array with the numbers and substrings (with []) to print each line of the number. I know is far from perfect, I'm new in Ruby and there is probably a way to make a loop in the printing that takes less chars.~~ [Answer] ### Delphi XE3 (504 495) Waay to much, but still fun to do :) Thanks Manatwork for the tip on multidimensional arrays. ``` const asc:array[0..9,0..2]of string=((' __ ','| |','|__|'),(' ',' |',' |'),(' __ ',' __|','|__ '),(' __ ',' __|',' __|'),(' ','|__|',' |'),(' __ ','|__ ',' __|'),(' __ ','|__ ','|__|'),(' __ ',' |',' |'),(' __ ','|__|','|__|'),(' __ ','|__|',' __|'));var s,l:string;x,i:int16;begin s:=FormatDateTime('hhnn',now);for I:=0to 2do begin l:='';for x:=1to length(s)do begin l:=l+asc[StrToInt(s[x])][i];if x=2 then if i>0then l:=l+' . 'else l:=l+' 'end;writeln(l);end;readln;end. ``` ### With indent ``` const asc: array[0..9,0..2] of string = ( (' __ ','| |','|__|'), (' ',' |',' |'), (' __ ',' __|','|__ '), (' __ ',' __|',' __|'), (' ','|__|',' |'), (' __ ','|__ ',' __|'), (' __ ','|__ ','|__|'), (' __ ',' |',' |'), (' __ ','|__|','|__|'), (' __ ','|__|',' __|')); var s,l:string; x,i:int16; begin s:=FormatDateTime('hhnn',now); for I := 0 to 2 do begin l:=''; for x := 1 to length(s) do begin l := l + asc[StrToInt(s[x])][i]; if x=2 then if i>0then l:=l+' . ' else l:=l+' ' end; writeln(l); end; readln end. ``` ]
[Question] [ ## Intro I guess most people are familiar with the game [Lights Off](http://en.wikipedia.org/wiki/Lights_Out_%28game%29), but in case someone isn't, here is a short description: > > You start with an NxN grid where each cell in the grid is a light. For this example N=5. There are 2 ways the game can start: either all of the lights are on, or some lights are off. The goal is to turn off all of the lights. If you toggle a light, the lights left, right, above and below it will toggle with it. > > > ### All Lights on ``` 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 ``` ### Toggled cells ``` Toggled(0,0) | Toggled(1,2)| Toggled(2,4) X X O O O | O O X O O | O O O O O X O O O O | O X X X O | O O O O X O O O O O | O O X O O | O O O X X O O O O O | O O O O O | O O O O X O O O O O | O O O O O | O O O O O ``` ## Task Make an interactive game of Lights Off with as little code as possible. **Requirements** There is a setup phase and a play phase. The setup phase takes user input to determine the grid size (minimum size of 5) and whether the grid starts with all of the lights on. If the grid should not start with all of the lights on, lights must be selected randomly to start off: at least 1 and at most 20% of the lights. In the play phase, the grid is displayed to the user and moves are taken as input. The application could use a windowed GUI with lights toggled by clicking, or a text UI which takes typed input of the coordinates of the cell to toggle. When the user reaches a solved state (all lights off), the application must notify them that they have solved the puzzle, and show how many moves it took. The use of external resources is not allowed. If there is anything unclear or missing please let me know :) ### Related questions * [Lights Out - Find the solution](https://codegolf.stackexchange.com/questions/3429/lights-out-find-the-solution) asks for a computer-generated solution given the input * [Lights Off!](https://codegolf.stackexchange.com/questions/1899/code-golf-lights-off) is more similar to this one, but non-interactive [Answer] ## APL (101) ``` 00{⎕←'XO'[1+⍵]⋄1∨.=,⍵:(⍺+1)∇⍵≠(⍳⍴⍵)∊⎕∘+¨Z,⌽¨Z←0∘.,¯1 0 1⋄'SOLVED',⍺}⎕{⍺:⍵ ⍵⍴1⋄~(⍵ ⍵⍴⍳V)∊V?⍨⌊.2×V←⍵*2}⎕ ``` The first input is the size, the second input is the start value (0=some off, 1=on). Coordinates are 1-based. ``` 0{⎕←'XO'[1+⍵]⋄1∨.=,⍵:(⍺+1)∇⍵≠(⍳⍴⍵)∊⎕∘+¨Z,⌽¨Z←0∘.,¯1 0 1⋄'SOLVED',⍺}⎕{⍺:⍵ ⍵⍴1⋄~(⍵ ⍵⍴⍳V)∊V?⍨⌊.2×V←⍵*2}⎕ ⎕: 5 ⎕: 1 OOOOO OOOOO OOOOO OOOOO OOOOO ⎕: 2 2 OXOOO XXXOO OXOOO OOOOO OOOOO ⎕: ``` [Answer] ## C++, 564 bytes ``` #include <iostream> #include <algorithm> #include <ctime> #include <cstdlib> #include <vector> using namespace std;int main(){int n,p,s=0,y,i=0,b;cin>>n>>b;if(n<5)n=5;vector<int>m(n*n,1);srand(time(0));if(b)for(int&c:m)c=rand()<RAND_MAX/6;for(;i<n*n;i++)cout<<m[i]<<(-~i%n?"":"\n");while(find(m.begin(),m.end(),1)!=m.end()){cin>>p>>y;p+=y*n;if(p<0||p>=n*n)continue;m[p]=!m[p];if(p%n)m[p-1]=!m[p-1];if(p%n+1<n)m[p+1]=!m[p+1];if(p>=n)m[p-n]=!m[p-n];if(p+n<n*n)m[p+n]=!m[p+n];for(i=0;i<n*n;i++)cout<<m[i]<<(-~i%n?"":"\n");s++;}cout<<"Solved in "<<s<<" steps."<<endl;} ``` In setup phase, the user should input the grid size first. Then if the grid should starts with all of the lights on, the user should input `0`; otherwise `1`. In play phase, the user should input the 0-based coordinates of the cell to toggle until all lights off. Original code: ``` #include <iostream> #include <algorithm> #include <ctime> #include <cstdlib> #include <vector> using namespace std; int main() { int n, p, s = 0, y, i = 0, b; cin >> n >> b; if(n < 5) n = 5; vector<int> m(n * n, 1); srand(time(0)); if (b) for (int& c : m) c = rand() < RAND_MAX / 6; for (; i < n * n; i++) cout << m[i] << (-~i % n ? "" : "\n"); while (find(m.begin(), m.end(), 1) != m.end()) { cin >> p >> y; p += y * n; if (p < 0 || p >= n * n) continue; m[p] = !m[p]; if (p % n) m[p - 1] = !m[p - 1]; if (p % n + 1 < n) m[p + 1] = !m[p + 1]; if (p >= n) m[p - n] = !m[p - n]; if (p + n < n * n) m[p + n] = !m[p + n]; for (i = 0; i < n * n; i++) cout << m[i] << (-~i % n ? "" : "\n"); s++; } cout << "Solved in " << s << " steps." << endl; } ``` [Answer] # C - 365 characters ``` #define a for(y=0;y<w*w;y++) *k,i,w,x,y,c=0;main(){scanf("%i %i",&w,&i);k=malloc(4*w*w+8*w)+4*w;i&=1;srand(k);a k[y]=i||ra nd()<6553;i^=1;for(;;){x=0;a{putchar(k[y]?79:88);x|=k[y]!=i;!((y+1)%w)&&putchar(10);}if(!x&&c )return printf("won in %i",c);putchar(62);scanf("%i %i",&x,&y);k[x*w-w+y]^=x>0;k[x*w+y-1]^=y> 0;k[x*w+w+y]^=x<w-1;k[x*w+y+1]^=y<w-1;k[x*w+y]^=1;c++;}} ``` In setup phase, it asks the user for two integers: table size and starting state (`0` for off and `1` for on), respectively. After that, before every move, it will print the grid, then prompt (`>`) the user for 0-based xy coordinates of the point. ]
[Question] [ In this [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") challenge, you will be making a [python](/questions/tagged/python "show questions tagged 'python'") 3 bot to play the card game judgement! [Sandbox](https://codegolf.meta.stackexchange.com/a/22303/82007) # Rules Judgement is a hand based game similar to games like rummy. In each round, 7 cards are dealt to each player, a trump suit is chosen (trump suits are chosen sequentially from the list Spades/Hearts/Diamonds/Clubs/No Trump), and based on these cards, the trump suit, and the play order, each player must make a guess as to how many hands they will win. The first player to play in a particular hand can play any card they want. From then on, any subsequent player must play a card of the same suit as the first player if they have it, otherwise, they can play any card. Once every player has played a card, the winner of the hand is determined as follows: * If a trump card has been played, the highest trump card wins * Otherwise, the highest card in the suit played by the first player wins (As in most card games, the ordering is 2,3,4,5,6,7,8,9,10,J,Q,K,A) The winner of a given hand starts the next hand. Once everyone's cards are depleted, each player counts the number of hands they have won. If it is equal to their guess, they earn 10 + the number of guessed hands. Otherwise, they earn nothing. The winner of the game is the player with the highest scores after several rounds. # Challenge I've built the game controller [here](https://colab.research.google.com/drive/1CFmWK9j6hTH1LvOiMNBjbPD6PuoiMS2-#scrollTo=mqBDWEWWpd6_). Everything in this section is present in the link, but I'll include it here for completeness. ### A submission must include 5 parts: --- ``` "name" ``` A name for the bot. --- ``` def make_bet(self, turn_order, trump): ... return hands_to_make ``` This function takes in `turn_order`, which is a list of the names of all bots in order of when they will play, and `trump`, which is a string representing the trump suit for the round. It must return `hands_to_make`, which is the number of hands the bot expects to win this round. `self.hand`will be automatically updated to contain your current hand. --- ``` play_card(self, current_board): ... return card_played ``` This function takes in the list of cards played so far this hand in the form `("bot_name", Card)`, and returns `card_played`, which is the card from your hand to play. --- ``` update_round(self, current_scores, rounds_left): ... return None ``` This function gets called right before every round (including at the very beginning for initializing you bot). It takes `current_score` which is a dictionary of `bot_name: current_score`, and `rounds_left`, which is the number of rounds left to be played. --- ``` update_play(self, final_board, winner): ... return None ``` This function gets called right after each hand. `final_board` is the list of cards played that hand in the form `("bot_name", Card)`, and `winner` is a string indicating which bot won the hand. --- The classes have the following specs **Card**: * self.suit accesses the suit (S,H,D, or C) * self.rank accesses the rank (int from 2 -> 14) * self.get\_rank() accesses the rank in str form (2-10,J,Q,K,A) **Bot**: * self.hand accesses the hand (List[Card]) * self.name accesses the name of the bot. Alternatively, str(self) works as well. * self.all\_bets accesses a dictionary of bets placed by all bots. * You can store other information you want to store by create self. class variables. As a basic example, consider the following bot: # Basic Bot ``` def basic_make_bet(self, turn_order, trump): return len(self.hand) def basic_play_card(self, current_board): if current_board: for card in self.hand: if card.suit == current_board[0].suit: return card return self.hand[0] def basic_update_round(self, current_scores, rounds_left): pass def basic_update_play(self, final_board, winner): pass basic_bot = ("basic", basic_make_bet, basic_play_card, basic_update_round, basic_update_play) ``` The Colab link above contains an easy to use template for submissions, so I recommend using that! I will also try to update the Colab link with new bots as soon as they are posted. # Requirements * You can only use libraries available in Google Colab. These are the libraries present in the Anaconda distribution of Python 3. * self.hand, the variable to access to see one's hand, must be treated as read only. Modifying the variable will mess up the game, so please avoid this. * Bots must run in a reasonable amount of time. I'm not going to provide any strict bounds but I'll remove any serious offenders. * The competition will be run June 6th, and the winner will receive a bounty + a check mark. * To judge the bots, I'll pick random groupings of up to 7 bots and play the game thousands of times, and evaluate the average score of the bots per game. # Current Averages Each bot has played a total of 100 rounds. This table should be updated semi-regularly. (PlanBot is currently too slow to run 10000 rounds) | Bot | Average | | --- | --- | | PlanBot | 6.71 | | Conservative | 6.30 | | BasicCardStrat | 4.77 | | Half | 4.28 | | Random | 4.15 | | sans. | 3.19 | | Basic | 0.00 | [Answer] ## PlanBot Plans one step ahead and then simulates a random game. Tries to sabotage its opponents once it goes bust. ``` import random def valid_plays(hand, suit): if suit is None: return list(range(len(hand))) follows_suit = [i for i, card in enumerate(hand) if card.suit == suit] if follows_suit: return follows_suit return list(range(len(hand))) def pick_random(hand, suit): if suit is None: return random.randrange(len(hand)) follows_suit = [i for i, card in enumerate(hand) if card.suit == suit] if follows_suit: return random.choice(follows_suit) return random.randrange(len(hand)) def simulate_random_game(hands, trump, starting_player, current_trick): tricks_won = [0] * len(hands) current_trick = list(current_trick) current_suit = current_trick[0].suit if current_trick else None while hands[starting_player]: i = 0 while len(current_trick) < len(hands): player = (starting_player + i) % len(hands) hand = hands[player] card_index = pick_random(hand, current_suit) card = hand[card_index] current_suit = current_suit or card.suit hand[card_index] = hand[-1] hand.pop() current_trick.append(card) i += 1 winner_offset = max(enumerate(current_trick), key=lambda t: (t[1].suit == trump, t[1].suit == current_trick[0].suit, t[1].rank))[0] current_suit = None starting_player = (starting_player + winner_offset) % len(hands) tricks_won[starting_player] += 1 current_trick.clear() return tricks_won def dirichlet_score(counts): sampled_counts = [random.gammavariate(n, 1) for n in counts] return max(sum(i * n for i, n in enumerate(counts_prime)) / sum(counts_prime) for counts_prime in (counts, sampled_counts)) INITIAL_DECK = Deck().cards def as_tuple(card): return (card.suit, card.rank) def deal(out, initial_dead_cards, hand_sizes): num_attempts = 4 order = sorted(range(len(hand_sizes)), key=lambda i: len(out[i]), reverse=True) for attempt in range(num_attempts): result = [[] for _ in hand_sizes] failed = False deck = INITIAL_DECK dead_cards = set(initial_dead_cards) for i in order: o = out[i] n = hand_sizes[i] if not n: result[i] = [] continue deck = [card for card in deck if as_tuple(card) not in dead_cards] if o and attempt != (num_attempts - 1): possible_cards = [card for card in deck if card.suit not in o] else: possible_cards = deck if len(possible_cards) < n: failed = True break hand = random.sample(possible_cards, n) result[i] = hand dead_cards |= {as_tuple(card) for card in hand} if failed: continue return result def plan_make_bet(self, turn_order, trump): scores = [0 for _ in range(8)] self.tricks_won = {bot.name: 0 for bot in turn_order} self.turn_order = [bot.name for bot in turn_order] self.my_index = next(i for i, bot in enumerate(turn_order) if bot == self) self.hand_sizes = {bot.name: 7 for bot in turn_order} self.trump = trump hand_sizes = [7 * (i != self.my_index) for i, _ in enumerate(turn_order)] self.dead_cards = {as_tuple(card) for card in self.hand} self.out = {bot.name: set() for bot in turn_order} for _ in range(1500): hands = deal([[] for _ in turn_order], self.dead_cards, hand_sizes) hands[self.my_index] = list(self.hand) tricks_won = simulate_random_game(hands, trump, 0, [])[self.my_index] scores[tricks_won] += 1 bet = max(enumerate(scores), key=lambda t: (10 + t[0]) * t[1])[0] self.bet = bet return self.bet def plan_play_card(self, current_trick): hand_sizes = dict(self.hand_sizes) for bot, card in current_trick: self.dead_cards.add(as_tuple(card)) hand_sizes[bot] -= 1 hand_sizes[self.name] = 0 current_suit = current_trick[0][1].suit if current_trick else None for bot, card in current_trick[1:]: if card.suit != current_suit: self.out[bot].add(current_suit) out = [self.out[bot] for bot in self.turn_order] plays = list(valid_plays(self.hand, current_suit)) bust = ((self.tricks_won[self.name] + len(self.hand)) < self.bet) or (self.tricks_won[self.name] > self.bet) if len(plays) == 1: return self.hand[plays[0]] if bust: a = 1. / (len(self.turn_order) - 1) outcomes = [[a] * (len(self.turn_order) - 1) for _ in plays] else: outcomes = [[1, 1] for _ in plays] hand_sizes = [hand_sizes[bot] for bot in self.turn_order] current_trick = [card for _, card in current_trick] all_bets = {k.name: v for k, v in self.all_bets.items()} for _ in range(1500): current_trick_copy = list(current_trick) hands = deal(out, self.dead_cards, hand_sizes) my_hand = hands[self.my_index] = list(self.hand) scores = [dirichlet_score(counts) for counts in outcomes] chosen_play = scores.index(max(scores)) current_trick_copy.append(my_hand[chosen_play]) my_hand[chosen_play] = my_hand[-1] my_hand.pop() tricks_won = simulate_random_game(hands, self.trump, (self.my_index + 1) % len(hands), current_trick_copy) if bust: outcome = -(1 + sum(self.tricks_won[bot] + trick_count == all_bets[bot] for bot, trick_count in zip(self.turn_order, tricks_won))) else: outcome = (self.tricks_won[self.name] + tricks_won[self.my_index]) == self.bet outcomes[chosen_play][outcome] += 1 best_play = max(enumerate(plays), key=lambda t: sum(outcomes[t[0]]))[1] return self.hand[best_play] def plan_update_round(self, current_scores, rounds_left): pass def plan_update_play(self, final_trick, winner): for bot in self.hand_sizes: self.hand_sizes[bot] -= 1 lead_suit = final_trick[0][1].suit for bot, card in final_trick[1:]: self.dead_cards.add(as_tuple(card)) if card.suit != lead_suit: self.out[bot].add(lead_suit) winner = max(final_trick, key=lambda t: (t[1].suit == self.trump, t[1].suit == final_trick[0][1].suit, t[1].rank))[0] self.tricks_won[winner] += 1 plan_bot = ("PlanBot", plan_make_bet, plan_play_card, plan_update_round, plan_update_play) ``` [Answer] # Conservative Bot This bot always bets 0, and tries its best to get rid of the biggest cards it has. ``` def conservative_make_bet(self, turn_order, trump): self.trump = trump return 0 def conservative_play_card(self,current_board): suit_count = {s:len([c for c in self.hand if c.suit == s]) for s in ["S","H","D","C"]} if current_board == []: if all(card.suit == self.trump for card in self.hand): return min(self.hand, key=lambda c: c.rank) return min([c for c in self.hand if c.suit != self.trump], key = lambda c: c.rank) trump_on_board = any(c[1].suit == self.trump for c in current_board) valid_cards = [c for c in self.hand if c.suit == current_board[0][1].suit] if valid_cards: if trump_on_board: return max(valid_cards, key = lambda c: c.rank) winning_card = max([c for c in current_board if c[1].suit == current_board[0][1].suit], key = lambda c: c[1].rank) losing_cards = [c for c in valid_cards if c.rank < winning_card[1].rank] if losing_cards: return max(losing_cards, key = lambda c: c.rank) return min(valid_cards, key = lambda c: c.rank) if trump_on_board: winning_card = max([c for c in current_board if c[1].suit == self.trump], key = lambda c: c[1].rank) small_trumps = [c for c in self.hand if c.rank < winning_card[1].rank and c.suit == self.trump] if any(card.suit != self.trump for card in self.hand) and not small_trumps: return max([c for c in self.hand if c.suit != self.trump], key = lambda c: c.rank * 8 + suit_count[c.suit]) if small_trumps: return max(small_trumps, key = lambda c: c.rank) return min(self.hand, key = lambda c: c.rank) if all(card.suit == self.trump for card in self.hand): return min(self.hand, key = lambda c: c.rank) return max([c for c in self.hand if c.suit != self.trump], key = lambda c: c.rank * 8 + suit_count[c.suit]) def conservative_update_round(self, current_scores, rounds_left): pass def conservative_update_play(self, final_board, winner): pass conservative_bot = ("Conservative", conservative_make_bet,conservative_play_card,conservative_update_round,conservative_update_play) ``` [Answer] # Half ``` def half_make_bet(self, _, trump): self.trump = trump self.wins = 0 self.bet = len([i for i in self.hand if i.rank > 8]) // 2 return self.bet def half_play_card(self, current_board): if not current_board: return min(self.hand,key=lambda card: card.rank) valid = [i for i in self.hand if i.suit == current_board[0][1].suit] if valid: return max(valid,key = lambda i: i.rank) if self.wins > self.bet: return self.hand[0] if self.bet - self.wins >= len([i for i in self.hand if i.rank > 8 or i.suit == self.trump]): return max(self.hand, key = lambda i: i.rank + 1000 * (i.suit == self.trump)) return min(self.hand, key = lambda i: i.rank + 1000 * (i.suit == self.trump)) def half_update_round(self, a, b): pass def half_update_play(self, a, w): self.wins += w == self.name half_bot = ("Half", half_make_bet, half_play_card, half_update_round, half_update_play) ``` [Answer] # sans. sans has arrived to pass Judgement. However, being sans, he aims low and plays lazily. ``` def sans_make_bet(self,turn_order,trump): return 1 def sans_play_card(self,current_board): if current_board: for card in self.hand: if card.suit == current_board[0][1].suit: return card return self.hand[-1] def sans_update_round(self, current_scores, rounds_left): pass def sans_update_play(self, final_board, winner): pass sans = ("sans.", sans_make_bet, sans_play_card, sans_update_round, sans_update_play) ``` [Answer] # BasicCardStrat ``` def bcs_make_bet(self, turn_order, trump): self.wins = 0 self.trump = trump self.played = [] winners_by_suit = {"C": 14, "D": 14, "H": 14, "S": 14} for card in self.hand: if winners_by_suit[card.suit] == card.rank: winners_by_suit[card.suit] -= 1 winner_count = 56 - winners_by_suit["C"] - winners_by_suit["D"] - winners_by_suit["H"] - winners_by_suit["S"] threshold = 3 + len(turn_order) face_count = sum(1 for x in self.hand if x.rank > threshold) - winner_count trump_count = sum(1 for x in self.hand if x.rank <= threshold and x.suit == self.trump) self.bet = int(winner_count * 0.75 + face_count * 0.33 + trump_count * 0.5) return self.bet def bcs_play_card(self, current_board): # Check if we're winning more than projected winners_by_suit = {"C": 14, "D": 14, "H": 14, "S": 14} for card in self.hand: if winners_by_suit[card.suit] == card.rank: winners_by_suit[card.suit] -= 1 winner_count = 52 - winners_by_suit["C"] - winners_by_suit["D"] - winners_by_suit["H"] - winners_by_suit["S"] face_count = sum(1 for x in self.hand if x.rank > 10) - winner_count trump_count = sum(1 for x in self.hand if x.rank <= 10 and x.suit == self.trump) ahead = int(winner_count * 0.75 + face_count * 0.33 + trump_count * 0.5) + self.wins - self.bet # Determine which cards are guaranteed winners (barring trump) winners_by_suit = {"C": 14, "D": 14, "H": 14, "S": 14} played_by_suit = {"C": 0, "D": 0, "H": 0, "S": 0} all_played = sorted(self.played, key=lambda x: -x.rank) for card in all_played: played_by_suit[card.suit] += 1 if winners_by_suit[card.suit] == card.rank: winners_by_suit[card.suit] -= 1 if not current_board: winners = [x for x in self.hand if winners_by_suit[x.suit] == x.rank] if len(winners): return next((x for x in winners if x.suit == self.trump), winners[0]) if ahead > 0: return max(self.hand, key=lambda x: x.rank - (15 if x.suit == self.trump else 0)) # Get rid of others' trump trump_cards = [x for x in self.hand if x.suit == self.trump] if trump_cards: return min(trump_cards, key=lambda x: x.rank) return min(self.hand, key=lambda x: x.rank + played_by_suit[x.suit]) lead_suit = current_board[0][1].suit valid = [x for x in self.hand if x.suit == lead_suit] is_trumped = lead_suit != self.trump and any(x[1].suit == self.trump for x in current_board) current_winner = max([x.rank for (_,x) in current_board if (x.suit == lead_suit and not is_trumped) or (x.suit == self.trump)]) # If I have more winners than tricks I want to take, try to slough one if ahead > 0: if valid: if is_trumped: current_winner = 15 return max(valid, key=lambda x: -x.rank if x.rank > current_winner else x.rank) if is_trumped: trump_cards = [x for x in self.hand if x.suit == self.trump and x.rank < current_winner] if trump_cards: return max(trump_cards, key=lambda x: x.rank) return max(self.hand, key=lambda x: x.rank - (15 if x.suit == self.trump else 0)) if not is_trumped: if valid: # If I want to win and I have a winner for this suit, play it. winner = next((x for x in valid if winners_by_suit[x.suit] == x.rank), None) if winner: return winner # Play my lowest winning card winners = [x for x in valid if (x.rank > current_winner)] if len(winners): return min(winners, key=lambda x: x.rank) return min(valid, key=lambda x: x.rank) winners = [x for x in self.hand if x.suit == self.trump] if len(winners): return min(winners, key=lambda x: x.rank) if is_trumped: # Have to follow suit if possible if len(valid): return min(valid, key=lambda x: x.rank) winners = [x for x in self.hand if x.rank > current_winner and x.suit == self.trump] if len(winners): return min(winners, key=lambda x: x.rank) # Finally, play my worst card if valid: return min(valid, key=lambda x: x.rank) return min(self.hand, key=lambda x: x.rank + (15 if x.suit == self.trump else 0)) def bcs_update_round(self, a, b): pass def bcs_update_play(self, final_board, winner): self.played += [x[1] for x in final_board] if self.name == winner: self.wins += 1 bcs_bot = ("BasicCardStrat", bcs_make_bet, bcs_play_card, bcs_update_round, bcs_update_play) ``` Some very simple card game strategy. Play winners, try to win with trump, slough when needed. Feel free to adapt this into other bots. [Answer] # Random Bot Simulates a random game and guesses the number of hands it wins in that random game. It always chooses a random card. ``` from random import sample def make_random_bot(): def pick_random(hand, suit): if suit is None: return sample(hand, 1)[0] shuffled = sample(hand, len(hand)) for card in shuffled: if card.suit == suit: return card return shuffled[0] def simulate_random_game(hands, trump): hands = [[c for c in hand] for hand in hands] hands_won = [0] * len(hands) last_won = 0 for h in range(7): last_suit = None cards = [] for i in range(len(hands)): player = (i + last_won) % len(hands) card = pick_random(hands[player], last_suit) last_suit = card.suit hands[player].remove(card) cards.append(card) winner_i = max(range(i), key=lambda i: (cards[i].suit == trump, cards[i].suit == cards[0].suit, cards[i].rank)) last_won = (winner_i + last_won) % len(hands) hands_won[last_won] += 1 return hands_won def make_bet(self,turn_order,trump): cards = list(set(Deck().cards) - set(self.hand)) other_cards = sample(cards, k=7*(len(turn_order) - 1)) hands = [] i = 0 for bot in turn_order: if bot == self: hands.append(self.hand) else: hands.append(other_cards[i * 7: (i+1)*7]) i += 1 result = simulate_random_game(hands, trump) return result[turn_order.index(self)] def play_card(self,current_board): hand = sample(self.hand, k=len(self.hand)) if current_board: for card in hand: if card.suit == current_board[0][1].suit: return card return hand[0] def nop(self, a, b): pass return ('Random', make_bet, play_card, nop, nop) random_bot = make_random_bot() ``` ``` ]
[Question] [ # Introduction In [this challenge](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/22202#22202), I asked you to implement swap encoding. Swap encoding is an encoding method where you iterate through the string, reversing substrings between identical characters. The basic algorithm is: For each character in the string: Check: Does the string contain the character again, after the instance you found? If so, then modify the string by reversing the section between the character and the next instance, inclusive. Otherwise do nothing. # Example Start with the string 'eat potatoes'. e is found again, so reverse that section: `eotatop taes` o is found again, so reverse that section (doing nothing as it is palindromic) t is found again, so reverse that section (doing nothing as it is palindromic) a is found again, so reverse that section: `eotat potaes` t is found again, so reverse that section: `eotatop taes` None of 'op taes' are found again, so `eotatop taes` is our final string! Anyway, in [this chat](https://chat.stackexchange.com/rooms/123489/discussing-swap-function), @okie and I discussed what would happen if you repeatedly ran the swap algorithm on something until it returned to the original string. We managed to prove that it will always return. Okay, that's a lot of preamble. Here's your challenge: Write a program or function that takes a string as input, and returns the number of times it has to be swapped before it will return to itself. # Scoring Answers will be timed on their combined score on all the scored testcases, so please append a snippet to your program that runs all the testcases one after another. I will time all answers on all on my computer (2018 Macbook Air), although please link to a downloadable interpreter/compiler for less mainstream languages. [Here](https://tio.run/##ZZBdboMwEITfOcX2zY6JiSn5qVLO0AMgpCBik42QjWxCLFU5OwXSIpS@2ZpvZnf2WnSFKy027Vqbs@x7ddNli0aDuxcN8fQ7AEBIYXMcHvcL1pIgfILntdRVe5l0ADUQnrsay0FmgnLUZ@m/FPEZ5nRCUBEFb2kKa/FrAvAL2yZEyjLO@ZwTKoYspjm3spPWSUL51aA@nYDNricyxT2eYxgbNx0/VrY3q8Efg0fQFXaqMbVqrCmlc7ywVZfFOQ2nRUQQRaXRztSS16b6R73ISIO/c4ytXmmIVgt6FZF5OoaeMUqDZZinfd/H79vksPvYi3grkljsD3HyAw) is my reference implementation. # Testcases # Simple testcases (Just to check it works): ``` 1231 => 2 1234512345 => 6 123142523 Sandbox for Proposed Challenges => 1090 Collatz, Sort, Repeat => 51 Rob the King: Hexagonal Mazes => 144 Decompress a Sparse Matrix => 8610 14126453467324231 => 1412 12435114151241 - 288 Closest Binary Fraction => 242 Quote a rational number => 282 Solve the Alien Probe puzzle => 5598 ``` # Scored testcases (The ones I'm timing you on) ``` 124351141512412435325 => 244129 Write a fast-growing assembly function => 1395376 And I'm now heading to the elevator => 207478 I'm in the now infamous elevator => 348112 1549827632458914598012734 => 1025264 i was always mediocre at golfing => 1232480 tho, i like some code challenges => 2759404 I am once again in an elevator => 1606256 A person with mannerism of cat => 867594 ``` # IMPORTANT To make it fair, I have to time all programs under the same load on my computer. So if one person requests a retime, I have to retime them all. This means your time may fluctate. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 3.809 seconds Compile with `g++ -O3 -std=c++14`. As requested by the OP, the testcases were included in the source. ``` #include <stdio.h> #include <string.h> #include <stdlib.h> constexpr int TESTCASES_NUM = 9; constexpr char *TESTCASES[TESTCASES_NUM] = {"124351141512412435325", "Write a fast-growing assembly function", "And I'm now heading to the elevator", "I'm in the now infamous elevator", "1549827632458914598012734", "i was always mediocre at golfing", "tho, i like some code challenges", "I am once again in an elevator", "A person with mannerism of cat"}; int solve(char *s, int n) { int ans = 0; int i, j; char *p, *q, b; char s0[n]; memcpy(s0, s, n); do { for(i = 0; i < n; ++i) { for(j = i + 1; j < n; ++j) { if(s[i] == s[j]) { for(p = s + i + 1, q = s + j - 1; p < q; ++p, --q) { b = *p; *p = *q; *q = b; } break; } } } ++ans; } while (memcmp(s0, s, n)); return ans; } int main(int argc, char **argv) { for(int t = 0; t < TESTCASES_NUM; ++t) { char* s = TESTCASES[t]; int n = strlen(s); int count[300]; memset(count, 0, sizeof(count)); for(int i = 0; i < n; ++i) { ++count[s[i]]; } char z[n]; int m = 0; for(int i = 0; i < n; ++i) { if(count[s[i]] == 1) { if(i > 1 and count[s[i - 1]] == 1 and count[s[i - 2]] == 1) { continue; } } if(i > 1 and s[i] == s[i - 2] and count[s[i - 1]] == 1) { --m; continue; } if(m == 0 and count[s[i]] == 0) { continue; } z[m++] = s[i]; } while(m > 1 and count[z[m - 1]] == 1) { --m; } printf("%d\n", solve(z, m)); } } ``` [Try it online!](https://tio.run/##lVVLb9pAEL77V4yoqhpsV5hHk4gkUlTl0EPbQ1L1QFG12GuzxN413iU0RPz10lkbsB3MoysO3tlv5psn4yWJE3reev2OcS@a@xSupfKZ@Di5NcqilPHwrcyP2FjLDE9wqeifJAXGFTzePzx@vnu4f/j97cdXuIGrQQngTUgKrR1kWAGPEP3acDu9bt91e24fv7JLt9Nv2ND4mTJFgUBApHLCVCzQJyBS0ngcvUAw555igmvkHffhy4cYuFjAhBJfA5UANaFAI/pMlEg1TEMYz8QayXhAYjGXFYzb711ddi4@dTu9/uWV2@tfXbbdzkW3px8ZLIgEEi3Ii4SYYt68FD1UEIooQFKNURNhA4OIPVGQIqbgCUwf5iGKKA@pzBwBEoPgHuqGBD3CH@EVN@4goakUHBZMTSAmnNOUSVQKwCOqsRoYhs69FNEzNfMkSzsrB2/CqwF49IVwiTluD3YCZsM0v@VKiQ2tmQ3jkky2h3yU32Mae8mLKds2oHXezKW@2DDoE4jUZBkHBn0NfACWxZolwBY0RRADC9wBTLfA6Vtg5mZgyiHD3rgBOZyO6iBbmwnalGgzs2vDbHOdgqNpEqSZaRoM0nFmhwzpM0bNVjI4@N7STK3ZEYDmHte/r2ql45SSp32FKri4FV@WhVXNFVewmLCIgqkLFSdFoTaVSqmap7q3EL/KOybGfjOz1khDz950QQsvz9v8ZBVFgMqrqjCLlanVGVXlZGobLdCNVsy5GhWhaWPAdW1UijNgymbxVgF5Ys7VsNtul5QxMkmVmT3ZoONjSyqCXNAsWdq6fbIZLSvn0U1WIlpV4oHlbgi23sXFJP0XH9s4mxPqtnYPtD2DW3CxWj7sFHQnb5T2HjpHrGVxCK4Yn9Pzm2zPj2IQc8KDztX54DjxPnW9U3suxNpqu0qXU7XrqM6xuhzGlqVXjjZVV/dslpC5WgRUOxJnJcbVflsnuEhVYDbe@7/0psr/r5c2xNvWXeFgrte1O9A4bwEaZ2w/49TqMw7uPePU0jNObTzj@Lozju@6v14QkVCune/dfw "C++ (gcc) – Try It Online") The naive implementation, with a couple of preprocessing optimizations. Say that a character is *unique* if it occurs exactly once in the input string. * If there are more than 2 consecutive unique characters, we can remove some of them until there are exactly 2 consecutive ones. * We can remove every prefix or suffix consisting entirely of unique characters. * We can make substitutions `aba -> a` whenever `b` is unique (thanks to [kops](https://codegolf.stackexchange.com/users/101474/kops) for the suggestion!). [Answer] # C, 1.972 seconds In 2021 we don't have faster CPUs, we just have more cores. Let's use them! Naive implementation using POSIX threads to parallelize. A simple but fast hash is used to save some string compares. Update: unrolled loop for short distances to shave off 9% percent. Update 2: flag unique characters to prevent unnecessary searching for duplicate character (saves additional 12%, now saved 19% over original code). ``` // To compile: // $ gcc -Wall -O3 JasonSmith.c -lpthread -o JasonSmith // #include <assert.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define UNIQUE_MASK (0x80) /** * Test Vectors with expected answers. */ typedef struct { const char *text; int expected; } test_vector_t; test_vector_t test_vectors[] = { { "124351141512412435325", 244129 }, { "Write a fast-growing assembly function", 1395376 }, { "And I'm now heading to the elevator", 207478 }, { "I'm in the now infamous elevator", 348112 }, { "1549827632458914598012734", 1025264 }, { "i was always mediocre at golfing", 1232480 }, { "tho, i like some code challenges", 2759404 }, { "I am once again in an elevator", 1606256 }, { "A person with mannerism of cat", 867594 }, }; int nr_test_vectors = sizeof(test_vectors)/sizeof(test_vectors[0]); /** * Worker thread * @param test vector to process */ void process(test_vector_t *test_vector) { // swap encoding is destructive, so first make copy // of challenge text in separate buffer char text[strlen(test_vector->text) + 1 + 5]; memset(text, 0, sizeof(text)); strcpy(text, test_vector->text); // flag unique characters by setting high bit for (char *p = text; *p; p++) { assert((*p & UNIQUE_MASK) == 0); // assume no "weird" UTF-8 chars int is_unique = 1; for (char *q = text; *q; q++) { if (p == q) continue; if (*p == *q) { is_unique = 0; break; } } if (is_unique) *p |= UNIQUE_MASK; } // flagged text no longer matches original text, so we must // save flagged text as the new "original" for comparison later. char orig[strlen(text) + 1]; strcpy(orig, text); // calculcate hash of original text unsigned long original_hash = 0; for (char *p = text; *p; p++) { original_hash = original_hash*31 + *p; } // repeatedly swap encode until original text is back unsigned long hash; unsigned int count = 0; do { hash = 0; for (char *p = text; *p; p++) { hash = hash*31 + *p; // no need to search for duplicate of unique character if ((*p & UNIQUE_MASK) != 0) continue; // unrolled loop for short distances if (p[0] == p[1]) continue; if (p[0] == p[2]) continue; if (p[0] == p[3]) { char temp = p[1]; p[1] = p[2]; p[2] = temp; continue; } if (p[0] == p[4]) { char temp = p[1]; p[1] = p[3]; p[3] = temp; continue; } if (p[0] == p[5]) { char temp = p[1]; p[1] = p[4]; p[4] = temp; temp = p[2]; p[2] = p[3]; p[3] = temp; continue; } // scan for larger distances char *last = p+6; while (*last && *last != *p) last++; if (*last) { char *start = p; while (++start < --last) { char temp = *start; *start = *last; *last = temp; } } } count++; } while (hash != original_hash || strcmp(orig, text)); // show result to user printf("%-40s -> %8d (%s)\n", test_vector->text, count, (count == test_vector->expected ? "Ok" : "FAIL")); } /** * Main */ int main() { pthread_t threads[nr_test_vectors]; for (int i = 0; i < nr_test_vectors; i++) { pthread_create(&threads[i], NULL, (void (*))process, test_vectors+i); } for (int i = 0; i < nr_test_vectors; i++) { pthread_join(threads[i], NULL); } return 0; } ``` [Answer] # [C (clang)](http://clang.llvm.org/), 5.383 seconds ``` #include <strings.h> #include <string.h> #include <stdio.h> #include <stdlib.h> unsigned int f(char* str) { unsigned int count = 0; char original[strlen(str) + 1]; strcpy(original, str); do { for (char* current = str; *current; ++current) { for ( char* last = index(current + 1, *current), *start = current; last > start; ) { char temp = *start; *start++ = *last; *last-- = temp; } } ++count; } while (strcmp(original, str)); return count; } int main(int argc, char** argv) { #ifdef SIMPLE char* tests[] = {"1231", "1234512345", "123142523", "Sandbox for Proposed Challenges", "Collatz, Sort, Repeat", "Rob the King: Hexagonal Mazes", "Decompress a Sparse Matrix", "14126453467324231", "12435114151241", "Closest Binary Fraction", "Quote a rational number", "Solve the Alien Probe puzzle"}; int expected[] = {2, 6, 4, 1090, 51, 144, 8610, 1412, 288, 242, 282, 5598}; #else char* tests[] = {"124351141512412435325", "Write a fast-growing assembly function", "And I'm now heading to the elevator", "I'm in the now infamous elevator", "1549827632458914598012734", "i was always mediocre at golfing", "tho, i like some code challenges", "I am once again in an elevator", "A person with mannerism of cat"}; int expected[] = {244129, 1395376, 207478, 348112, 1025264, 1232480, 2759404, 1606256, 867594}; #endif char* checker[] = {"\xE2\x9C\x95", "\xE2\x9C\x93"}; for (int index = 0; index < sizeof(expected)/sizeof(*expected); ++index) { char* t = tests[index]; char buff[strlen(t) + 1]; strcpy(buff, t); int s = f(buff); int e = expected[index]; printf("\"%s\" -> %d %s\n", t, s, checker[e==s]); } } ``` [Try it online!](https://tio.run/##dVXbbts4EH3XVwwcFGs78sa6@bJpAmTTFht0g@02D/vQ5IGWKJkoRQqkFDsO/OubztCyY@ciwDI5c@bCOaNhOkglU8XTSR8usgwGn@Dm6vrb358h1WUlJDeQS1ZArcE0CqwoK8mh5rZOmeXQP3k6EiqVTcbho62NUIX9fX7uvRS@lGVCvxJJMSOZ1ygrCsUzEKqGvJvOmekDuul5jx7gc6BPdYPvMxieek5JaNBGFEIx@QOtJFddMoZjCO5OHQa3afXQ3aJ857y1zzRsotCTawNt/LQxhrtICD6Ffrs/hePjdtnbmT072Dk5kGyfjWfJLLkVKuPL7jYMJuvvgvT8N837tmaGTLe5vIly7s/BYV8jegeSR@@tFJHtssIw/Xd8bOTHxwShaG8gSDwYIIBcHerX3usV1pRo3QDXsJhjHwKxmJbVC9q2vBleN0ZBa7f2PGqOkgnVpQUzRepv6t2nzT310pHIM5637e49E0LNbX/cYbaPnSCMgo4P9B8n7tXugjhMwog2N0xlM710PH8zutIWW/NyziR2XsEtQS61lKxe@XCjTe3Dd15xVpPiu55BPefwFT@RP@AvvmSFxqPBNVttLD9x@gwNtxYY3FTM4Dd3zfCTWro84iAcxUkUj8ZRGO9SjaMkQBXmGzvJpcScsAv@xLKZB/hiWFoLrUj1b6Nrjq4NIwlGVk0548adS8t77rK7kIIrOtuMQ9WsVpJ31htuqLZ8WfG05tmmYqEPIx9iH4LhdOhDgm0cxLidjIIhLQMEhJMJvmK3wleSTCfo74hLy9@lYf9MtIlCx8R/Rrj8c2qwwugFFhKYtbycyQfIG7U76YXK4Oq3EpRewJyzjIA41Oh8XPJ7Vmt3aoII5cSEFCpnpW7sASZI4ukkHI@w5slkGsSY/zAIx1FMSgELhmTJBXuwUHIcdKnBDGsotMwxKGHqufZBgBQ/OVhdcmxbnIHpQc9cAStBqxRtC2xjSoqpgzQuoOLGagULUc@x15XiRlg0yiHF9nqfohhLOEUyomkSjZGtcDiOx0hJFE8C4icYYm@PiMMQjzhB3sJxMo2HJBkNR2EyIj5J5GhTmci9PeLSOU9/coPBwJF3u/wc3i6nl/hznO3to22WbkhSqm4MunneLj/inbPiOu9uD9E7aQX9nYSmsEP39kZY20Vu6FAnOcDd6YEeZk2eb2@Jev@O2LsnCOND3XtWUKIWHedO90LBUbEr@MugFV6Gdd7t3HY@2NsODM7hQwa4pBbFyWD9XfX42Zm9a12vvfXT0/8pXcT2afBP9As "C (clang) – Try It Online") Compile with `-O3`. [Answer] # Rust, 9.659 seconds Port of [@Delfad0r's C++ answer](https://codegolf.stackexchange.com/a/225055/110802) in Rust. [Try it online!](https://tio.run/##jVVNb@IwEL3zK6YcsolaIsLH9oOlUlX1sGeq3QNCyDVOYurYUeyASstfX3YcCKQJq66FIifzZua9GY/Jcm12O22I4RSenybPjw@Tp8kdOFNHm2wGY9y1AFc76A36wyAYBEPcFS/93rB9tTf@zrhhQCAk2nSiTK25jIBozZIX8QZhLqnhSpboB7mAn98SkGoNMSMLCzYKTMyACbYiRmUl1MK4LEwWzWVIEpXrBi4YDm5vetff@73B8OY2GAxvb7pB77o/KAEc1kQDEWvypiFhC65ohowNREqESKDEmVhdAQfBXxlolTCgaoGPmAjBZMT0kRiQBJSkGCMiyBB/RDZoPUDKMq0krLmJISFSsoxrdAyBEoOo2ajVCiVmEivmJrkBfQe/GP2BCbN7Dzr3wPs9eC@iCWbAQojU2Jfu6PhRZTzikoi5/a59KpRkrnewK5Ue/O0KVYbqkGzX97WPklyvYrWLh0XMCWp3lx4GdDlcQnCEez6Wa@F@OMsP0FOORwRzTpezehy70L73Xc78jK2wFEde5dq2mjsr8HIMwQmJpLRNVFH6Di8ZI6@jg9/@iZ6tbVHRBJty1GZVO4ZpQ4lmVv3xpFdIW9XV6qP00sW3H7Tr@VThMaCmKsK6yaLuRXmwn1WL7RdVuTSIWDF6Me2OoN/tzkafOuLQ2LJydK2GhecUjXh0c803bFary7aZbVNmquUouy6b/d6nKZp5SoTVDs60FOEc7tHkOCc/6EDQ8K0Bev8RfK9ZGi5zNmpYt61/v1VpnU7lIe@XVM/KPE7B3E7Bxk9Vag/UieBXhDY@13OWpOYN/aocavm7Z/Kfr8LnFEgp17FrA3qjM2O0jrlgJxmOwMt5L8Xuzg3@nqG1NipUFqCumgmcqNosfqaRZlwaIS/c9vu2fXW46jbegfIW53W3@0NDQSK96zyq1HTwEmVi3Mc3YdQ4JAZ3hmQRMx2a5mOJf1Yr9hc) ``` static TESTCASES: &[&str] = &[ "124351141512412435325", "Write a fast-growing assembly function", "And I'm now heading to the elevator", "I'm in the now infamous elevator", "1549827632458914598012734", "i was always mediocre at golfing", "tho, i like some code challenges", "I am once again in an elevator", "A person with mannerism of cat", ]; fn solve(mut s: Vec<char>) -> i32 { let mut ans = 0; let original_s = s.clone(); loop { for i in 0..s.len() { if let Some(j) = (i + 1..s.len()).find(|&j| s[i] == s[j]) { s[i + 1..j].reverse(); } } ans += 1; if s == original_s { break; } } ans } fn main() { for &testcase in TESTCASES { let s: Vec<char> = testcase.chars().collect(); let n = s.len(); let mut count = vec![0; 300]; for &ch in &s { count[ch as usize] += 1; } let mut z = vec![]; for i in 0..n { if count[s[i] as usize] == 1 { if i > 1 && count[s[i - 1] as usize] == 1 && count[s[i - 2] as usize] == 1 { continue; } } if i > 1 && s[i] == s[i - 2] && count[s[i - 1] as usize] == 1 { if let Some(_) = z.pop() { continue; } } if z.is_empty() && count[s[i] as usize] == 0 { continue; } z.push(s[i]); } while let Some(&last) = z.last() { if count[last as usize] == 1 { z.pop(); } else { break; } } println!("{}", solve(z)); } } ``` ]
[Question] [ [Codidact post](https://codegolf.codidact.com/posts/280092), [CGCC Sandbox](https://codegolf.meta.stackexchange.com/a/20491/80214), [Codidact Sandbox](https://codegolf.codidact.com/posts/279245) Given three positive integers as input, animate an ascii-art polygonal loading symbol on the screen. ## Intro You will be given three inputs, \$n\$, \$l\$, and \$d\$... \$n\$ (one of \$3\$, \$4\$, \$6\$, or \$8\$), is the number of sides of a polygon: ``` * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ``` \$l\$ is the side length to use. (The above all use \$l = 3\$, the minimum possible value). You may use any printable ASCII character other than space instead of `*`. \$d\$ is the load length and is less than the perimeter. The task is to create a loading animation as follows: 1. Make the first frame of the animation by starting at any one of the topmost corners and drawing the perimeter until its length is \$d\$. 2. Make the next frame by shifting this partial perimeter by 1 clockwise. 3. Repeat step 2 ad-infinitum. For example, \$n=3,l=3,d=4\$ would result in the following steps: ``` * * * * * -> * -> * -> * -> * * -> * * -> . . . * * * * * * * * * * * * ``` ## Example Here is a solution made by [Hakerh400](https://codegolf.codidact.com/posts/280096#answer-280096): [Try It Online!](https://hakerh400.github.io/cg/280092/) ## Further details(important): * You are guaranteed that \$n∊(3,4,6,8)\$ * You are guaranteed that \$l≥3.\$ You are guaranteed that \$d<(l-1)×n.\$ * There must be a delay of at least 0.1 s between each step. You can have a delay of up to 10 seconds. * Your language is allowed to output a list of steps infinitely if and only if it cannot clear the screen or do something similar. * If so, there must be at least 2 newlines between each step. * This is not [graphical-output](/questions/tagged/graphical-output "show questions tagged 'graphical-output'"). ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in each language wins. [Answer] # JavaScript (ES8), 265 bytes ``` (n,l,d)=>setInterval(_=>(g=i=>i<q?g(i+1,(m[y-=634%~(D+=i%l?0:+("02112122230"[(n*12^i/l)%43%29]||1))-2>>1]=m[y]||[...''.padEnd(l*4)])[x-=D<4?D-1:5-D]=(i+j)%q<d?0:" "):C.log(m.reverse().map(r=>r.join``).join` `))(y=D=!++j,(C=console).clear(x=l*3,m=[])),j=100,q=n*--l) ``` [Try it online!](https://tio.run/##JY3RaoMwFEDf9xWbIL1Xk8xEO6j02oe6h32DuFVqKpEY21hKC2W/7oQ9Hc7LOX1za6ajN@crd2Or5xPN4JhlLVIx6euXu2p/ayz8UAEdGSrM9rLrwMSSwVA9OH2kWfgLZUwmtLskjyFIlJRKKqXSJKjARVJ9m3eLYZaGalM/nxKRq6KQNS2BxSshxGolzk376VqwUYY1VndO5TbblVzma17WtBx7DC/bdnkErwHme2HHDgbh9U37SQOKoTmDp8KLfjTucMB/vhwQ4UElvcVxz2BPx9FNo9UojlY3Hu5ko5QNVNWIrCeZJOxCLuLc4nyClK3ZBuc/ "JavaScript (Node.js) – Try It Online") ### Snippet ``` f= (n,l,d)=>setInterval(_=>(g=i=>i<q?g(i+1,(m[y-=634%~(D+=i%l?0:+("02112122230"[(n*12^i/l)%43%29]||1))-2>>1]=m[y]||[...''.padEnd(l*4)])[x-=D<4?D-1:5-D]=(i+j)%q<d?0:" "):C.log(m.reverse().map(r=>r.join``).join` `))(y=D=!++j,(C=console).clear(x=l*3,m=[])),j=100,q=n*--l) console.log = s => o.innerHTML = s; f(3, 5, 9) ``` ``` <pre id="o"></pre> ``` [Answer] # [JavaScript (V8)](https://v8.dev/), ~~353~~ 318 bytes ``` f=(n,l,d,o=0)=>{w=[...{3:'330231',4:'42240220',6:'423313021131',8:'4233231302112131'}[n]] a=Array(3*l).fill().map(_=>Array(4*l).fill` `) x=n==4?0:l,y=0 for(i=0;i<d+o;++i){a[y][x]=i>=o?'*':' ' j=~~(i/(l-1))%n*2 x+=w[j]-2 y+=w[j+1]-2}(c=console).clear() c.log(a.join` `.replace(/,/g,'')) setTimeout(_=>f(n,l,d,o+1),100)} ``` [Try it online!](https://tio.run/##NZDLbsIwFET3/go2lX2JMX5EFQq9oP5Dd1HUWCFBjkyMkhSIEPx6SkrZzZyzGU1tT7YrWnfsF6fVOFbIGu75jgeUgJvrGVMhxNUk1BipjaI8TmisdSy1lpS/T8UY9XBKTXb1BPof6Qne0ibLiMXPtrUDM3MPonLeMxAHe2TfuHmK@CXyWQ7kgg1ivJWJ5wNKUoWWOZRr97GLwjqKHFxtOmTpJUO3wbClc5rQGSU13u/MLZlfKIC3Zq7JJcJzWmcLTYa/FKlHvrECi9B0wZcgCl/algEphA97ZkUdXJOTXLTl0duiZEu@3HNKAUhX9l/uUIaffppdva6KFHAlJdzGihlueAzjLw "JavaScript (V8) – Try It Online") On the tio.run it displays all output instantly, but in the browser console it animates as it should. ``` f=(n,l,d,o=0)=>{w=[...{3:'330231',4:'42240220',6:'423313021131',8:'4233231302112131'}[n]] a=Array(3*l).fill().map(_=>Array(4*l).fill` `) x=n==4?0:l,y=0 for(i=0;i<d+o;++i){a[y][x]=i>=o?'*':' ' j=~~(i/(l-1))%n*2 x+=w[j]-2 y+=w[j+1]-2}(c=console).clear() c.log(a.join` `.replace(/,/g,'')) setTimeout(_=>f(n,l,d,o+1),100)} f(3,3,4) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~69~~ 65 bytes ``` NθNηNζ≔⁰εRWφ¹«≦⊖εF§⪪”)″‴Byε=μχ?⟦⌕r”8θF⊖η«≦⊕ε✳Iκ⁺§ *‹﹪ε×⊖ηθζ× №04κ ``` [Try it online!](https://tio.run/##XY5Ra4MwFIWf9VeEPN0MB9pZFfZU2hdhHWUb7Nnp7QyLiU3iGB397e7WjiJ9CeckOec7dVvZ2lRqHEvdD/556D7QwkE8hnPf3vgj@ZVz8lNDHDEk94J7i659b6VCSOgyEew3DLZV//9vg7XFDrXH5pII9sYyWPlSN/gDr72SHni@TB@SuCjyjMSCVJ4mRZYu4oJHjBdcROwgBJuis0YaOOFmvFLf8oKdldrDRlqsvTQa1pXz8CWoc6cGd53C2R3BntA52JpmUAYwYm@yQ3eDnLZE7Hg@Lu@cUXJtBsLwOCVN7eLMPoWncczCZZiP99/qDw "Charcoal – Try It Online") Link is to verbose version of code with 100× speed-up (`φ` replaced with `χ`) so that you can get results in a reasonable amount of time; each frame is separated by `␛ [2J␛ [0;0H`. Explanation: ``` NθNηNζ ``` Input `n`, `l` and `d` as numbers. ``` ≔⁰ε ``` Keep track of how many frames have passed and which step we are on the current frame. ``` RWφ¹« ``` Every second, run the rest of the code and refresh the screen. ``` ≦⊖ε ``` Decrement the frame/step counter, so that each frame starts a step later than the previous. ``` F§⪪”)″‴Byε=μχ?⟦⌕r”8θ ``` Look up the direction vectors for the appropriate shape in a compressed string and loop over them. ``` F⊖η« ``` Loop over the length of each side. ``` ≦⊕ε ``` Increment the frame/step counter. ``` ✳Iκ⁺§ *‹﹪ε×⊖ηθζ× №04κ ``` Print a `*` if the frame/step counter is within the input length, plus a further space for a horizontal movement. ]
[Question] [ The periodic table gets its shape from the arrangement of elements into blocks: [![blocks intro](https://i.stack.imgur.com/0NQAx.png)](https://i.stack.imgur.com/0NQAx.png) An element is assigned its block based on what type of orbital holds its valence electron(s). For instance, the sole valence electron of neutral hydrogen occupies the 1s orbital in the 1s subshell, and so hydrogen belongs to the s-block. The least energetic subshell is the 1s subshell, followed by 2s, 2p, 3s, etc. Electrons fill orbitals in less-energetic subshells first, in accordance with the following chart: [![arrow](https://i.stack.imgur.com/MctIX.png)](https://i.stack.imgur.com/MctIX.png) The diagonal arrows give the diagonal rule its name. When finding the block of an element, there are some important facts to consider: * Each subsequent element has one more electron than its predecessor. * Every new type of subshell (s, p, d . . . ) can hold four more electrons than its predecessor as a consequence of the presence of two additional orbitals. * All subshells (1s, 2s . . . ) have an odd number of orbitals, each of which can hold two electrons. As such, all subshells can hold twice an odd number of electrons. * Subshells beyond s, p, d and f have names reserved for their eventual observation: after f comes the rest of the alphabet, starting with g and omitting j. # The Challenge Given the atomic number of an element, output its block (a letter). Because one can tell how many electrons are held by theorized, not-yet-observed subshells, input will be less than or equal to 17296 (found with the sum \$2\sum\_{n=1}^{23}\sum\_{\ell=0}^{n-1}2\left(2\ell+1\right)\$), the atomic number of the last element with valence electrons in the 46s subshell. Letters beyond z would be needed for elements past that point, and so they will not be included in the challenge. An extended version of the diagonal line chart above can be seen [here](https://i.stack.imgur.com/5TCtB.png). # Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes in each language wins * For the purpose of this challenge, when s and p are reached a second time after f, they will be capitalized. This means letters are sequenced as follows: `s p d f g h i k l m n o P q r S t u v w x y z`. Additionally, it means output is case-sensitive. * Assume only valid input is given. * There is a discrepancy between the periodic table above and the expected output: in reality, lanthanum and actinium (57 and 89) are in the d-block, and lutetium and lawrencium (71 and 103) are in the f-block. The diagonal rule implies that lanthanum and actinium are in the f-block, and that lutetium and lawrencium are in the d-block, and so that is what the program should state. # Test Cases ``` In: 1 Out: s In: 5 Out: p In: 21 Out: d In: 57 Out: f In: 2784 Out: l In: 17296 Out: s In: 15181 Out: z In: 12024 Out: q ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 59 bytes ``` Nθ⊞υ²W›θ⊗Συ«≧⁻⊗Συθ⊞υ⁺⁴⌈υ»§”>-◧βYTB↷p{ï⭆Σ]¬∕↷›”LΦυ‹﹪⊖θΣυΣ✂υκ ``` [Try it online!](https://tio.run/##ZY7LasMwEEXX8VeIrMagLlqyKV4FQkqgLib@AsWeWiJ62JImcVL67apFH5ve1WUe595OCt85oVM62JHiG5kTepjKqmgoSCDOnhZ/lUojgxePIuY1ZztHJ409tGSAykXso1jVYtyGoAZ7VIOMUCtL4d8pZ5m@@sU3mgJsOKvFrMwPrCo@i8YrG2EbD7bHGdb3MPbvg1RnbaxrJt9Gulzn25qzV7RDlLBXOlejPAgBateTdrDDzqNBG5f8aYn@65BNq1WH@eNcfqtK6fE5PVz0Fw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input the atomic number. ``` ⊞υ² ``` Start with just an `s`-shell. ``` W›θ⊗Συ« ``` Repeat while the number of electrons left will fill all the shells twice... ``` ≧⁻⊗Συθ ``` ... remove those electrons, and... ``` ⊞υ⁺⁴⌈υ ``` ... add another shell which can hold 4 more electrons than the previous. ``` »§”>-◧βYTB↷p{ï⭆Σ]¬∕↷›”LΦυ‹﹪⊖θΣυΣ✂υκ ``` Count how many of the remaining shells have no electrons and look that up in the compressed string of block letters. (Because of the way `Sum` works in Charcoal, the calculation is adjusted slightly to avoid a sum of no elements, which ends up offsetting the result by 1, which is compensated by moving the `z` to the beginning of the string where it can be cyclically indexed.) [Answer] # [J](http://jsoftware.com/), 64 bytes *-4 for 12024 being q* ``` ('spdfghiklmnoPqrStuvwxyz'{~]{~[I.~[:+/\2+4*])&(;2#</.99|i.2#99) ``` [Try it online!](https://tio.run/##DcTJDoIwFAXQX7mBxLaihb4UoaArExMTFwaXyM6gOM8Thl@vLM7ZWkeyEqMEDD0ESFp9iXE2m1jObudVud5Uu/3heJpfrov74/l6f76sboq6yaeyyRPPX5Knu4Xo8JTcoS@N@VWSXGOEFZanpXB4IKAQgtoiUBRrQEVkBlChihUUBaT/ "J – Try It Online") ### How it works ``` 99|i.2#99 ``` Create a 99x99 matrix where each row counts up: `0 1 2 3 …` ``` ;2#</. ``` Take each diagonal `0;1 0;2 1 0` two times: `0 0 1 0 1 0 2 1 0 2 1 0 …`. ``` [:+/\2+4*] ``` Multiply each number by 4, add 2, add each number left to it: `2 4 10 12 18 20 30 …` ``` [I.~ ``` Use this as range boundaries to find the index for the input, e.g. `13`. ``` ]{~ ``` Get the corresponding shell at that index, e.g. `1`. ``` 'spdfghiklmnoPqrStuvwxyz'{~ ``` Retrieve the shell name. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 46 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [N4*̈¯O·-Ð1‹#U}A3.$„sp©Du‡®ì„ejмÁ¯.sOX<¯O%›Oè ``` Port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/207018/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##AVEArv9vc2FiaWX//1tONCrDjMuGwq9Pwrctw5Ax4oC5I1V9QTMuJOKAnnNwwqlEdeKAocKuw6zigJ5latC8w4HCry5zT1g8wq9PJeKAuk/DqP//MTI) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/2g/E63DPafbDq33P7Rd9/AEw0cNO5VDax2N9VQeNcwrLji00qX0UcPCQ@sOrwHyU7Mu7DnceGi9XrF/hA1Qi@qjhl3@h1f81zm05X@0oY6RjrGOiY6pjpmOuY6FjqWOoYGOoaGOoZGOkaGOqbmOkbmFCZBnYAQkTQ0tgDLmRpZmsQA). **Explanation:** ``` [ # Start an infinite loop: N4* # Multiply the (0-based) loop-index by 4 Ì # Increase it by 2 ˆ # Pop and add this value to the global array ¯O # Get the sum of the global array · # Double this sum - # Subtract it from the current integer, # which will be the (implicit) input in the first iteration Ð # Triplicate this new value 1‹ # If it's 0 or negative: # # Stop the infinite loop U # Pop and store the triplicated value in variable `X` # (which is 1 by default, which doesn't matter for inputs ≤ 4) }A # After the infinite loop: push the lowercase alphabet 3.$ # Remove the leading "abc" „sp # Push string "sp" © # Store it in variable `®` (without popping) D # Duplicate "sp" u # Uppercase the copy: "SP" ‡ # Transliterate "s" to "S" and "p" to "P" ®ì # Prepend "sp" from variable `®` „ejм # Remove "e" and "j" Á # Rotate it once towards the right # (we now have the string "zspdfghiklmnoPqrStuvwxy") ¯.s # Get a list of suffices of the global array O # Sum each inner suffix X< # Push value `X`, and decrease it by 1 ¯O% # Modulo it by the sum of the global array › # Check for each prefix-sum if it's larger than this value # (1 if truthy; 0 if falsey) O # Get the amount of truthy values by summing è # And use it to (0-based) index into the string # (after which the resulting character is output implicitly) ``` ]
[Question] [ A program ordinal is a (possibly transfinite) ordinal which can be assigned to programs in some language depending on their output. To be more specific: * Strings that give no output have ordinal 0 * Programs that output a program of ordinal n have ordinal n+1 * Programs P0 outputting multiple programs P1, P2... Pn have ordinal S, where S is the supremum of the set of program ordinals corresponding to the programs P1, P2... Pn Your goal is to create the shortest possible program with program ordinal ω\*ω, also writable as ω2 or omega squared. Output is required for a program. As well as this, the output must go through STDOUT or closest equivalent. All programs printed by your program must be delimited by any string, so long as the delimiter is always the same. (`acbcd` and `accbccd` are allowed, but not `acbed`) These delimiters must be the only output other than the programs themselves, unless your language must output trailing characters. Here is a program-ordinal ω program created in pseudocode, which generates programs of the form "exit, print(exit), print("print(exit)")...: ``` x=exit loop{ print(x) x='print(#x)' } ``` Within each iteration of the loop, x is printed and then wrapped in print() (exit becomes print(exit)). # is put before x in pseudocode to indicate that it is the variable x and not the actual alphabetical character x. The shortest program (measured in bytes) which has program ordinal ω2 wins. Have fun. [Answer] # [Python 2](https://docs.python.org/2/), ~~67 63~~ 65 bytes ``` x="" while 1:x="x=%r\nwhile 1:x='print%%r;'%%x;exec x;"%x;print x ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8JWSYmrPCMzJ1XB0ArIqbBVLYrJQwioFxRl5pWoqhZZq6uqVlinVqQmK1RYKwGZYAmFiv//AQ "Python 2 – Try It Online") Use the same strategy as [@UnrelatedString's answer](https://codegolf.stackexchange.com/a/205277/92237), be sure to check out and upvote his answer! Repeatedly print out programs with ordinal \$0, \omega, \omega2, \omega3,\ldots \$. The programs are separated by the string `";\n"` (a semi-colon and a new line). **[68 bytes](https://tio.run/##K6gsycjPM/r/v8JWSYmrPCMzJ1XB0ArIqbBVLYrJQwioFxRl5pWoAgVj8tRVVSusUytSkxUqYvKUgGywnELF//8A) to separate programs by a blank line.** ### Explanation A program with ordinal \$n+1\$ is created by adding a print statement around an \$n\$-ordinal program: ``` print <escaped string of ordinal-n program> ``` A program with ordinal \$\omega(n+1)\$ is created by repeatedly printing out programs with ordinal \$\omega n, \omega n+1,\omega n+2,\ldots\$ ``` x = <string of omega*n program> while 1: x = 'print %r' % x exec x ``` Note the use of `%r`, which escapes the given string `x`. This way, we don't have to worry about quote and new line characters. Finally, a program with ordinal \$\omega^2\$ is created by repeatedly printing out programs with ordinal \$0, \omega, \omega 2,\omega 3,\ldots\$: ``` # string of program to go from omega*n to omega*(n+1) s = "x=%r\nwhile 1:x='print%%r'%%x;exec x" # current omega*n program, start with n=0 x = "" while 1: # create the omega*(n+1) program from omega*n x = s % x # print it out print x ``` [Answer] # [Python 3](https://docs.python.org/3/), 85 bytes ``` s='def l(f,x):\n print(x+"\\n")\n l(f,"%s%r)"%(f,x))' exec(s) l(s+"\nl('print(',",'') ``` [Try it online!](https://tio.run/##JYu9CoAgEIB3n0IO5O7IrS3oTdxKKZBL1MGe3qzW7yfd9bhk7r2suPugIwXbeHGiUz6lUpvAOQEe4FVgiskM5qsYlW9@o8IqUhmhRMJ/QwsWkXt/AA "Python 3 – Try It Online") I... *think* this might be valid? This should print a sequence of programs, separated by blank lines, with ordinals ω, ω·2, ω·3, ω·4, ..., but the reasoning by which I arrived at those ordinals was pretty shaky and I've already forgotten what it even was, so I'd appreciate being shown that I'm completely wrong. The general idea of it is that one program with ordinal ω+ω = ω2 is one which prints a program with ordinal ω, then prints a program that prints that program (so that it has ordinal ω + 1), then prints a program that prints that, and so on... and the part I don't feel too solid about is doing that with the program with ordinal ω·2 to get to ω·3, and iterating to get ω2. [Answer] # Mathematica, 38 bytes ``` Nest[Nest[HoldForm@*Print,#,∞]&,,2] ``` Thinking process: ``` y=w="x=0;Do[Print[x=\"Print[\"<>ToString[x,InputForm]<>\"]\"],∞]";Do[Print[y=StringReplace[w,"0"->ToString[y,InputForm]]],∞] ``` This first solution is the same as the other solutions, it is a port of Surculose Sputum's answer, so I *think* it is correct. ToString[x,InputForm] sanitizes a string to be fed into it's own print statement. w stores the program that outputs the 0,1,2,3,... or the first ω, and y stores the program fed into itself n times that outputs ω+1,ω+2,ω+3..., when looped gives ω\*ω. But that got me thinking, all that nested loop does, is, well, Nest. Which is a function in Mathematica, and Mathematica also can output "held" code, meaning no handling strings. Which means I could change w to ``` w="Nest[HoldForm@*Print,0,∞]" ``` Which makes w hold a program that doesn't have a loop for n=0,1,2,3... , but has ω more directly inside it by just holding prints. Alternatively NestList would return the same n as the original program, but why waste time with printing 1, and then 2, and then 3, when we can just print a program ω. But if I do that for the first part, what's stopping me from doing that to the last part? ``` Nest[HoldForm@*Print, Nest[HoldForm@*Print, 0, ∞], ∞] ``` Well, now we have that ω2 program we wanted, but it looks a bit... referential? Like it's code is nesting itself. Nesting nests time! ``` Nest[Nest[HoldForm@*Print,#,∞]&,0,2] ``` That looks very nice. And since the program of just the keyword "Null" (not to be mistaken for the null program) is a valid program, we can golf out that 0. And it could even be changed for arbitrary ωn's, or even ωω for just two bytes more. If anyone wanted to run this themselves, I would change out the ∞ for a 3. Side note: if you really wanted to keep using strings instead of holdform: ``` Nest[Nest["Print["<>ToString[#,InputForm]<>"]"&,#,∞]&,,2] ``` is 57 bytes, and good for learning. ]
[Question] [ *Inspired by [There, I fixed it (with rope)](https://codegolf.stackexchange.com/questions/157600/there-i-fixed-it-with-rope), [There, I fixed it (with Tape)](https://codegolf.stackexchange.com/questions/157240/there-i-fixed-it-with-tape), [There, I broke it (with scissors)](https://codegolf.stackexchange.com/questions/157612/there-i-broke-it-with-scissors)* Given a string with characters from `a-z` or `A-Z` (whichever you prefer), turn missing letters into numbers and make them explode. --- # Example Input: `abcafabc` Output: `a12344321c` ***Why?*** 1) Find the missing letters (only going forward in the alphabet): `abca(bcde)fabc` 2) Replace them with the number of missing letters: `abca4fabc` 3) Replace the number with * Itself twice if it's even * Itself + 1 if it's odd In this case: `abca44fabc` 4) Explode those numbers outwards replacing any letters: `a12344321c` --- # Challenge Rules 1. Explosions can't exceed the boundaries of the string * `ae -> 343` (3 letters are missing but since 3 is odd, it's been replaced by 4) 2. Numbers can be greater than 9 * `az -> 23242423` (24 letters are missing and since 24 is even, it's repeated twice) 3. You can have multiple explosions * `abcefghijmnop -> ab121fghi1221nop` 4. Multiple explosions can overlap, take the sum of the number when they do * `abceghij -> abc(2)e(2)ghij -> ab12(1+1)21hij -> ab12221hij` 5. It's possible that no explosions occur, in that case simply return the string 6. No explosions between `ab`, `aa`, `aaa`, etc. 7. You are allowed to take the input in any reasonable format. Can be a single string, string-array/list, character-array/list, etc. Output has the same flexibility. 8. You are allowed to use lowercase and/or uppercase any way you'd like. This applies both to the input, output. # General Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-golfing languages. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422). * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link to a test for your code, preferably [Tio](https://tio.run/#). * Also, please add an explanation if necessary. --- # Test cases: ``` Input : 'abcdefgklmnopqrstuvwxyz' Output : 'abcd1234321nopqrstuvwxyz' Input : 'abdefgjkl' Output : 'a121ef1221kl' Input : 'xyzaz' Output : '20212223242423' Input : 'abceghij' Output : 'ab12221hij' Input : 'zrabc' Output : 'zrabc' ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 162 bytes ``` ->a{b=[*a=a.reduce{|x,y|[*x,*[(n=y.ord+~x[-1].ord)+n%2]*(n<1?0:2-n%2),y]}];i=-1;b.map{|x|d=-~i+=1;a.map!{|y|(z=x.to_i-(d-=1)*s=d<=>0)<1||x==b[i-s]?y:z+y.to_i}};a} ``` [Try it online!](https://tio.run/##JY7NboMwEITvfYr2UPFrK84xsMmDWFa1BhPID1ADrU1MXp3i9LI7881qtHqSdq1gJUd8SOAxAlKtyqlQD2dS63hs0piHLVja6TJ5Gk6Y8DJK2s@9iMM2Z6fdYU82F6VWLCJrgLBM0jv2W4UrgTybBFiGnnw8nHXhDIaO3VdDwpIAi@IByhyOuyhnzhkAyRsyiJM9zIl93S1Lhss6Ag9QFlhtI0gDVKj8kkWpqvP1dm@7/lsP4/Tza@z8Snxwud42vRH8Z4U6181lk7P2PeJtpAqL2r/aT@PwXnFDixr1IOIgWNY/ "Ruby – Try It Online") Takes input as an array of chars, returns a mixed array of chars/ints. (I'm still not sure whether this is allowed after reading the comments to the original post. If not allowed, it's +3 bytes to fix). ## Explanation First, we apply a `reduce` operation, where we aren't actually reducing anything, but rather reconstruct the array `a` as `[*x,*[...],y]`, where the middle part contains the numbers inserted at ground zero. We also make a copy of the array: `b=[*a]` to serve as a reference, so that we don't get confused which numbers are at the center of the explosion, and which ones are introduced later on. Then we iterate through `b` and for each element `x`, iterate through `a` to record, what effect `x` will have on each element `y` of `a`. Conveniently, `to_i` method returns 0 for non-numeric chars, so that we don't have to worry about distinction between numbers and text. In my initial code, arrays were indexed by `i` and `j`, but this was golfed down to use a "delta" value `d=i-j`. Another helper variable is the sign of the delta: `s=d<=>0`. At the first occurrence it performs the same function as `abs`, and at the second - it helps us to block the other side of one-sided explosions as in `12344321`. Ultimately, if `z` is estimated to be positive, we add it up with the integer equivalent of `y` and store in `a`, otherwise, `y` remains intact. [Answer] # [Perl 5](https://www.perl.org/), `-p` ~~110~~ 109 bytes Handling the even/odd rules waste around 20 bytes ``` #!/usr/bin/perl -p s#.#$p+=$.;$c{$p-$_}+=$-=$z-abs$_+$z%2/2for-25..($z=ord($')-ord$&);$&x($.=$z<2||$z%2+2)#eg;s##$c{+pos}||$&#eg ``` [Try it online!](https://tio.run/##FY3RjsIgEEXf@xUkjN02BDYh8any6m8YWrFbrQUBFVn99WWnTzPnZs5cZ/y8LSVQQcExBaKD4Rcch8MHiSvIXPcBDgzyRn7Lk/VcboVoICvrjw18tRwn1G0HdWpAoLCT7/d6zWRLzdgFSvElczZ8MK8xKt1mUA0aTvFVYQyWllCynxIJUUdDsIYsJkVikr662RTdD0dzGi/zdbHu5kO8P57plSvdr/H5MldIeuXBjD/Tucoe1@rPujjZJRTu/gE "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~351~~ 348 bytes ``` Z=zip R=range E=lambda o:R(o,0,-1) D=lambda d:[]if d<1else[[E(d),E(d+1)]]if d%2else[[E(d-1),[d]],[[],E(d)]] def f(s): s=sum(([c]+D(ord(n)+~ord(c))for c,n in Z(s,s[1:]+' ')),[]);l=len(s);v=[0]*l for i,c in enumerate(s): if len(c)>1: for j,d in list(Z(R(i-1,-1,-1),c[0]))+list(Z(R(i,l),c[1])):v[j]+=d print(*(d or c for c,d in Z(s,v)),sep='') ``` [Try it online!](https://tio.run/##RVDBcsIgFDyHr@DSCRh0THuLjSf9AY8yHGIgSiSEQkyrh/56@ojTdoYB3u6@ZR/uPlx6@zZNx/KhHTqUvrJnhfalqbqTrHBfHEjP1myZU7T7BWXBhW6wfM@VCYrzPZGUwZblVMzEy@sfAY2MSyEY5yJqQIGkanBDAi1QEspw6wjhtch2pPeSWJp9x7OmtOk9rpnF2uIjCSzwvBBZilMKjoJuTGmUBZfNWPK1WBiUxAbN6tig7K1TvhrU85kEUkV1Tbd5LGdpy2SUGh0GciQHopc5mxdlNThSmv1TzEQwB7AYeSuyUqLEeW0HsiASx6D4GVf@xh0hZlCuTFM66c71fsDhHlBUhajpKkfC4FceNu1YJFdhkNrGvE/rwHCKl1ucAjs7MZhLRkeYFQabqlMNf3m@ms727gOcbuPn1/2BqlOE26tBUFWxrtX5olv08HD9AQ "Python 3 – Try It Online") * −3 thanks to Kevin The function `f` takes one string as input and prints the result to standard output. ## Ungolfed ``` def range_downto_0(o): return range(o, 0, -1) def D(d): return ( [] if d >= 0 else [[range_downto_0(d), range_downto_0(d + 1)]] if d % 2 else [[range_downto_0(d - 1), [d]], [[], range_downto_0(d)]] ) def f(s): s = sum(([c] + D(ord(n) + ord(c) - 1) for c, n in zip(s, s[1:] + ' ')), []) v = [0] * len(s) for i, c in enumerate(s): if len(c) == 2: for j, d in itertools.chain( zip(range(i - 1, -1, -1), c[0])), zip(range(i, len(s)), c[1]) ): v[j] += d return ''.join(str(d) if d else c for c, d in zip(s, v)) ``` ## Explanation 1. Expand the string `s` to insert number range objects as placeholders for the "outward explosions". Save the result as a list `s`. 2. Create a list of zeros `v` with the same length as `s`. 3. Inspect `s` and, for every number range, add the numerical values to the value at their respective position in `v`. `v` now contains all the numbers that are going to be in the result at their correct positions. 4. Iterate over `s` and `v` simultaneously, take the entry from `v` if it is greater than 0 or the entry from `s` otherwise and print each chosen entry in order. The expensive repeated array concatenation in step 1 is at best in O(n2) but could be expressed in O(n) using a generator (assuming Python can construct lists from generators in O(n)). The remainder of this algorithm is in O(n ⋅ min{n, |Σ|} ⋅ log |Σ|) with Σ being the alphabet or, if you want to regard Σ as a constant, straight out O(n) (assuming that Python can join string generators in O(n)). “min{n, |Σ|}” comes from the outward range expansion and “log |Σ|” results from the conversion of numbers to strings. [Answer] # [C (gcc)](https://gcc.gnu.org/), 395 bytes ``` #include<stdlib.h> #include<stdio.h> f(char*s){char*S=s;while(*S++);const int l=S-s-1;int i=1,j=0,k,d,o,t[l*3],*v;for(;i<l;i++)(d=s[i]+~(t[j++]=s[i-1]))>0&&(t[j++]=-d,d%2||(t[j++]=0));l>0&&(t[j++]=s[l-1]);v=calloc(k=j,4);for(i=0;i<k;i++){if((d=-t[i])>0){d+=o=d%2;for(j=0;j<d&&j<=i;j++)v[i-j]+=d-j;i+=!o;for(j=o;j<d&&i+j<k;j++)v[i+j]+=d-j;}}for(i=0;i<k;i++){d=v[i];printf(d?"%d":"%c",d?d:t[i]);}} ``` [Try it online!](https://tio.run/##ZZBPc9sgEMXP1qegytgBgTp225MRyTmnHnxUdVDAskFEuAIrfxz3q6uLas94pif2Lb99b2dlvpNyHO90J@1RbQsflNXPX/cPyW1Lu9hpsNzXfebJaXo3wvPXvbZbnG0oJVy6zgeku4Cs2OQ@X/FYa7FiRixZyxRzLJQ2@16xbOCN6zHXheUaZrESvtQV/YNDaSitospXFSEPy8Xi2ssVU/Nvn59XvSSE21vAlzYO8UHI2loncSsM@0GmKC2WkNZOaSfdYEjMA0RCAjkpKpwA74mEZbkp1GJhCqE5GJMBljEVFSo3MC@@uAvn/nGaGjC@gPQKns//xSoBQMUPPdylweoxnat0nc5lytSjWk/bwNgYr/ZS6w7Hou53kqF4b5RBPZQVSU7JDLzR9K@RQCsOTzGhUEFSMgNkdslJn7rDMSC0Rvdzf/@r@3kMUYNMGZosYy7wDb5VwHicAp9GeU7O41g/S7Vtdq196dzhd@/DcXh9e/@Afmyb1o6g6qjldrfXZvzoofwL "C (gcc) – Try It Online") `f` takes input as a null-terminated character array and returns its result on standard output. ## Explanation This is my first C submission to Code Golf. The algorithm is the same as in my [Python submission](/a/158179/68800). ]
[Question] [ ## Your Task: You all know what a magic square is! But what about a magic cube? A magic cube is the 3D version of a magic square, and is a set of numbers in a cube, where the sums of every straight (not diagonal) line are equal. You must write a program or function that receives an integer, and returns the number of valid magic cubes made up of up to one of each integer between 1 and that integer (inclusive). ## Input: An integer. ## Output: The number of magic cubes you can make by using up to one of of each integer between 1 and the input. A cube with various rotations should only be counted once. ## Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte count wins. ## BOUNTY: I will award a 100 rep bounty to the first user that manages to do this in < 100 bytes without using built-ins designed specifically towards magic cubes or squares (looking at you Mathematica). [Answer] # Clingo, 220 + 2 = 222 bytes ``` 1{s(S):S=0..n,S**3==n}. A{a(0..n-1,A)}:-A=1..n. :-a(P,A-1),{a(P,A)}0,A<n. :-s(S),{a(P,A):P-P/K\S*K=Q-Q/K\S*K}>(S*n+S)/2,Q=0..n,K=(1;S;S*S). :-s(S),a(((0;1)+(0;S)+(0;S*S))*~-S,A),{a(0,A)}0. :-s(S),a((S;S*S)*~-S,A),{a(S-1,A)}0. ``` Run with `clingo magic-cubes.lp -n0 -cn=INPUT`. The answer will be printed next to `Models`. All newlines are optional and shown here for clarity but excluded from the byte count. I’m scoring +2 bytes for `-n0` (“count all models”). The last two lines ensure that only one rotated version of each cube is counted. The answers for 1, 8, 27 are quickly found to be 1, 0, 216; the rest are probably too hard. If you want to see the cubes in a more readable format, add `b((P\S,P/S\S,P/S/S),A):s(S),-a(P,A),not a(P,A-1). #show b/2.` ``` $ clingo magic-cubes.lp -n0 -cn=1 clingo version 5.1.0 Reading from magic-cubes.lp Solving... Answer: 1 a(0,1) s(1) SATISFIABLE Models : 1 Calls : 1 Time : 0.009s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s) CPU Time : 0.010s $ clingo magic-cubes.lp -n0 -cn=8 clingo version 5.1.0 Reading from magic-cubes.lp Solving... UNSATISFIABLE Models : 0 Calls : 1 Time : 0.010s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s) CPU Time : 0.000s $ clingo magic-cubes.lp -n0 -cn=27 clingo version 5.1.0 Reading from magic-cubes.lp Solving... Answer: 1 a(7,1) a(7,2) a(13,2) a(7,3) a(13,3) a(19,3) a(7,4) a(13,4) a(15,4) a(19,4) a(7,5) a(13,5) a(15,5) a(19,5) a(21,5) a(0,6) a(7,6) a(13,6) a(15,6) a(19,6) a(21,6) a(0,7) a(7,7) a(13,7) a(15,7) a(19,7) a(21,7) a(26,7) a(0,8) a(5,8) a(7,8) a(13,8) a(15,8) a(19,8) a(21,8) a(26,8) a(0,9) a(5,9) a(7,9) a(11,9) a(13,9) a(15,9) a(19,9) a(21,9) a(26,9) a(0,10) a(2,10) a(5,10) a(7,10) a(11,10) a(13,10) a(15,10) a(19,10) a(21,10) a(26,10) a(0,11) a(2,11) a(5,11) a(7,11) a(11,11) a(13,11) a(15,11) a(17,11) a(19,11) a(21,11) a(26,11) a(0,12) a(2,12) a(5,12) a(7,12) a(11,12) a(13,12) a(15,12) a(17,12) a(19,12) a(21,12) a(23,12) a(26,12) a(0,13) a(2,13) a(5,13) a(7,13) a(10,13) a(11,13) a(13,13) a(15,13) a(17,13) a(19,13) a(21,13) a(23,13) a(26,13) a(0,14) a(2,14) a(5,14) a(7,14) a(10,14) a(11,14) a(13,14) a(15,14) a(17,14) a(19,14) a(21,14) a(23,14) a(25,14) a(26,14) a(0,15) a(2,15) a(4,15) a(5,15) a(7,15) a(10,15) a(11,15) a(13,15) a(15,15) a(17,15) a(19,15) a(21,15) a(23,15) a(25,15) a(26,15) a(0,16) a(2,16) a(4,16) a(5,16) a(7,16) a(10,16) a(11,16) a(13,16) a(15,16) a(17,16) a(18,16) a(19,16) a(21,16) a(23,16) a(25,16) a(26,16) a(0,17) a(2,17) a(4,17) a(5,17) a(6,17) a(7,17) a(10,17) a(11,17) a(13,17) a(15,17) a(17,17) a(18,17) a(19,17) a(21,17) a(23,17) a(25,17) a(26,17) a(0,18) a(2,18) a(4,18) a(5,18) a(6,18) a(7,18) a(10,18) a(11,18) a(12,18) a(13,18) a(15,18) a(17,18) a(18,18) a(19,18) a(21,18) a(23,18) a(25,18) a(26,18) a(0,19) a(2,19) a(3,19) a(4,19) a(5,19) a(6,19) a(7,19) a(10,19) a(11,19) a(12,19) a(13,19) a(15,19) a(17,19) a(18,19) a(19,19) a(21,19) a(23,19) a(25,19) a(26,19) a(0,20) a(2,20) a(3,20) a(4,20) a(5,20) a(6,20) a(7,20) a(9,20) a(10,20) a(11,20) a(12,20) a(13,20) a(15,20) a(17,20) a(18,20) a(19,20) a(21,20) a(23,20) a(25,20) a(26,20) a(0,21) a(2,21) a(3,21) a(4,21) a(5,21) a(6,21) a(7,21) a(9,21) a(10,21) a(11,21) a(12,21) a(13,21) a(15,21) a(17,21) a(18,21) a(19,21) a(21,21) a(23,21) a(24,21) a(25,21) a(26,21) a(0,22) a(2,22) a(3,22) a(4,22) a(5,22) a(6,22) a(7,22) a(9,22) a(10,22) a(11,22) a(12,22) a(13,22) a(14,22) a(15,22) a(17,22) a(18,22) a(19,22) a(21,22) a(23,22) a(24,22) a(25,22) a(26,22) a(0,23) a(2,23) a(3,23) a(4,23) a(5,23) a(6,23) a(7,23) a(9,23) a(10,23) a(11,23) a(12,23) a(13,23) a(14,23) a(15,23) a(17,23) a(18,23) a(19,23) a(20,23) a(21,23) a(23,23) a(24,23) a(25,23) a(26,23) a(0,24) a(2,24) a(3,24) a(4,24) a(5,24) a(6,24) a(7,24) a(8,24) a(9,24) a(10,24) a(11,24) a(12,24) a(13,24) a(14,24) a(15,24) a(17,24) a(18,24) a(19,24) a(20,24) a(21,24) a(23,24) a(24,24) a(25,24) a(26,24) a(0,25) a(2,25) a(3,25) a(4,25) a(5,25) a(6,25) a(7,25) a(8,25) a(9,25) a(10,25) a(11,25) a(12,25) a(13,25) a(14,25) a(15,25) a(17,25) a(18,25) a(19,25) a(20,25) a(21,25) a(22,25) a(23,25) a(24,25) a(25,25) a(26,25) a(0,26) a(1,26) a(2,26) a(3,26) a(4,26) a(5,26) a(6,26) a(7,26) a(8,26) a(9,26) a(10,26) a(11,26) a(12,26) a(13,26) a(14,26) a(15,26) a(17,26) a(18,26) a(19,26) a(20,26) a(21,26) a(22,26) a(23,26) a(24,26) a(25,26) a(26,26) a(0,27) a(1,27) a(2,27) s(3) a(3,27) a(4,27) a(5,27) a(6,27) a(7,27) a(8,27) a(9,27) a(10,27) a(11,27) a(12,27) a(13,27) a(14,27) a(15,27) a(16,27) a(17,27) a(18,27) a(19,27) a(20,27) a(21,27) a(22,27) a(23,27) a(24,27) a(25,27) a(26,27) Answer: 2 […] Answer: 216 a(0,2) a(12,1) a(12,2) a(0,3) a(12,3) a(24,3) a(0,4) a(12,4) a(22,4) a(24,4) a(0,5) a(10,5) a(12,5) a(22,5) a(24,5) a(0,6) a(7,6) a(10,6) a(12,6) a(22,6) a(24,6) a(0,7) a(5,7) a(7,7) a(10,7) a(12,7) a(22,7) a(24,7) a(0,8) a(5,8) a(7,8) a(10,8) a(12,8) a(20,8) a(22,8) a(24,8) a(0,9) a(5,9) a(7,9) a(10,9) a(12,9) a(17,9) a(20,9) a(22,9) a(24,9) a(0,10) a(5,10) a(7,10) a(10,10) a(12,10) a(16,10) a(17,10) a(20,10) a(22,10) a(24,10) a(0,11) a(4,11) a(5,11) a(7,11) a(10,11) a(12,11) a(16,11) a(17,11) a(20,11) a(22,11) a(24,11) a(0,12) a(4,12) a(5,12) a(7,12) a(10,12) a(12,12) a(16,12) a(17,12) a(19,12) a(20,12) a(22,12) a(24,12) a(0,13) a(4,13) a(5,13) a(7,13) a(10,13) a(12,13) a(16,13) a(17,13) a(19,13) a(20,13) a(22,13) a(24,13) a(26,13) a(0,14) a(4,14) a(5,14) a(7,14) a(10,14) a(12,14) a(14,14) a(16,14) a(17,14) a(19,14) a(20,14) a(22,14) a(24,14) a(26,14) a(0,15) a(2,15) a(4,15) a(5,15) a(7,15) a(10,15) a(12,15) a(14,15) a(16,15) a(17,15) a(19,15) a(20,15) a(22,15) a(24,15) a(26,15) a(0,16) a(2,16) a(4,16) a(5,16) a(6,16) a(7,16) a(10,16) a(12,16) a(14,16) a(16,16) a(17,16) a(19,16) a(20,16) a(22,16) a(24,16) a(26,16) a(0,17) a(2,17) a(4,17) a(5,17) a(6,17) a(7,17) a(10,17) a(12,17) a(14,17) a(16,17) a(17,17) a(19,17) a(20,17) a(21,17) a(22,17) a(24,17) a(26,17) a(0,18) a(2,18) a(4,18) a(5,18) a(6,18) a(7,18) a(9,18) a(10,18) a(12,18) a(14,18) a(16,18) a(17,18) a(19,18) a(20,18) a(21,18) a(22,18) a(24,18) a(26,18) a(0,19) a(2,19) a(4,19) a(5,19) a(6,19) a(7,19) a(9,19) a(10,19) a(11,19) a(12,19) a(14,19) a(16,19) a(17,19) a(19,19) a(20,19) a(21,19) a(22,19) a(24,19) a(26,19) a(0,20) a(2,20) a(4,20) a(5,20) a(6,20) a(7,20) a(8,20) a(9,20) a(10,20) a(11,20) a(12,20) a(14,20) a(16,20) a(17,20) a(19,20) a(20,20) a(21,20) a(22,20) a(24,20) a(26,20) a(0,21) a(2,21) a(4,21) a(5,21) a(6,21) a(7,21) a(8,21) a(9,21) a(10,21) a(11,21) a(12,21) a(14,21) a(16,21) a(17,21) a(19,21) a(20,21) a(21,21) a(22,21) a(23,21) a(24,21) a(26,21) a(0,22) a(2,22) a(4,22) a(5,22) a(6,22) a(7,22) a(8,22) a(9,22) a(10,22) a(11,22) a(12,22) a(14,22) a(16,22) a(17,22) a(18,22) a(19,22) a(20,22) a(21,22) a(22,22) a(23,22) a(24,22) a(26,22) a(0,23) a(2,23) a(4,23) a(5,23) a(6,23) a(7,23) a(8,23) a(9,23) a(10,23) a(11,23) a(12,23) a(14,23) a(15,23) a(16,23) a(17,23) a(18,23) a(19,23) a(20,23) a(21,23) a(22,23) a(23,23) a(24,23) a(26,23) a(0,24) a(2,24) a(3,24) a(4,24) a(5,24) a(6,24) a(7,24) a(8,24) a(9,24) a(10,24) a(11,24) a(12,24) a(14,24) a(15,24) a(16,24) a(17,24) a(18,24) a(19,24) a(20,24) a(21,24) a(22,24) a(23,24) a(24,24) a(26,24) a(0,25) a(1,25) a(2,25) a(3,25) a(4,25) a(5,25) a(6,25) a(7,25) a(8,25) a(9,25) a(10,25) a(11,25) a(12,25) a(14,25) a(15,25) a(16,25) a(17,25) a(18,25) a(19,25) a(20,25) a(21,25) a(22,25) a(23,25) a(24,25) a(26,25) a(0,26) a(1,26) a(2,26) a(3,26) a(4,26) a(5,26) a(6,26) a(7,26) a(8,26) a(9,26) a(10,26) a(11,26) a(12,26) a(14,26) a(15,26) a(16,26) a(17,26) a(18,26) a(19,26) a(20,26) a(21,26) a(22,26) a(23,26) a(24,26) a(25,26) a(26,26) a(0,27) a(1,27) a(2,27) s(3) a(3,27) a(4,27) a(5,27) a(6,27) a(7,27) a(8,27) a(9,27) a(10,27) a(11,27) a(12,27) a(13,27) a(14,27) a(15,27) a(16,27) a(17,27) a(18,27) a(19,27) a(20,27) a(21,27) a(22,27) a(23,27) a(24,27) a(25,27) a(26,27) SATISFIABLE Models : 216 Calls : 1 Time : 6.101s (Solving: 6.07s 1st Model: 1.03s Unsat: 0.37s) CPU Time : 6.090s ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 275 bytes ``` n=gets.to_i;p (2.upto(n**(1/3r)).map{|i|(1..n).to_a.permutation(i**3).map{|x|c=eval'x'+".each_slice(#{i}).to_a"*2;[c,c.map(&:transpose),c.transpose.map(&:transpose)].map{|q|q.map{|a|a.map{|b|b.inject(:+)}}.flatten.uniq.length}.inject(:+)==3?1:0}}+[0]).flatten.inject(:+)/48+n ``` [Try it online!](https://tio.run/##Zcxha8JADAbgvzIczLvriLbdh1Ep@yEikh5RT2p6bdPh8O63d5MOFfz2JnnedEP1M45c7kl6kGbrVv5FZTB4aRQbo9JF3mkNJ/SX4IJKAVhfHYKn7jQIimtYOWPyf3QOtqRvrOfneTIDQnvY9rWzpF4vLk7VmclWa/turwX1VkiH3PumJ/23ug1Px830vw3tFDDgFKpQgeMjWVFFomOEXY0ixDCwa6Em3sshPoiyzL/SYhljsl5u9E3fweLjM@FxzH4B "Ruby – Try It Online") In theory, this works. In practice, since it creates every permutation of the list of possible numbers, it'll take hopelessly large amounts of time and memory for any input more than 13 or so. I haven't taken the time to test it past 12, but it seems no 2×2×2 magic cubes exist for that range, so all it really does is tell you how many 1×1×1 cubes you can make. I "golfed" it a bit (really just made it hard to read for minimal size reduction returns). I'm sure the size can be reduced quite a bit, though getting it under 100 characters is a pretty tall order. Ruby 2.4 added `.sum`, but TIO doesn't support it yet, so this has a few `.inject(:+)`s. I'll add a non-golfed version + explanation if requested. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 36 bytes ``` ;Z;Z€ẎS€E *3³œcŒ!€Ẏs€s€¹Ç€S Ç€ḊS÷24+ ``` [Try it online!](https://tio.run/##y0rNyan8/986yjrqUdOah7v6goGUK5eW8aHNRycnH52kCBEtBlIgfGjn4XYgFcwFph7u6Ao@vN3IRPv///8WAA "Jelly – Try It Online") As you expect, it's terribly slow. ## Explanation * Link 1: Given a cube, check if it's valid. ``` ;Z;Z€ẎS€E Input: N = [ [ [a,b], [ [e,f], [c,d] ], [g,h] ] ] ;Z Concatenate with zip of N. The zip (transpose) of N is [ [ [a,b], [ [c,d], [e,f] ], [g,h] ] ] (by treating each 2-element block as an unit and transpose the large table) ;Z€ Concatenate with plane-wise zip of N, that is [ [ [a,c], [ [e,g], [b,d] ], [f,h] ] ] (transpose each 2x2 block) The current value is: [ [ [a,b], [ [e,f], [ [a,b], [ [c,d], [ [a,c], [ [e,g], [c,d] ], [g,h] ], [e,f] ], [g,h] ], [b,d] ], [f,h] ] ] Ẏ Tighten, concatenate all elements inside, similar to `;/`. Get [ [a,b], [c,d], [e,f], [g,h], [a,b], [e,f], [c,d], [g,h], [a,c], [b,d], [e,g], [f,h] ] S€ Sum each sublist. `ZS` also works. E All **E**qual? `1` if all elements are equal, `0` otherwise. ``` * Link 2: Given a side length `x`, generate all cubes with that side length and calculate number of valid cubes. ``` *3³œcŒ!€Ẏs€s€¹Ç€S Given: `x` (side length). *3 Calculate *x³*. ³ First commandline argument. (**n**) œc Generate all subsets of the range `[1..n]` having length *x³*. Œ!€Ẏ All permutation of each and tighten. (the current value is a list of all ways to choose an ordered tuple of *x³* elements from `[1..n]`) s€s€ Split each twice into slices of length `x`. On a list of (list of *x³* integers), this format each sublist into a cube. ¹ Do nothing. Because Jelly is a tacit programming language without this the program will behave differently. Ç€ Apply last link for **€**ach. S **S**um. ``` * Link 3 (main link): For all side lengths from `1` to `n`, calculate number of cubes (rotations are counted multiple times) for each side length, dequeue and sum it (so we get the sum of number of cubes with side length `>= 2`), divide by `24` (to avoid duplication of cubes) and add the number of side length 1 cube (input). ``` Ç Apply last link... € for **€**ach element from `1` to `n`. Ḋ **Ḋ**equeue, dispose the result for value 1. S÷24 **S**um and divide by 24. + Add the input (number of cubes with side length 1) ``` ]
[Question] [ Your task is to write a program that, given a number *n*, returns a list of all valid, halting [Smallfuck](https://esolangs.org/wiki/Smallfuck) programs of length *n*, in any order. Actually, we're using a variation of Smallfuck called [F2](https://esolangs.org/wiki/Fm), which is just Smallfuck with a right-unbounded tape. For the purposes of this challenge, a program that moves left from the start of the tape is considered invalid, as is one with unbalanced brackets. ## Scoring Since solving this for every *n* is impossible (as it would require you to solve the [halting problem](https://en.wikipedia.org/wiki/Halting_problem)), your submission's score will be the lowest *n* for which it returns an incorrect answer. Each submission must be, at most, 1000 bytes (though you are encouraged to provide an ungolfed version as well). In the event of a tie, the earlier answer wins. ## Test Cases *n* = 1: ``` + > ``` *n* = 2: ``` ++ +> >+ >< >> [] ``` *n* = 3: ``` +++ ++> +>+ +>< +>> >++ >+< >+> ><+ ><> >>+ >>< >>> >[] [+] [<] [>] []+ []> ``` *n* = 4: ``` ++++ +++> ++>+ ++>< ++>> +>++ +>+< +>+> +><+ +><> +>>+ +>>< +>>> >+++ >++< >++> >+<+ >+<> >+>+ >+>< >+>> ><++ ><+> ><>+ ><>< ><>> >>++ >>+< >>+> >><+ >><< >><> >>>+ >>>< >>>> [][] ++[] +>[] ><[] >>[] [++] [+<] [+>] [<+] [<<] [<>] [>+] [><] [>>] []++ []+> []>+ []>< []>> +[+] +[>] >[+] >[<] >[>] >[]+ >[]< >[]> [+]+ [+]> [<]+ [<]> [>]+ [>]> [[]] ``` Please inform me if there are any more that I have forgotten to add. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), Score: ??? This clocks in at 980 bytes, since I had so much to work with I decided to make it a little more readable. Basically I'm generating all the possible programs for length n and iterating them n^x times for some x. x is currently 3 but it can be modified arbitrarily to any size, limited only by the limitation of the JVM's precission. This will work for arbitrarily large input values if x is increased, but I have it set to 3 for tio. ``` import java.util.*; public class Main{ public static void main(String[] args){ int i = new Scanner(System.in).nextInt(); int x = 3; l:for(int j=0;j<Math.pow(5, i);j++){ try { String s=""; for(int k=j;s.length()<i;k/=5) s="+<>][".charAt(k%5)+s; Stack<Integer>y=new Stack<Integer>(); Map<Integer,Integer>f=new HashMap<>(),b=new HashMap<>(); for(int m=0; m<s.length();m++){ char c=s.charAt(m); if(c=='[')y.push(m); if(c==']'){int n=y.pop();f.put(n, m);b.put(m, n);} } if(y.size()>0) continue; boolean[] t= new boolean[s.length()]; int l=0,n=0; for(long m=0;l<s.length()&m<Math.pow(i,x);l++,m++){ switch(s.charAt(l)){ case'+':t[n]=!t[n];break; case'>':n++;break; case'<':n--; if(n < 0)continue l;break; case'[':if(!t[n])l=f.get(l);break; case']':l=b.get(l)-1;break; } } if(l>=s.length()){ System.out.println(s); } } catch(Exception e){continue;} } } } ``` [Try it online!](https://tio.run/##ZVNNj5swED2TX@FGarELoanaXGIcqYdK7WFPOUYcDOsEgxkj7Gw2jfLbU/OVj80BY715M/PeDBT8jc90LaB4LS8XWdW6sahwYLS3UkVf6aTep0pmKFPcGPTCJZwm3oAZy617vWn5iioXwWvbSNhtEsSbnSGO6EmwSCKGQBzQOuMAosHro7GiiiSQCMS7/QsWE@q4arnVDW4zCjanRfzCbR7V@oAXIZKEFkHQlfRsc0Tdxev7IcOmU9oBY4GSFdRESsDO5pjEkpbf2IJ0FM@xg3iVbKZRlvPml8Xl5wUJDB0q8qyMnSSxE83qyDrdD1iv1fNeeD1i4Rjbdvw/3ORt1FHD9CPyqLNyRlEV36TSanTpea08lDEz6qyGZE9uccaYv/HJMar3Jn@KJD45teWBOYKuXdmtI1oMIXLUtLtXIQJCz11ef7rkY2TkP4HJaj4MK9NgJexFXz/VWgkObsG2X@kI3AwkPbPtrtg8BGfw6lhpt6zWsrpz/KW6LVqGPwhVQRDeTcEcpM1yfJ2CItf5cCP8wF/aDSTsU3vStBG8pHfhlb@EIHjGY4fPZhQ5z4BiNCejUaSeyRt/6XhdB6LYNtqJVsYzL/GXiqVDePb9gfBh0GrFbiMYDQ0/ht7bqHYftlWAzbDZLvGMMt7O4vd7JmorNSBBTtcNtRT3nCfny@Xnfw "Java (OpenJDK 8) – Try It Online") [Answer] # Braingolf, Score: 3 ``` 1-?"++ +> >+ >< >> []":"+ >"|&@ ``` Start things off nice and easy, hardcodes the correct answer for 1 and 2, outputs `+ >` if n = 1, and `++ +> >+ >< >> []` otherwise ]
[Question] [ Your task is to write a function which outputs a ukulele chord chart in the following format for a given chord symbol. For instance, for input "`G7`", it must output: ``` G C E A --------- | | |#| | --------- | |#| |#| --------- | | | | | --------- | | | | | --------- | | | | | --------- ``` > > It must support all chords of these forms: **X Xm X7 Xm7 Xmaj7 Xsus4 Xdim Xdim7** > > > where X is any of **A A# B C C# D D# E F F# G G#** > > > (Supporting flats, such as Bb and Eb, is not required.) The rest of the challenge description (until "Output and scoring") is purely explanatory: if you know ukulele chords already, you don't need it. There are three steps parts to producing the chart for a chord. 1. First, work out which notes are in the chord. 2. Choose the correct fret for each string to match the notes. 3. Draw the chart. ## Work out which notes are in the chord There are 12 **notes** in the cyclical music scale, each a **semitone** apart: `A, A#, B, C, C#, D, D#, E, F, F#, G, G#`, then A, A#.... *(If you're not into music, just mentally translate every "`A`" into a `0`, every "`A#`" into a `1`, etc, and everything will work out just fine.)* A **chord** is a set of 3 or 4 notes, according to a defined pattern of intervals starting from the **base note**: * `X`: 0 + 4 + 3 ("major"). *Example: C, C+E+G* * `Xm`: 0 + 3 + 4 ("minor"). *Example: Cm, C+D#+G* * `X7`: 0 + 4 + 3 + 3 ("seven"). *Example: C7, C+E+G+A#* * `Xm7`: 0 + 3 + 4 + 3 ("minor seven"). *Example: Cm7, C+D#+G+A#* * `Xmaj7`: 0 + 4 + 3 + 4 ("major seven") . *Example: Cmaj7, C+E+G+B* * `Xsus4`: 0 + 5 + 2 ("sus four"): *Example: Csus4, C+F+G* * `Xdim`: 0 + 3 + 3 ("diminished"). *Example: Cdim, C+D#+F#* * `Xdim7`: 0 + 3 + 3 + 3 ("diminished seven"). *Example: C+D#+F#+A#. [You may find it helpful to know that this is the same chord as A#dim7, D#dim7 and F#dim7].* (The name in parentheses is just for your music education, it's not relevant to the challenge.) For instance: "`Am`" is a chord, where "A" is the base note, and "m" is the chord type. Looking up the table ("Xm: 0 + 3 + 4"), we see it has 3 notes: * the base note (`A`), * the note 3 semitones above (`C`, counting `A#` and `B`), and * the note 4 semitones above that (`E`). (Chords that have 3 notes will by necessity be repeating one of the notes across the 4 strings. That's fine.) ## Choose the correct frets for the notes Ukulele is an instrument with four **strings**, that play the notes G, C, E and A. Pressing the string against a **fret** makes it sound higher, one semitone per fret. (Pressing fret 1 on the A string turns it to A#, fret 2 turns it to B, etc). ### Chord charts The chord chart represents the first few frets, played by the left hand, read from top to bottom ("higher" frets are lower down the page). The **strings** are the columns separated by **`|`** symbols. The **frets** are the rows separated by **`-`** symbols. The symbol **`#`** means that the string is pressed against that fret ("is fretted"), while the right hand strums. So in the chord chart at the start: * The G string is not fretted (it is "open"), so it sounds like G. * The C string is fretted on fret 2 (two semitones up), so it sounds like D. * The E string is on fret 1 (one semitone up), and sounds like F. * The A string is on fret 2, so sounds like B. So this chord has notes: G, D, F, B. (It's G7, G+B+D+F - the order of the pitches doesn't matter.) ### Calculating chords To calculate which fret to play for a given string, for a given chord: * if the string's base note (G, E, A or C) is not already in the chord, play the lowest fret that belongs to the chord * repeat for each of the four strings. ### Example #1 For instance, let's play `E7` (consisting of `E` + `G#` + `B` + `D`). 1. The `G` string is not in the chord. Raise it to `G#` (fret 1). 2. The `C` string is not in the chord. Raise it to `D` (fret 2). 3. The `E` string is in the chord. Don't fret it. (Leave the string open.) 4. The `A` string is not in the chord. Raise it to `B` (fret 2). So we are playing: `G#`, `D`, `E`, `B`. So we output: ``` G C E A --------- |#| | | | --------- | |#| |#| --------- | | | | | --------- | | | | | --------- | | | | | --------- ``` ### Example #2 Another example: `G#` (consisting of `G#` + `B#` + `D#`): 1. The `G` string is not in the chord, raise it to `G#` (fret 1). 2. The `C` string is in the chord (B#), don't fret it. 3. The `E` string is not in the chord, raise it to `G#` (fret 4). 4. The `A` string is not in the chord, raise it to `B#`(C) (fret 3) So we are playing `G#`, `C`, `G#`, `C` ``` G C E A --------- |#| | | | --------- | | | | | --------- | | | |#| --------- | | |#| | --------- | | | | | --------- ``` (You may notice that sometimes not every note in the chord ends up getting played. Don't worry about it. "Proper" ukulele chords are slightly more complicated than this basic algorithm.) ## Output and scoring Your output must closely match the above. (You can use other characters instead of `|`, `-` and `#`, such as em-dashes or ASCII line-drawing characters, if they are visually superior. An unfilled circle character would be better than `#`). Trailing linespace on each line is ok. Whitespace before the first line or after the last line is not ok. Final linefeed is optional. Normal forms of input and output. You will receive one chord name, guaranteed to be in the table above, in the correct case. Standard loopholes disallowed. Online services are disallowed. If your language has music functions in its standard library, you may use them (but not if they're plugins, packages, etc.) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Lowest score (in bytes) wins. ## Extra credit This simple algorithm sometimes produces useless chord fingerings that don't include all the important notes of the chord. (For instance, for `Dm`, it produces `ACFA`, the same as `Fm`.) For extra credit, modify the algorithm so that: * For all chords, the root and third (first two notes, usually 0 and 3 or 0 and 4) are played on at least one string each. * For 4-note chords (X7, Xm7, Xmaj7, Xdim7), the root, third and seventh (first, second and fourth notes) are played on at least one string each. [Answer] ## Javascript 280 ~~282~~ ~~287~~ bytes (Non-meaningful linebreaks inserted for readability) ``` f= a=>' G C E A'+[1,2,3,4,5].map(y=> (l=` --------- `)+[-2,3,7,0].map( x=>(z=a.match(/(.#?)(.*)/), [...'9'+{'':14,7:147,m:40,m7:740,maj7:148,sus4:24,dim:30,dim7:360}[z[2]]] .map(i=>(i-x+'D EF G A BC'.search(z[1][0])+!!z[1][1]+8)%12) .sort((a,b)=>a-b)[0]-y?'| ':'|#' )).join``+'|').join``+l document.getElementById("mysubmit").onclick=function() { document.getElementById("out").innerHTML=f(document.getElementById("myinput").value) } ``` ``` <input type="text" value="G7" id="myinput"> <input type="submit" id="mysubmit"> <pre id="out"></pre> ``` ## Commentary I've never been so happy at Javascript's weird type conversions. This is probably the first time I've ever wanted 40 + 9 to equal 409 :) It's also really fortunate that integers are acceptable as keys in Objects. There's nothing too clever going on here. I subtract 3 from each chord note in order to keep the range within 0-9, so that I can temporarily express a chord as a 3-digit number. Luckily, the order of notes isn't important, so we can express 036 as 360. [Answer] # [Python 2](https://docs.python.org/2/), 518, 448 bytes Thanks to Wheat Wizard for the coding suggestions! ``` S='GCEA' N=['A','A#','B','C','C#','D','D#','E','F','F#','G','G#'] C={'':(0,4,7),'m':(0,3,7),'7':(0,4,7,10),'m7':(0,3,7,10),'maj7':(0,4,7,11),'sus4':(0,5,7),'dim':(0,3,6),'dim7':(0,3,6,9)} x=raw_input() j=1+('#'in x) c=[] for s in S:c.append(min((N.index(i)-N.index(s))%12for i in [N[(a+N.index(x[:j]))%12]for a in C[x[j:]]])) print' '+''.join(a+' 'for a in S) for f in range(5):f=['|o'if i==f+1else'| 'for i in c];print'-'*9,'\n',''.join(f)+'|' ``` [Try it online!](https://tio.run/##TVDLTsMwELz7KyJVaG3iVk2fapAPIZTeeunRWMhqE3BEnShpRRDl24PXbRCHsWZmZ9errb5O76WddN1OwCZdJxCQrZCQAIdk4J5HhxSB4gmBZO3wjECxQQxAkVR8A8R0zGd8yTgcPZ96vux9Ho2xtOxrN62Lf4nIOc25mXln7vsPpp@2uKp@wIKv2A9pRa0/X42tzifKSCGikMIAjA1aRvZCKpKXddAEztjF@5Guqswe6NFYSrcjYw9ZSw0b9rRh7C6aYIfBDrmVVId9sZVxoXxAYUJjIpWtLGKlnE@q2tgTBBACjIrS/aBDp/6iO@ZXyZHX2r5ldM7i3B38UoJxrhB5GGUfTQaXa5dfYa8ernOHcL/i8GLdxW/jcxbCBQghXZfgFX8B "Python 2 – Try It Online") ## Sample Output ``` G G C E A --------- | | | | | --------- | |o| |o| --------- | | |o| | --------- | | | | | --------- | | | | | ``` ## Commentary Thanks for a fun challenge. My daughter and I are off to buy a uke this weekend. I've never played the uke, but I play mandolin, and the theory is similar. For this submission (my first), I addressed the original challenge without the extra credit components. I fear addressing the extra credit questions will add a lot of of bytes to the code. I hope to submit again with the extra credit bits, time permitting. The logic is pretty simple if you trace your way back through the successive functions: 1. Parse the chord description. 2. Identify what notes are in that chord. 3. Figure out what frets on each string would fit 4. Assemble a chord by selecting the lowest fret that works on each string 5. Print out the chart fret by fret. The core of the golfed code lies in the gnarly mess of nested list comprehensions in the eighth -- now seventh -- line of the code. The best way I can explain what's going on is by presenting the ungolfed version. (Wheat Wizard suggested a shift from list comprehensions to generators that was not reflected in this ungolfed code) ``` STRINGS = 'GCEA' # Ukelele #STRINGS = 'GDAE' # Mandolin NOTES=['A','A#','B','C','C#','D','D#','E','F','F#','G','G#'] TYPES = {'':(0,4,7), 'm':(0,3,7), '7':(0,4,7,10), 'm7':(0,3,7,10 ), 'maj7':(0,4,7,11), 'sus4':(0,5,7), 'dim':(0,3,6), 'dim7':(0,3,6,9)} def parse(x): # parses the chord into the root and the chord type i=2 if '#' in x else 1 return x[:i],x[i:] def strng(string,notes): # Return a list of possible fret locations based on notes in a chord # This will return all possible fret locations, including those # beyond the fifth fret, where this code stops drawing. return sorted([(NOTES.index(i)-NOTES.index(string))%12 for i in notes]) def chordnotes(note,typ): #return the list of Notes that belong to the chord return [NOTES[(a+NOTES.index(note))%12] for a in TYPES[typ]] def chord((note,typ)): # Returns a list of four fret locations, in order of the strings. # This is the heart of the musical logic of the code. Here I use a naive # approach, and simply grab the lowest note on each string that fits the # chord. This function needs to be rewritten to address the extra # credit parts of the challenge. # The extra parentheses in the function declaration allow us to pass in # the results of the parse function directly. x = [] for s in STRINGS: x.append(min(strng(s,chordnotes(note,typ)))) return x def printchart(x): # Do the heavy lifting of formatting the output # I calculate the layout of each fret, and print them in turn. ch = chord(parse(x)) print ' '+''.join([a+ ' ' for a in STRINGS]) fret = '-'*9 for f in range(5): note = ['|o' if i==f+1 else '| ' for i in ch] print fret + '\n' + ''.join(note)+'|' def main(): x = raw_input('Chord?') printchart(x) if __name__ == '__main__': main() ``` ]
[Question] [ Your task is to create a program/function to replicate [this word generator](http://www.zompist.com/gen.html). # Details Your program/function take two input. One input is the `categories`. The other input is the `syllable types`. ### Categories `categories` will consist of classes of letters. For example, `V=aeiou` means that the letters `a`, `e`, `i`, `o`, and `u` will be classified under the category `V`. * Each category will have a 1-letter name in **UPPERCASE**. * The letters it contains will all be in **lowercase**. ### Syllable types For example `CV` would mean that the syllable will consist of a letter in category `C` and then a letter in category `V`. For example, if `C=bcd` and `V=ae`, then the syllable can be `ba`, `be`, `ca`, `ce`, `da`, or `de`. ### Your task Your task is to generate 100 random words, each with a random length of 1-5 syllables, each chosen randomly in the syllable types, with the letter in each category chosen also randomly. # Specs * Any reasonable input/output format. I don't care how you input the list. * All inputs will be valid. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest solution in bytes wins. # Testcase ``` input1 input2 output "C=st;V=aeiou" "CV/CVC" tasiti tese tossi tesis titi sese saset su sosastesisat sisosis sissa sata to sisas sese satetot sisuta tatote sa tetsesuti sossut ti seso tese tostutsasussi tutiset sasates tasa ta sa satso tastitta tetti sesita setetat tatsi tisetot sassu sessiso satessase sas ses totasta si tetsit titse sase totas sa ta sasesa tasa sostat sesi sissa tato tos tate sustosussatta sustas sassatote tesas sutat tatetatossos testisot tatta tissisisa sasese sesatus tito sisa satas sasisi so sasatustu sosses tetsa tese sestit sestu tisot sutastot sesu tet sotte sisute setotitsesi tita ``` [Answer] # Ruby, 80 bytes gotta go fast Input is a dictionary hash (for example, `{'C' => ['b', 'c'], 'V' => ['a', 'e']}`) and a list of syllable structures (for example, `['CV', 'VC']` or `%w{CV VC}`. ``` ->c,s{100.times{puts (0..rand(5)).map{s.sample}.join.gsub(/./){|e|c[e].sample}}} ``` For sample input: ``` c = { 'C' => %w{r s t l n}, 'V' => %w{a e i o u} } s = %w{CV CVC} ``` This produces a sample output: ``` salsun lonlutunonnus solitlaton rusitar lotol ris relussetsa tanotte nasun sur lusin tuslu nerunol sorrelussenu ni nanro nulila ritlalatiso nururlontensa lilas tatsisuto lel rerlisletnut ler netlo sorora surot tilsasotisi rilnolrati lasrare totni surreratlaral li tullatilro rusenoreto lulnunen nortille tut sanitare soniserloras tiritrattitsis ratretrate tesne lastinsolta sinirsitur lulesuleno li sirurata nutesnisitur rulunna natneretasi lonre les laruletan nitis tarletu tonrora la senru seltotoniles teransotutel re lulsirnilletus nunanurlon nunlortotsonna nolun tolso nas leltirninara neltinlesla lulutsisot lesulusutnis nolu nun tituntillini ralteres sasnirosse tutorlari nonlelletottan lirsetutit so le setse susritterlilu lorrirotri linuritlilrat rernilnelnutel sulolletrolo nisatellilru tulene tetnan lisotoslersor nerlani ne tunoletso nonlontaroltun rirrostarset sotlonsiro net sutona ``` [Answer] # Pyth - 18 bytes Takes input as a dict and then one structure per line. ``` [[email protected]](/cdn-cgi/l/email-protection) ``` [Try it online here](http://pyth.herokuapp.com/?code=V100ssmmO%40QkO.zhO5&input=%7B%22C%22%3A%22st%22%2C+%22V%22%3A%22aeiou%22%7D%0ACV%0ACVC&debug=1). [Answer] # [Python 3](https://docs.python.org/3/), 117 bytes (Also works in Python 2.) ``` lambda C,T:[J(J(R(C[t])for t in R(T))for j in[0]*randint(1,5))for i in[0]*100] from random import* R=choice J="".join ``` The lambda function takes the categories `C` as a dictionary and the syllable types `T` as a list of strings. It returns a list of 100 words. [Try it online!](https://tio.run/##LY4/C4MwEMV3P8VxUxQpWugiOLmJOIi4pA7WPzRWk5CmlFL62W1iXO5@79097uRH3wU/b1N63ZZuvQ0dZGGd0JzkpCIZ1a0/CQUaGIeK1P6uZqNo1Aaq4wPjmsThxQ3YMYijqPUmJVawK6axVQqlA69K@7tg/ejlKeJpFoxvNvcWarAXJvLFDBOU@vHEELA0vHJLhaFFWWoMdSMTL/yFQDFrrOlqsdfycApnlU6VLtv6iQcglX3bXvW3Pw "Python 3 – Try It Online") ### Ungolfed ``` import random def wordlist(categories, types): return [ "".join( "".join( random.choice(categories[t]) for t in random.choice(types)) for j in range(random.randint(1, 5))) for i in range(100)] ``` [Answer] # JavaScript (ES6), 136 bytes ``` document.write("<pre>"+( c=>s=>eval("for(r=Math.random,i=100,o=``;i--;o+=` `)for(j=r()*5;j-->0;)for(t=s[r(k=0)*s.length|0];l=t[k++];)o+=c[l][r()*c[l].length|0]") )({ C: "st", V: "aeiou" })([ "CV", "CVC" ])) ``` Takes an object for the categories and an array for the syllable types. [Answer] ## JavaScript (ES6), 134 bytes ``` (c,s,r=s=>s[Math.random()*s.length|0],t="01234")=>[...Array(100)].map(_=>t.slice(r(t)).replace(/./g,_=>r(s)).replace(/./g,s=>r(c[s]))) ``` Explanation: ``` (c,s, // Parameters r=s=>s[Math.random()*s.length|0], // Select random character t="01234" // Number of syllables to skip )=>[...Array(100)].map(_=> // Generate 100 words t.slice(r(t)) // Skip random number of syllables .replace(/./g,_=>r(s)) // Select syllables randomly .replace(/./g,s=>r(c[s]))) // Select letters randomly ``` [Answer] ## Haskell, 95 bytes ``` import Test.QuickCheck e=elements c#s=mapM putStr=<<(generate$resize 5$listOf1$e s>>=mapM(e.c)) ``` The categories are passed as a function from `Char` to `String` and the syllables types as a list of strings, e.g. ``` cat 'C' = "st" cat 'V' = "aeiou" syl = ["CV","CVC"] ``` Usage example: `cat # syl` -> `tesat`. Or with function/list literals: `(\c->case c of 'C' -> "st"; 'V' -> "aeiou") # ["CV","CVC"]`. Note: the function prints the generated word to stdout. If you try this within ghci, the return value is also printed, but that's a feature of the REPL and not of my code. Dealing with random values in a purely functional language like Haskell is usually awkward. Luckily `Test.QuickCheck` provides some random generators and combinators for them that hide all the nastiness in a monad. How it works: ``` input: s: list of syllable types c: categories as a function from Char to String e s -- pick a random syllable type from s >>=mapM(e.c) -- for each letter: apply c and pick a random letter from the returned string. We now have a random generator for a single syllable listOf1 -- make a list of syllables of random length with a minimum of 1 resize 5 -- limit the maximum size to 5 (the list is not simply cut if it is too long, all lengths are equally likely generate -- run the generator. We now have a list of 1 to 5 syllables mapM putStr=<< -- print the syllables. ``` I'm happy that it works at all, maybe there's room for improvement. Some more examples: ``` *Main> mapM_ (\_ -> do (cat#syl) ; putStrLn "" ) [1..10] sisatassetto se ti taso sittos tuttuste tottu satutustittes sutetsetusut tattatosote ``` [Answer] # Python 3.5, 227 223 210 206 201 bytes: ``` def k(u,*p): import itertools as i,random as r;y=[] for z in p:y+=[''.join(i)for i in i.product(*[u[i]for o in z for i in o])] for q in'1'*100:print(''.join([r.choice(y)for i in'1'*r.randint(1,5)])) ``` Takes the categories in as a Python dictionary (e.g `{'C':'hello','K':'hoop'}`) and the syllable types in as normal strings, with each separated by a comma (e.g. `'CK','CKC'`). Output is in the form of 100 lines, with 1 word per line. Will add detailed explanation later. [Try it online! (repl.it)](https://repl.it/CLww/3) ]
[Question] [ ## The Scenario You are given a matrix of size m x n (width x height) with m\*n spots where there are a few obstacles. Spots with obstacles are marked as 1, and those without are marked as 0. You can move vertically or horizontally, but can visit each spot only once. The goal is to cover as much area/spots as possible, avoiding obstacles. ## Input A 2D Matrix consisting of 0s and 1s and the coordinates of starting point. Example Matrix1: ``` 0(0,0) 1(0,1) 0(0,2) 0(1,0) 0(1,1) 0(1,2) 1(2,0) 0(2,1) 0(2,2) ``` Example Matrix2: ``` 0(0,0) 0(0,1) 1(0,2) 0(0,3) 0(0,4) 0(1,0) 1(1,1) 0(1,2) 0(1,3) 0(1,4) 0(2,0) 0(2,1) 0(2,2) 1(2,3) 0(2,4) 0(3,0) 1(3,1) 0(3,2) 0(3,3) 0(3,4) 0(4,0) 0(4,1) 1(4,2) 0(4,3) 0(4,4) ``` The coordinates shown above, next to matrix elements is for explanation only. They are nothing but array indices. Actual input would just be the matrix. for example1 the input is just, ``` 0 1 0 0 0 0 1 0 0 ``` Input for example2, ``` 0 0 1 0 0 0 1 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 ``` Starting Point (0,0). ## Output Output should be a line containing comma separated *moves*. A *move* is a space separated direction (n,s,e,w) and number of units of movement in the direction (range 1-1000). Example output for the matrix in example1 would be, ``` s 1,e 1,s 1,e 1,n 2 (0,0) --> (1,0) --> (1,1) --> (2,1) --> (2,2) --> (1,2) --> (0,2) ``` and for the matrix in example2 would be, ``` s 2,e 2,n 1,e 1,n 1,e 1,s 4,w 1,n 1,w 1 (0,0) --> (1,0) --> (2,0) --> (2,1) --> (2,2) --> (1,2) --> (1,3) --> (0,3) --> (0,4) --> (1,4) --> (2,4) --> (3,4) --> (4,4) --> (4,3) --> (3,3) --> (3,2) ``` which is the longest path, visiting each coordinate only once and avoiding those coordinates with obstacles. ## Objective Winning Criteria Should compute the distance efficiently(efficient: performance wise, fast program basically) for huge matrices (Of order say, 500x500). One which computes the fastest wins (All submissions run on my machine, for fairness). No restrictions on number of bytes! Here is a 20x20 matrix which can be used to get some idea of the performace, for tuning purposes. ``` 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 1 0 1 0 0 0 ``` [Answer] ## Python 3, `2619 bytes` (90 [LOC](https://en.wikipedia.org/wiki/Source_lines_of_code)), ~6 seconds (20x20)   ``` #!/usr/bin/env python import networkx as nx class input(object): def __init__(self,world_string): rows=world_string.split("\n") column_count=len(rows[0]) blocked_cells=[] x=0 y=-1 for row in rows: if len(row)>column_count: column_count=len(row) y+=1 for column in row: if column=='1': blocked_cells.append((y,x)) x+=1 x=0 self.matrix=world(len(rows),column_count) self.block_graph(blocked_cells) self.matrix.add_sink() def block_graph(self,block_list): for cell in block_list: self.matrix.block_cell(cell) class world(object): SINK="END" def __init__(self, rows=3, columns=3): self.graph=nx.grid_2d_graph(rows, columns) for e in self.graph.edges(): self.graph[e[0]][e[1]]["weight"]=-1.0 def block_cell(self,node): neighbours=list(self.graph[node].keys()) for linked_node in neighbours: self.graph.remove_edge(node,linked_node) def add_sink(self): matrix=self.graph.nodes()[:] self.graph.add_node(world.SINK) for source_cell in matrix: self.graph.add_edge(source_cell, world.SINK, weight=1.0) class algorithm(object): SOURCE=(0,0) def find_path(graph): def _heuristic(current, target): if current==target:return 0.0 cost=nx.astar_path(graph, algorithm.SOURCE,current,lambda x,y:1) return -1 * len(cost) path=nx.astar_path(graph, algorithm.SOURCE, world.SINK, _heuristic) return path[:-1] class output(object): directions={ ( 1, 0) : "n", (-1, 0) : "s", ( 0, 1) : "w", ( 0, -1) : "e" } def edge_to_direction(source_node, dest_node): row_delta=source_node[0]-dest_node[0] column_delta=source_node[1]-dest_node[1] return output.directions[(row_delta, column_delta)] def path_to_directions(path): result="" for step in range(len(path)-1): result+=output.edge_to_direction(path[step],path[step+1]) return result def simplify_directions(directions): directions+="\0" count=0 result="" last="" for d in directions: if d!=last or d is "\0": result+="{} {},".format(last, count) count=0 last="" if count==0: last=d count=1 continue if d==last: count+=1 return result[3:-1] if __name__=='__main__': contents="010\n000\n100" #read from file? data=input(contents).matrix.graph result_path=algorithm.find_path(data) directions=output.path_to_directions(result_path) directions=output.simplify_directions(directions) print(directions+"\n") print(str(result_path)[1:-1].replace('), (',') --> (').replace(', ',','))   ```   ## Performance I ran this solution (on my old Core i3 laptop) on the 20x20 '*performance*' example input and it ran in around ~6 seconds (of course, YMMV). I am **SURE** there are ways to do this faster, probably by orders of magnitude. However, I didn't feel like re-writing my own [A\*](https://en.wikipedia.org/wiki/A*_search_algorithm) algorithm in assembly and renting some time slices on a super computer! ## About this Code ## The Idea The idea for this approach comes from [my answer over here in Code Review](https://codereview.stackexchange.com/questions/122658/finding-the-longest-path-avoiding-obstacles-in-a-2d-plane/122785#122785). You can also read a little bit more about it and the end of my answer here. ## Dependencies As you may have notice by the (rather prominent) line `import networkx as nx` - this code relies upon the [Python NetworkX module](https://networkx.github.io/) to function. So do >`pip install networkx` if you get import errors when running. ## Breakdown of Solution Elements by Lines of Code I also thought it would be interesting (and it was), after [Don Muesli](https://codegolf.stackexchange.com/users/36398/don-muesli)'s comment (particularly the part "*a significant part of the efffort[sic] is formatting the output*"), to **examine** how much of the code is for various things.       **Breakdown**: * 39 lines (or 43.33%) of the lines of code in the program are concerned with parsing the input and constructing/weighting the graph data structure. * 37 lines (approx. 41%) directly relate *solely* to displaying and formatting the desired **output**! * 5 lines (5.5%) are 'other' stuff, which relates to *running the program* ([shebang line](https://en.wikipedia.org/wiki/Shebang_%28Unix%29), imports, the `if __name__=="__main__"`..., etc). * And 9 (yes.. nine) lines of code (or *just* 10%) **actually relates to the algorithm usage**.       **Obligatory Pie Chart**: ##                   [Pie Chart illustration of Solution Elements by Lines of Code](https://i.stack.imgur.com/a1YMg.png) --- ## About the Approach As I mentioned above, most of the idea for this approach comes from [my answer over on Code Review](https://codereview.stackexchange.com/questions/122658/finding-the-longest-path-avoiding-obstacles-in-a-2d-plane/122785#122785) regarding this problem. The process itself is relatively straightforward: 1. Transform the given matrix into an undirected graph data structure 2. Annotate (*i.e.* add weights) the edges of that graph 3. Add a "sink" node - to be used as a *search target* 4. Add (weighted) edges between all nodes and the sink node 5. Use a [Graph Search Algorithm](https://en.wikipedia.org/wiki/Tree_traversal) (in this case [A\*](https://en.wikipedia.org/wiki/A*_search_algorithm))   So, taking the 3x3 matrix from the question for example. The transformation into a graph would yield something like the following: [![Graph of example 3x3 Matrix](https://i.stack.imgur.com/b2Ofo.png)](https://i.stack.imgur.com/b2Ofo.png) (**Note:** the 'blocked' nodes do not have any edges) Step 2; *imagine* each green line in the above picture has a *weight* of `-1`. Next, for step 3 and 4 together (I didn't want to have to make another picture), take a look at the following graph: [![Matrix Graph with Sink Node](https://i.stack.imgur.com/jRnPX.png)](https://i.stack.imgur.com/jRnPX.png) And again *imagine* the edges are weighted, only red lines are *weighted* `+1`. We can then apply the [A-star algorithm from the NetworkX library](http://networkx.github.io/documentation/latest/reference/generated/networkx.algorithms.shortest_paths.astar.astar_path.html#networkx.algorithms.shortest_paths.astar.astar_path) to this graph, using the custom *heuristic* function. This makes the search algorithm score paths in an inverse manner (longest path rather than shortest). And the **longest** path will be the one that visits the *most* cells of the problem matrix! [Answer] # [Clingo](https://potassco.org/), 202 seconds for 20×20 [This problem is NP-complete](http://www.cs.technion.ac.il/~itai/publications/Algorithms/Hamilton-paths.pdf), even if you were to guarantee that all `0`s are used, so your dreams of a program that runs efficiently for 500×500 may be a little bit unrealistic. (The other answer using A\* search doesn’t find the optimal solution, even on the 3×3 example case, because A\* never revisits a node that was previously found on a different path.) ``` #script (python) import clingo import itertools import sys def main(prg): matrix = [list(line.split()) for line in sys.stdin] def data(): for i, row in enumerate(matrix): for j, cell in enumerate(row): if cell == '0': yield f'cell(({i}, {j})).\n' def on_model(model): step = {} for atom in prg.symbolic_atoms: if atom.symbol.name == 'step' and model.contains(atom.symbol): a, d, b = atom.symbol.arguments step[a] = d, b moves = [] a = clingo.Tuple((0, 0)) while step[a][1] != clingo.Tuple((0, 0)): d, a = step[a] moves.append(d) print(len(moves) + 1) print(','.join(f'{d} {len(list(g))}' for d, g in itertools.groupby(moves))) prg.add('data', [], ''.join(data())) prg.ground([('base', []), ('data', [])]) prg.solve(on_model=on_model) #end. #program base. dir(s, (1, 0); e, (0, 1); n, (-1, 0); w, (0, -1)). adj((X, Y), D, (X+DX, Y+DY)) :- cell((X, Y)), dir(D, (DX, DY)), cell((X+DX, Y+DY)). adj(A, end, (0, 0)) :- cell(A). {step(A, D, B) : adj(A, D, B)} = 1 :- visit(A). :- visit(B), {step(A, D, B) : adj(A, D, B)} != 1. visit((0, 0)). visit(B) :- step(A, D, B). :~ visit(A). [-1, A] #show step/3. ``` ### Demo ``` $ clingo -q longest.lp < 20x20.in clingo version 5.2.2 Reading from longest.lp Solving... 1 2 s 1 3 s 2 4 s 3 5 e 3,s 1 6 e 3,s 2 7 e 3,s 3 9 e 3,s 5 … 264 s 4,e 1,n 4,e 2,s 1,w 1,s 1,e 1,s 1,w 1,s 1,e 1,s 1,w 1,s 1,w 1,n 1,w 1,s 3,e 1,n 1,e 1,s 12,e 1,n 13,e 2,s 1,e 2,n 7,e 1,s 2,e 2,n 1,w 1,n 1,e 4,s 5,w 1,s 1,e 1,s 1,w 2,s 1,e 2,s 1,w 1,s 1,e 1,s 1,w 2,s 1,w 1,s 2,w 1,n 3,e 1,n 1,e 1,n 1,w 1,n 3,e 1,n 1,w 1,n 1,e 2,n 3,w 1,s 2,w 3,s 1,e 1,s 1,w 1,s 1,e 1,s 4,w 1,n 2,w 1,s 3,e 1,s 1,w 1,s 1,e 1,s 1,w 1,s 1,e 3,s 1,e 1,n 3,e 1,n 1,e 1,s 2,w 1,s 1,e 1,s 1,w 1,s 2,w 1,n 1,w 2,n 1,w 2,s 1,e 1,s 1,w 1,s 1,e 2,n 1,e 1,s 1,e 3,n 2,e 2,n 1,e 2,s 3,e 1,n 1,e 1,n 6,w 1,n 1,e 1,n 9,w 1,n 1,e 1,n 1,w 2,s 3,e 1,s 1,w 1,s 1,e 1,s 1,w 1,s 1,e 1,s 1,w 1,s 1,e 1,s 1,w 1,s 3,e 1,s 1,w 1,s 1,e 1,s 2 265 s 4,e 1,n 4,e 2,s 1,w 1,s 1,e 1,s 1,w 1,s 1,e 1,s 1,w 1,s 1,w 1,n 1,w 1,s 3,e 1,n 1,e 1,s 12,e 1,n 13,e 2,s 1,e 2,n 7,e 1,s 2,e 2,n 1,w 1,n 1,e 4,s 5,w 1,s 1,e 1,s 1,w 2,s 1,e 2,s 1,w 1,s 1,e 1,s 1,w 2,s 1,w 1,s 2,w 1,n 3,e 1,n 1,e 1,n 1,w 1,n 3,e 1,n 1,w 1,n 1,e 2,n 3,w 1,s 2,w 3,s 1,e 1,s 1,w 1,s 1,e 1,s 4,w 1,n 2,w 1,s 3,e 1,s 1,w 1,s 1,e 1,s 1,w 1,s 1,e 3,s 1,e 1,n 3,e 1,n 1,e 1,s 2,w 1,s 1,e 1,s 1,w 1,s 2,w 1,n 1,w 2,n 1,w 2,s 1,e 1,s 1,w 1,s 1,e 2,n 1,e 1,s 1,e 3,n 2,e 2,n 1,e 2,s 1,e 1,s 1,w 1,s 1,e 2,n 3,w 1,n 1,w 1,n 1,e 1,n 1,w 1,n 1,e 1,n 1,w 1,n 1,e 1,n 1,w 1,n 1,e 1,n 1,w 1,n 1,e 1,n 1,w 1,n 1,e 1,n 1,w 1,n 1,e 1,n 1,w 1,n 1,e 2,s 15 OPTIMUM FOUND Models : 99 Optimum : yes Optimization : -265 Calls : 1 Time : 201.664s (Solving: 201.56s 1st Model: 0.00s Unsat: 0.00s) CPU Time : 201.602s ``` The final output line (above `OPTIMUM FOUND`) corresponds to the following path through 265 nodes: ``` • ┌───┐ 1 0 1 ┌─┐ ┌───────┐ 1 0 1 ┌───┐ │ │ ┌─┘ 1 0 1 │ │ └─┐ ┌─┐ │ 1 0 1 └─┐ │ │ │ └─┐ 1 0 1 │ └───┘ │ │ │ 1 0 1 ┌─┘ │ │ │ ┌─┘ 1 0 1 │ ┌─────┘ │ │ 1 0 1 └─┐ │ └─┘ └─┐ 1 0 1 │ └─┐ ┌───┘ │ 1 0 1 ┌─┘ │ ┌─┐ ┌─┘ 1 0 1 │ ┌─┘ └─┐ ┌─┘ 1 0 1 └─┐ │ │ └─┘ ┌───┐ 1 │ └─┐ ┌─┘ └─┐ 1 0 1 ┌─┘ │ │ ┌─┐ │ 1 └───┘ 1 │ │ ┌───┘ 1 0 1 └─┐ │ └─┘ │ │ 1 0 1 ┌─┐ │ │ └───┐ 1 0 1 ┌─┘ │ 0 1 │ │ 1 1 1 │ │ │ └─┐ ┌─┘ 1 0 1 └─┐ │ 0 1 │ │ 1 1 1 │ └─┘ ┌─┘ └─┐ 1 0 1 ┌─┘ │ 0 1 │ │ 1 1 1 └─┐ ┌─┘ ┌───┘ 1 0 1 └─┐ │ 0 1 │ │ 1 1 1 ┌─┘ │ ┌─┘ ┌─┐ 1 0 1 ┌─┘ │ 0 1 │ │ 1 1 1 └─┐ │ │ ┌─┘ │ 1 0 1 └─┐ │ 0 1 │ │ 1 1 1 ┌─┘ └─┘ │ ┌─┘ 1 0 1 ┌─┘ │ 0 1 │ │ 1 1 1 └─────┐ │ └─┐ 1 0 1 └─┐ • 0 1 │ │ 1 1 1 ┌───┐ └─┘ ┌─┘ 1 ┌───┐ └─┐ 0 1 │ │ 1 1 1 └─┐ └───┐ │ ┌───┘ 1 └─┐ │ 0 1 │ │ 1 1 1 ┌─┘ ┌─┐ └─┘ │ 1 0 1 ┌─┘ │ 0 1 └─┘ 1 1 1 └───┘ └─────┘ 1 0 1 └───┘ ``` ]
[Question] [ Your task here is to write an AI for a simple robot battle. The class to be implemented is provided at the bottom of this post, and source of the controller can be found [here.](http://pastebin.com/raw.php?i=JZ7cfGZJ) # Requirements 1. Write a class which implements the abstract Bot class, provided at the bottom of this post 2. You must provide a 0-argument constructor, this must change the value of the Name field, but may not change any other inherited fields 3. Outside of the constructor, you may not change any of the inherited fields in any way 4. Your action method should, when called (it will be called once per turn cycle, with a copy of the 64 by 64 map as its argument), return one of the Action enum fields: ``` UP to move up (towards y=0) DOWN to move down LEFT to move left (towards x=0) RIGHT to move right MINE to plant a mine and then move a random direction PASS to pass ``` 5. Within the passed map, 0 represents an empty cell, -1 represents a mined cell, and anything else denotes a cell occupied by a bot (each bot will be represented by its unique bot\_id, you can get your bot's id by calling this.id()) 6. A bot is eliminated in any of the following situations: * It moves out of the map * It moves into a cell occupied by a mine * Another bot moves into the cell it currently occupies * Its action method takes more than 50ms to respond * Its action method throws any exception that is not caught within its own bounds # To win Have your bot be the last bot standing! # Additional Rules The round is not allowed to last more than 1,000 turn cycles. If, after the 1,000th turn cycle, more than one bot is still standing, all of the surviving bots are considered to have tied that round. Each time a new bot is submitted, it will, as soon as possible, be pitted in two two-bot, three three-bot, and three-four bot rounds; each time against randomly selected opponents. # Scoring total score=1000\*(wins+(1/3) ties - (1/12) losses)/roundsPlayed The exceptions to this are that any bot that has played at least one round that it didn't lose is guaranteed at least one point, and no bot may have a negative score. # The class to be implemented: ``` import java.util.*; public abstract class Bot { public static enum Action{ UP,DOWN,LEFT,RIGHT,MINE,PASS; } public static final class Position{ public int x; public int y; public String toString(){ return "("+x+","+y+")"; } public double distance(Position p){ int dx=p.x-this.x; int dy=p.y-this.y; return Math.sqrt(dx*dx+dy*dy); } public Position(int x,int y){ this.x=x; this.y=y; } } public String toString(){return name;} public Position p; public String name=""; public abstract Action action(int[][] map); private int bot_id; public final int id(){return bot_id;} public final void register(List<Bot> a){ a.add(this); bot_id=a.size(); } } ``` # Leaderboard *The full match log may be read [here](https://drive.google.com/file/d/0B66Q2_YrkhNneEFCVGxyYVBNWWM/view?usp=sharing)* ``` ProtectiveBot (6 wins, 6 ties, 1 loss)- 609 points Albert (2 wins, 8 ties, 0 losses)- 467 points Frozen (1 win, 8 ties, 0 losses)- 407 points Cocoon (1 win, 3 ties, 3 losses)-250 points Wanderlust (0 wins, 3 ties, 5 losses)- 73 points MineThenBoom (0 wins, 2 ties, 11 losses)- 1 point PatientBot (0 wins, 0 ties, 13 losses)- 0 points ``` # Sample Bots Simple Pathfinder: <http://pastebin.com/raw.php?i=aNBf00VU> RandomBot: <http://pastebin.com/raw.php?i=VD8iGaHC> Minelayer: <http://pastebin.com/raw.php?i=sMN1zSa0> [Answer] # Frozen After analyzing how the controller worked, I determined the only way to lose is to move. Therefore, this robot stays in place unless absolutely necessary. ``` public class Frozen extends Bot{ public Frozen(){ this.name="Frozen"; } public Action action(int[][] map) { if (p.x > 0 && map[p.x-1][p.y] > 0) return Action.LEFT; if (p.x < map.length-1 && map[p.x+1][p.y] > 0) return Action.RIGHT; if (p.y > 0 && map[p.x][p.y-1] > 0) return Action.UP; if (p.y < map.length-1 && map[p.x][p.y+1] > 0) return Action.DOWN; return Action.PASS; } } ``` [Answer] # ProtectiveBot A bunch of ideas rolled together to form something. There are a number of states that it can enter. Firstly, if there is no-one around them, it will build itself a cocoon which is just about indestructible, and sit in it for a while, killing anyone it can. If there is someone close during startup, there is less then 200 turns left, or there is only one enemy bot remaining, the bot will enter a aggressive mode, which is essentially an enhanced pathfinder, attempting to trick its opponents. This mode uses a flood style pathfinding system at close range, and the same technique in the provided pathfinding example at long range. If there are multiple instances of this bot in game, the bots will refrain from killing each other until the end. Its big as well, weighing in at ~~527~~ 741 lines. Compiling against Java 8. Also, have a graphic renderer of the battle system: <https://github.com/j-selby/RobotBattleController> > > I've reached the limit for how big these posts can be, see bot src at > <https://github.com/j-selby/RobotBattleController/blob/master/src/main/java/ProtectiveBot.java>. > Sorry... > > > Rev 3: * Threaded pathfinding. No more timeouts! * Detection of stalemates. TODO: Do something about them. * Full A\* pathfinding. No more dumb stuff. * Checks OTHER bots positions for unfair play (trapping themselves in completely). Rev 2: * Stopped bot being killed at corners * Smarter building logic * Will never do any move that could endanger us, excluding against other instances of ProtectiveBot. [Answer] # Wanderlust I join the competetion with a bot called Wanderlust! Its algorithm is actually pretty straightforward. While it's trying to avoid mines and not running off the map, it's randomly spraying mines around. If an enemy bot would come closer, though, it scurries off in the opposite direction. Wanderlust's a decent bot, but just doesn't cut it when there are A\* algorithm bots on the field. You can see it running away while the enemy bot is figuring out how to get closer, but eventually it dies. (Unless those bots get trapped of course, which then simply results in a tie.) ``` import java.util.ArrayList; import java.util.List; import java.util.Random; public class Wanderlust extends Bot { private static final double NEAR_ENEMY_RUN_DISTANCE = 12; private static final double NEAR_ENEMY_PASS_DISTANCE = 2.5; private static final int SAFE_NUMBER_OF_MINES = 0; private Random random; public Wanderlust() { this.name = "Wanderlust"; this.random = new Random(System.currentTimeMillis()); } @Override public Action action(int[][] map) { List<Action> actions = new ArrayList<Action>(); List<Position> enemyPositions = mapEnemyPositions(map); Position nearestBotPosition = getNearestBotPosition(enemyPositions); Action action = Action.PASS; if (nearestBotPosition != null && nearestBotPosition.distance(this.p) < NEAR_ENEMY_RUN_DISTANCE) { // Run! Can't risk to drop a mine because of the random movement afterwards. // So check where the enemy is and run the opposite way! // This is all good unless the enemy is reaaaally close. In that case, we're just struck with fear and stand still. if (nearestBotPosition.distance(this.p) < NEAR_ENEMY_PASS_DISTANCE) { return Action.PASS; } int dx = this.p.x - nearestBotPosition.x; int dy = this.p.y - nearestBotPosition.y; Action horizontalAction = dx < 0 ? Action.LEFT : Action.RIGHT; Action verticalAction = dy < 0 ? Action.UP : Action.DOWN; // Is the enemy closer to me on the x-axis, or the y-axis? if (Math.abs(dx) < Math.abs(dy)) { // OK, which way do we run away from the enemy? Left or right? // And if we can't run left or right, we should think about a back-up plan: moving vertically. Action primaryAction = dx < 0 ? Action.LEFT : Action.RIGHT; actions.add(primaryAction); actions.add(verticalAction); action = getValidMove(actions, true, map); } else { // OK, which way do we run away from the enemy? Up or down? // And if we can't run up or down, we should think about a back-up plan: moving horizontally. Action primaryAction = dy < 0 ? Action.UP : Action.DOWN; actions.add(primaryAction); actions.add(horizontalAction); action = getValidMove(actions, true, map); } } else { // Just casual strolling. Hey, perhaps dropping a mine? #casualThings actions.add(Action.LEFT); actions.add(Action.RIGHT); actions.add(Action.UP); actions.add(Action.DOWN); actions.add(Action.MINE); if (this.p.x == 0 || this.p.x == 63 || this.p.y == 0 || this.p.y == 63 || getNumberOfMinesAroundPosition(this.p, map) > SAFE_NUMBER_OF_MINES) { actions.remove(Action.MINE); } action = getValidMove(actions, false, map); } return action; } private Action getValidMove(List<Action> actions, boolean preserveOrder, int[][] map) { List<Action> validMoves = new ArrayList<Action>(); for (Action action : actions) { if (action == Action.LEFT && this.p.x > 0 && map[this.p.x-1][this.p.y] >= 0) { validMoves.add(Action.LEFT); } if (action == Action.RIGHT && this.p.x < 63 && map[this.p.x+1][this.p.y] >= 0) { validMoves.add(Action.RIGHT); } if (action == Action.UP && this.p.y > 0 && map[this.p.x][this.p.y-1] >= 0) { validMoves.add(Action.UP); } if (action == Action.DOWN && this.p.y < 63 && map[this.p.x][this.p.y+1] >= 0) { validMoves.add(Action.DOWN); } if (action == Action.MINE) { validMoves.add(Action.MINE); } } if (validMoves.isEmpty()) { return Action.PASS; } return preserveOrder ? validMoves.get(0) : validMoves.get(random.nextInt(validMoves.size())); } private int getNumberOfMinesAroundPosition(Position position, int[][] map) { int count = 0; if (position.x > 0 && map[position.x-1][position.y] == -1) { count++; } if (position.x < 63 && map[position.x+1][position.y] == -1) { count++; } if (position.y > 0 && map[position.x][position.y-1] == -1) { count++; } if (position.y < 63 && map[position.x][position.y+1] == -1) { count++; } return count; } private Position getNearestBotPosition(List<Position> enemyPositions) { Position botPosition = null; double distance = Double.MAX_VALUE; for (Position position : enemyPositions) { double botDistance = position.distance(this.p); if (botDistance <= distance) { distance = botDistance; botPosition = position; } } return botPosition; } private List<Position> mapEnemyPositions(int[][] map) { List<Position> enemyPositions = new ArrayList<Position>(); for (int yy = 0; yy < 63; yy++) { for (int xx = 0; xx < 63; xx++) { if (map[xx][yy] > 0 && map[xx][yy] != id()) { enemyPositions.add(new Position(xx, yy)); } } } return enemyPositions; } } ``` [Answer] # PatientBot Super simple bot that puts down a defensive wall and then just waits. (I will probably write a more serious solution later, but this will do for now.) ``` public class PatientBot extends Bot{ public PatientBot(){ name="PatientBot"; } int turn = 0; public Action action(int[][] map){ switch(turn++){ case 0: return Action.UP; case 1: return Action.MINE; case 2: return Action.LEFT; case 3: return Action.DOWN; case 4: return Action.MINE; case 5: return Action.DOWN; case 6: return Action.RIGHT; case 7: return Action.MINE; case 8: return Action.RIGHT; case 9: return Action.UP; case 10: return Action.MINE; default: return Action.PASS; } } } ``` [Answer] # Cocoon I borrowed a bit of utility code from some other bots. The basic strategy here is to get into a safe spot. To accomplish that, I try to lay mines in spots likely to bump me into safe spots. Nearby goals are preferred over distant goals. Absolutely nothing is done about other bots. This bot can usually build a safe spot in a few dozen turns after laying down a checkerboard of failures, so it will at least tie with other bots that can't seek it out and kill it that fast. A bit of code to avoid or kill other bots would improve that scenario. ``` import java.awt.*; import java.util.*; import java.util.concurrent.LinkedBlockingQueue; public class CocoonBot extends Bot{ private static final int Y = 64, X = 64; public CocoonBot() { this.name="Cocoon"; } private int neighborMines(int[][] map, Point p){ int mines=0; if (p.y>=Y-1||map[p.x][p.y+1]==-1) mines++; if (p.y<= 0||map[p.x][p.y-1]==-1) mines++; if (p.x>=X-1||map[p.x+1][p.y]==-1) mines++; if (p.x<= 0||map[p.x-1][p.y]==-1) mines++; return mines; } @Override public Action action(int[][] map) { Point firstPoint = new Point(p.x, p.y); if ( neighborMines(map,firstPoint) == 4 ) { return Action.PASS; // we've built a cocoon and are safe } // calculate how many mines surround each point of the map, 0-4 Map<Point, Integer> safety = new HashMap<>(); for(int x=0; x<X; x++) { for(int y=0; y<Y; y++) { //TODO: teach the bot that it won't ever lay mines on the edge or adjacent to other mines // so effective safety is 0 if getting to 3 requires one of those actions Point p = new Point(x,y); int s = neighborMines(map,p); safety.put(p,s); } } // flood fill the map to find travel paths and distances from the current square to each other non-mine square LinkedBlockingQueue<Point> frontier = new LinkedBlockingQueue<>(); Map<Point, Point> came_from = new HashMap<>(); Map<Point, Integer> distance = new HashMap<>(); frontier.add(firstPoint); came_from.put(firstPoint, new Point(-1, -1)); distance.put(firstPoint,0); Point current; while((current = frontier.poll()) != null) { // TODO: bail here for squares too far away to be worth considering for(int d=0; d<4; d++) { int dx = d<2?(d*2-1):0; //-1 +1 0 0 int dy = d<2?0:(d*2-5); // 0 0 -1 +1 if (current.y+dy<Y && current.y+dy>=0 && current.x+dx<X && current.x+dx>=0) { if (map[current.x+dx][current.y+dy] != -1) { Point next = new Point(current.x+dx, current.y+dy); if(!distance.containsKey(next)) { frontier.add(next); came_from.put(next, current); distance.put(next,distance.get(current)+1); } } } } } // calculate the safety of where we might end up after dropping a mine // weighted towards safer spaces, we really want to end up in space that's already safety=3 Map<Point, Integer> safety2 = new HashMap<>(); for(int x=0; x<X; x++) { for(int y=0; y<Y; y++) { int s = 0; for(int d=0; d<4; d++) { int dx = d<2?(d*2-1):0; //-1 +1 0 0 int dy = d<2?0:(d*2-5); // 0 0 -1 +1 Point p = new Point(x+dx,y+dy); if ( x+dx<0||x+dx>=X||y+dy<0||y+dy>=Y || map[x+dx][y+dy]==-1 ) { // never risk moving into a mine or off the map! s = -999; break; } else if ( safety.containsKey(p) ) { // safety 3 is great // safety 2 is ok // safety 1 is better than nothing s += safety.get(p)>2?12:safety.get(p)>1?3:safety.get(p); // magic numbers! } } Point p = new Point(x,y); safety2.put(p,s); } } // find the safest/closest point Point bestpoint = firstPoint; double bestscore = safety2.get(firstPoint)+0.1; distance.remove(firstPoint); for (Map.Entry<Point,Integer> pd : distance.entrySet()) { Point p = pd.getKey(); double score = safety2.get(p)/Math.pow(pd.getValue(),0.8); // magic number! if(score > bestscore) { bestscore = score; bestpoint = p; } else if (score == bestscore) { if ( (bestpoint.x-X/2)*(bestpoint.x-X/2)+(bestpoint.y-Y/2)*(bestpoint.y-Y/2) > (p.x-X/2)*(p.x-X/2)+(p.y-Y/2)*(p.y-Y/2) ) { // aim for the middle, less wasted time at edges bestscore = score; bestpoint = p; } } } // we're in the right spot, place a mine and hope for a good random bump if(bestpoint == firstPoint) { return Action.MINE; } // walk back up came_from to figure out which way to step to get to bestpoint while(came_from.get(bestpoint) != firstPoint) { bestpoint = came_from.get(bestpoint); } if ( bestpoint.x > firstPoint.x ) { return Action.RIGHT; } if ( bestpoint.x < firstPoint.x ) { return Action.LEFT; } if ( bestpoint.y > firstPoint.y ) { return Action.DOWN; } if ( bestpoint.y < firstPoint.y ) { return Action.UP; } // should never happen return Action.MINE; } } ``` [Answer] # MineThenBoom A modified version of the pathfinder. His priorities are crush, mine, leave, sit. Yeah, the guy's a little crazy. Updates to this bot may be given as I find new strategies. Please notify me if something goes wrong. ``` import java.util.*; public class MineThenBoom extends Bot{ public MineThenBoom() { this.name="MineThenBoom"; } public Action action(int[][] map) { List<Position> enemies=new ArrayList<Position>(); for(int x=1;x<map.length;x++){ for(int y=1;y<map[x].length;y++){ if(map[x][y]!=0&&map[x][y]!=this.id()&&map[x][y]!=-1){ enemies.add(new Position(x,y)); } } } double d=200; Position x=null; for(Position pos:enemies){ if(p.distance(pos)<d){ x=pos; d=p.distance(pos); } } // initialize checking for walls boolean can_move_left = p.x != 0; boolean can_move_right = p.x != 63; boolean can_move_up = p.y != 0; boolean can_move_down = p.y != 63; // Check if there's anyone nearby to crush, if it won't put us in danger. if(x.x<p.x&&map[p.x-1][p.y]!=-1&&x.x<p.x&&map[p.x-1][p.y]!=0) { boolean no_one_around = map[p.x-1][p.y-1] < 1 && map[p.x-1][p.y+1] < 1; if(no_one_around)return Action.LEFT; } if(x.x>p.x&&map[p.x+1][p.y]!=-1&&x.x<p.x&&map[p.x-1][p.y]!=0) { boolean no_one_around = map[p.x+1][p.y-1] < 1 && map[p.x+1][p.y+1] < 1; if(no_one_around)return Action.RIGHT; } if(x.y>p.y&&map[p.x][p.y+1]!=-1&&x.x<p.x&&map[p.x-1][p.y]!=0) { boolean no_one_around = map[p.x-1][p.y+1] < 1 && map[p.x+1][p.y+1] < 1; if(no_one_around)return Action.DOWN; } if(x.y<p.y&&map[p.x][p.y-1]!=-1&&x.x<p.x&&map[p.x-1][p.y]!=0) { boolean no_one_around = map[p.x-1][p.y-1] < 1 && map[p.x+1][p.y-1] < 1; if(no_one_around)return Action.UP; } // If we've come this far, it means no one is crushable. Lay a mine, but only if we're ABSOLUTELY safe. boolean no_one_around = map[p.x+1][p.y-1] < 1 && map[p.x+1][p.y+1] < 1 && map[p.x-1][p.y-1] < 1 && map[p.x-1][p.y+1] < 1; boolean not_walking_into_mine = map[p.x+1][p.y] == 0 && map[p.x-1][p.y] == 0 && map[p.x][p.y-1] == 0 && map[p.x][p.y+1] == 0; boolean not_walking_near_danger = map[p.x+2][p.y] < 1 && map[p.x-2][p.y] < 1 && map[p.x][p.y+2] < 1 && map[p.x][p.y-2] < 1; if(no_one_around && not_walking_into_mine && not_walking_near_danger)return Action.MINE; // OK, let's take a little walk. if(x.x<p.x&&map[p.x-1][p.y]!=-1) { boolean no_one_around = map[p.x-1][p.y-1] < 1 && map[p.x-1][p.y+1] < 1; if(no_one_around)return Action.LEFT; } if(x.x>p.x&&map[p.x+1][p.y]!=-1) { boolean no_one_around = map[p.x+1][p.y-1] < 1 && map[p.x+1][p.y+1] < 1; if(no_one_around)return Action.RIGHT; } if(x.y>p.y&&map[p.x][p.y+1]!=-1) { boolean no_one_around = map[p.x-1][p.y+1] < 1 && map[p.x+1][p.y+1] < 1; if(no_one_around)return Action.DOWN; } if(x.y<p.y&&map[p.x][p.y-1]!=-1) { boolean no_one_around = map[p.x-1][p.y-1] < 1 && map[p.x+1][p.y-1] < 1; if(no_one_around)return Action.UP; } // We clearly are pinned down by some number of players on one or more edges. Let's make our way out of here! no_one_around = map[p.x-1][p.y-1] < 1 && map[p.x-1][p.y+1] < 1 && map[p.x-2][p.y] < 1 && map[p.x-1][p.y] == 0 && x.x<p.x; if(no_one_around)return Action.LEFT; no_one_around = map[p.x+1][p.y-1] < 1 && map[p.x+1][p.y+1] < 1 && map[p.x+2][p.y] < 1 && map[p.x+1][p.y] == 0 && x.x>p.x; if(no_one_around)return Action.RIGHT; no_one_around = map[p.x-1][p.y-1] < 1 && map[p.x+1][p.y-1] < 1 && map[p.x][p.y-2] < 1 && map[p.x][p.y-1] == 0 && x.y<p.y; if(no_one_around)return Action.DOWN; no_one_around = map[p.x-1][p.y+1] < 1 && map[p.x+1][p.y+1] < 1 && map[p.x][p.y+2] < 1 && map[p.x][p.y+1] == 0 && x.y>p.y; if(no_one_around)return Action.UP; // Well then. We can't crush, lay a mine, or escape. // We are most likely near a player who, if they move, will either no longer be a threat or we can crush. // If we are somehow surrounded by mines, we're safe anyways. return Action.PASS; } } ``` **CHANGES** * Fixed bot so it wouldn't always lay mines, and won't be crushed too easily. * Fixed severe logic flaws in bot, as well as minor tune-ups. * Once again, rewrote all the logic. * v1.0: Added code to try to move around a little, see if we can force other bots like us to move. Thanks to SuperJedi224 for helping me with my code. [Answer] Well, here's another Simple Pathfinder variant I wrote, and I decided... why not enter it this time? # Albert ``` import java.util.*; public class Albert extends Bot{ private Random r=new Random(); public Albert(){ this.name="Albert"; } private int countMines(int[][] map,Position p){ int mines=0; if(p.y==63||map[p.x][p.y+1]==-1)mines++; if(p.y==0||map[p.x][p.y-1]==-1)mines++; if(p.x==0||map[p.x-1][p.y]==-1)mines++; if(p.x==63||map[p.x+1][p.y]==-1)mines++; return mines; } @Override public Action action(int[][] map) { List<Position> enemies=new ArrayList<Position>(); for(int x=1;x<map.length;x++){ for(int y=1;y<map[x].length;y++){ if(map[x][y]!=0&↦[x][y]!=this.id()&↦[x][y]!=-1){ enemies.add(new Position(x,y)); } } } double d=200; Position x=null; for(Position pos:enemies){ if(p.distance(pos)<d){ x=pos; d=p.distance(pos); } } if(countMines(map,p)==0&&r.nextDouble()<0.5&&d>2.01)return Action.MINE; if(d>1.03&&d<3)return Action.PASS; if(x==null)return Action.PASS; if(x.x<p.x&↦[p.x-1][p.y]!=-1&&countMines(map,new Position(p.x-1,p.y))<2&&r.nextDouble()<0.8)return Action.LEFT; if(x.x>p.x&↦[p.x+1][p.y]!=-1&&countMines(map,new Position(p.x+1,p.y))<2&&r.nextDouble()<0.8)return Action.RIGHT; if(x.y>p.y&↦[p.x][p.y+1]!=-1&&countMines(map,new Position(p.x,p.y+1))<2&&r.nextDouble()<0.8)return Action.DOWN; if(x.y<p.y&↦[p.x][p.y-1]!=-1&&countMines(map,new Position(p.x,p.y-1))<2&&r.nextDouble()<0.8)return Action.UP; List<Action> v=new ArrayList<Action>(); if(p.y>0&↦[p.x][p.y-1]!=-1&&countMines(map,new Position(p.x,p.y-1))<3)v.add(Action.UP); if(p.y<63&↦[p.x][p.y+1]!=-1&&countMines(map,new Position(p.x,p.y+1))<3)v.add(Action.DOWN); if(p.x>0&↦[p.x-1][p.y]!=-1&&countMines(map,new Position(p.x-1,p.y))<3)v.add(Action.LEFT); if(p.x<63&↦[p.x+1][p.y]!=-1&&countMines(map,new Position(p.x+1,p.y))<3)v.add(Action.RIGHT); v.add(Action.PASS); return v.get((new Random()).nextInt(v.size())); } } ``` ]
[Question] [ # Background In this challenge, a *partition* of a set `S` means a collection of nonempty subsets of `S`, which are mutually disjoint and whose union is `S`. We say that a partition `p` is *finer* than another partition `q` (and `q` is *coarser* than `p`), if it can be obtained from `q` by splitting some of its sets into smaller pieces. The *join* (or *least upper bound*) of two partitions is the finest partition which is coarser than both of them, and their *meet* (or *greatest lower bound*) is the coarsest partition which is finer than both of them. See the Wikipedia pages on [partitions](http://en.wikipedia.org/wiki/Partition_of_a_set#Refinement_of_partitions) and [lattices](http://en.wikipedia.org/wiki/Lattice_%28order%29#Examples) for more information and nice pictures. One way to compute the join and meet of two partitions `p` and `q` is the following. Form a graph whose vertex set is `S`, and add an edge `a - b` for each pair `a, b` that are in the same set in either `p` or `q`. Then the join of `p` and `q` contains the connected components of this graph. The meet of `p` and `q` consists of all nonempty intersections of a set in `p` with a set in `q`. For example, consider the partitions `[[0,1],[2,3]]` and `[[0,1,2],[3]]` of `S = [0,1,2,3]`. The graph mentioned above is ``` 0-1 |/ 2-3 ``` where the edge `2 - 3` comes from the first partition (`2` and `3` are in the same set), and the triangle comes from the second one (`0`, `1` and `2` are in the same set). This means that the join is `[[0,1,2,3]]`. The intersections of all the sets in the partitions are ``` [0,1] ∩ [0,1,2] = [0,1], [0,1] ∩ [3] = [], [2,3] ∩ [0,1,2] = [2], [2,3] ∩ [3] = [3] ``` Removing the empty set, we have the meet `[[0,1],[2],[3]]`. # Input Two partitions of a finite set of integers, given as arrays of arrays. # Output The join and meet of the input partitions, in this order. # Test Cases ``` [[1]] [[1]] -> [[1]] [[1]] [[0,1],[2,3]] [[0,1,2],[3]] -> [[0,1,2,3]] [[0,1],[2],[3]] [[0],[1],[2,3,4,7,6]] [[2,3],[4,7],[6],[1,0]] -> [[0,1],[2,3,4,6,7]] [[0],[1],[2,3],[4,7],[6]] [[0],[1,2],[5,4],[3,6]] [[0,3],[6,4],[5,2],[1]] -> [[0,1,2,3,4,5,6]] [[0],[2],[1],[4],[5],[3],[6]] ``` # Detailed Rules The order of the sets in the output partitions, and of the numbers in those sets, does not matter. You can assume that the inputs are correct, that is, they contain the same numbers, each exactly once, and no empty arrays. Note that the numbers do not necessarily form an interval (the third test case contains no `5`). You can write either a full program or a function. You can also write two programs/functions in the same language, one of which computes the join and other the meet, but there's a bonus of **-10 bytes** if you don't choose this option. The shortest byte count wins, and standard loopholes are disallowed. [Answer] # CJam, 32 - 10 = 22 ``` q_~{_{T&},:U-U:+a+}fTp~m*::&La-p ``` `::&` is newer than this question. # CJam, 36 - 10 = 26 ``` q_~{:T;_{T&},:U-U:+a+}/p~m*{~&}%La-p ``` Input: ``` [[0] [1] [2 3 4 7 6]] [[2 3] [4 7] [6] [1 0]] ``` Output: ``` [[2 3 4 7 6] [0 1]] [[0] [1] [2 3] [4 7] [6]] ``` ### Explanation ``` q " Read the input. "; _~ " Evaluate a copy. "; {:T; " For each list T in the second partition: "; _{T&}, " Select all lists in the first partition which share items with T. "; :U- " Save to U and remove them from the first partition. "; U:+a+ " Append the union of U to the first partition. "; }/ p " Print the meet. "; ~ " Evaluate another copy. "; m* " Get the Cartesian product. "; {~&}% " Get the intersections of each pair of lists. "; La- " Remove empty lists. "; p " Print. "; ``` [Answer] ## Java: 2014 (-10) = 2004 bytes ``` import java.util.*;public class A{static List<List<Set<Integer>>>b(Integer[][]c,Integer[][]d){Integer[][]e;Integer[][]f;if(c.length<=d.length){e=c;f=d;}else{e=d;f=c;} Q g=h(e);List<List<Set<Integer>>>i=new ArrayList<>();i.add(j(f,g));i.add(k(f,g));System.out.println(i.toString());return i;} static List<Set<Integer>>j(Integer[][]l,Q m){for(Integer[]o:l){if(o.length>1){n(m,o);}} return p(m);} static List<Set<Integer>>k(Integer[][]q,Q r){List<Set<Integer>>s=new ArrayList<>();for(Integer[]t:q){for(Set<Integer>u:v(r,t).values()){s.add(u);}} return s;} static Map<R,Set<Integer>>v(Q w,Integer[]x){Map<R,Set<Integer>>y=new HashMap<>();for(Integer z:x){R a=w.getSubset(z);if(!y.containsKey(a)){y.put(a,new HashSet<>());} y.get(a).add(z);} return y;} static List<Set<Integer>>p(Q partition){partition.b();List<Set<Integer>>c=new ArrayList<>();for(R d:partition.y){Set<Integer>e=new HashSet<>();R f=d;while(f!=null&&!f.g){e.addAll(f.t);f.g=true;f=f.s;} if(!e.isEmpty()){c.add(e);}} return c;} static void n(Q h,Integer[]i){for(int j:i){R k=h.getSubset(j);for(int l:i){R m=h.getSubset(l);if(k.s==null&&k!=m&&k!=m.s){k.s=m;}}}} static Q h(Integer[][]n){List<R>o=new ArrayList<>();for(Integer[]p:n){o.add(new R(p));} return new Q(o);}} class R{R s;Set<Integer>t;boolean g=false;R(Integer[]u){this.t=Collections.unmodifiableSet(new HashSet<>(Arrays.asList(u)));} R(Set<Integer>v){this.t=Collections.unmodifiableSet(v);}@Override public int hashCode(){final int p=31;int r=1;r=p*r+((t==null)?0:t.hashCode());return r;}@Override public boolean equals(Object x){if(this==x) return true;if(x==null) return false;if(getClass()!=x.getClass()) return false;R other=(R)x;if(t==null){if(other.t!=null) return false;}else if(!t.equals(other.t)) return false;return true;}} class Q{List<R>y;R getSubset(Integer z){for(R a:y){if(a.t.contains(z)){return a;}} return null;} Q(List<R>b){this.y=b;} void b(){List<R>c=new ArrayList<>();for(int i=0;i<y.size();i++){if(y.get(i).s!=null){c.add(y.get(i));y.remove(i);}} c.addAll(y);this.y=c;}} ``` Run by calling the b() function with two Integer[][]. Using the given inputs, outputs are: ``` [[[1]], [[1]]] [[[0, 1, 2, 3]], [[0, 1], [2], [3]]] [[[0, 1], [2, 3, 4, 6, 7]], [[2, 3], [4, 7], [6], [1], [0]]] [[[0, 1, 2, 3, 4, 5, 6]], [[3], [0], [6], [4], [2], [5], [1]]] ``` [Answer] # Mathematica, 127 - 10 = 117 Not fully golfed. ``` {ConnectedComponents@Graph@Union@##,FindClique[Graph@Intersection@##,Infinity,All]}&@@(Union@@(Rule@@@Tuples[#,2]&/@#)&/@{##})& ``` ]
[Question] [ ***Challenge*** You are given the following function:- ![enter image description here](https://i.stack.imgur.com/SMy3h.png) which is the same as:- ![enter image description here](https://i.stack.imgur.com/POl0F.png) with the base cases q(r, b, L) = 1 whenever r ≤ L, q(r, 0, L) = 0, if r > L and q(r, 0, L) = 1, if r ≤ L. Your task is to code a program that takes r as input, and outputs the value of q(r, r - L, L) for all L taking integer values from 1 to (r-1), where r is any nonnegative integer. ***Example 1*** ***Input*** > > Enter the value of r: 2 > > > ***Output*** > > q(2,1,1) = 0.3333333333 > > > ***Example 2*** ***Input*** > > Enter the value of r: 3 > > > ***Output*** > > q(3,2,1) = 0.1 > > > q(3,1,2) = 0.5 > > > ***Winning criterion*** The code that can correctly output q(r, r-L, L) for all L taking integer values from 1 to (r-1), for **the highest value of r**, in less than 300 seconds. In case of a tie, the code with lesser runtime will be considered. As this is a runtime-based challenge, I shall test all submissions on my machine. [Answer] ## Java I've applied some algebraic transformation and dynamic programming. ``` public class CodeGolf42234 { public static void main(String[] args) { int r = Integer.parseInt(args[0]); for (int L = 1; L < r; L++) System.out.println(qDouble5(r, r-L, L)); } private static double qDouble5(int _r, int _b, int L) { double[][] q = new double[_r+1][_b+1]; for (int r = 0; r <= L; r++) { for (int b = 0; b < q[r].length; b++) q[r][b] = 1; } for (int r = L + 1; r < q.length; r++) { for (int b = 1 + (r - L - 1)/L; b < q[r].length; b++) { double sum = 0, m = 1; for (int k = 0; k <= L; k++) { sum += m * q[r-k][b-1]; m = m * (r - k) / (r + b - 1 - k); } q[r][b] = sum * b / (r + b); } } return q[_r][_b]; } } ``` [Answer] ## Java Here's a recursive solution. Just like you wanted. You can always uncomment the output and display it if you want. ``` import java.util.ArrayList; import java.util.Scanner; public class HeaderFinder { static ArrayList<Double> answers = new ArrayList<Double>(); public static void main(String[]args) { Scanner scanner = new Scanner(System.in); int r = scanner.nextInt(); for(int b=r-1; b!=0; b--) for(int L=r-1; L!=0; L--) answers.add(formulate(r,b,L)); // int i=-1; // for(int b=r-1; b!=0; b--) // for(int L=r-1; L!=0; L--) // System.out.println("q("+r+", "+b+", "+L+") = "+answers.get(++i)); } public static double formulate(double r, double b, double L) { if(b==0) if(r>L) return 0.0; else return 1; if(r<=L) return 1; double partone = (b/(r+b)); double result = 0.0; for(int k=1; k<=L; k++) { result+=summation(r, b, k) * (b/(r+b-k)) * formulate(r-k, b-1, L); } return (partone * formulate(r, b-1, L)) + result; } public static double summation(double r, double b, int k) { double rb = r+b; double mul=r/rb; for(int i=1; i<k; i++) { mul*=(r-i)/(rb-i); } return mul; } } ``` ]
[Question] [ The [Riemann series theorem](http://en.wikipedia.org/wiki/Riemann_series_theorem) states that the terms of a conditionally convergent series can be permutated such that the resulting series converges to an arbitrary value. # The Challenge Write a program or function that takes in three parameters via stdin (or equivalent) or as parameters: * The expression for the sequence `x_n` (with variable `n`). The exact format (e.g., whether a power is represented as `^`, `pow()` or `**`) is irrelevant and may be chosen to fit your language. Alternatively you may pass a function directly as an argument. The definition of the function does not count towards the byte count. * A value `S` that we want to approach. Numerical values only are fine, you don't need to support mathematical expressions. * A threshold `t>0`. Numerical values only are fine here as well. Your program/function must output (to stdout or equivalent) resp. return a space- or newline-separated list `p_1, ..., p_N` of indices. Your output must satisfy the condition that the sum from `k = 1..N` over `x_(p_k)` differs from `S` no more than `t` in terms of the absolute difference. In other words, it must satisfy ![| sum(1..N, x_(p_k)) - S | <= t](https://i.stack.imgur.com/8B79z.png) So far, since the output will be a finite number of indices, the order would not matter. Therefore, another restriction applies: with decreasing threshold `t`, you may only *add* indices to the output (assuming a fixed `S`). In other words, for a fixed `S`, if `t_1 < t_2` and `[x_1, ..., x_N]` is a solution for `t_2`, then a solution for `t_1` must be of the form `[x_1, ..., x_N, ..., x_M]` with `M >= N`. # Details and Restrictions * The order of the arguments may be changed to suit your needs. * Provide an example call with the arguments from the example below. Ideally, post a link to an online interpreter/compiler. * `eval` and the like are explicitly allowed for the purpose of evaluating mathematical expressions. * Sequences are 1-based, so the first index is 1. * You don't need to take special care of big integers or floating point problems. There will be no extreme test cases such as using machine precision as the threshold. * Standard loopholes apply. * You may assume that the sequence passed to your program is conditionally convergent, i.e. that it is possible to solve the task with the given parameters. # Example Say your program is in a file `riemann.ext`, then a call might be ``` ./riemann.ext "(-1)^(n+1)/n" 0.3465 0.1 ``` # Scoring This is code-golf. The shortest program in bytes (UTF-8 encoding) wins. In case of a tie, the earlier entry wins. [Answer] # Haskell, ~~161~~ ~~158~~ 144 because Haskell can deal with infinite lists, instead of doing the parsing stuff this solution receives an infinite list as the sequence. ``` r l s t=unwords[show$[i+1|i<-[0..],l!!i==x]!!0|x<-s%filter(>0)l$filter(<0)l]where(g%j@(p:o))y@(n:b)|abs g<t=[]|g<0=n:((g-n)%j)b|0<1=p:((g-p)%o)y ``` example output: ``` *Main> let harm = zipWith (*) (cycle [1,-1]) (map (1/) [1..]) -- the alternating harmonic numbers *Main> r harm 3 0.001 "1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 101 103 105 107 109 111 113 2 115 117 119 121 123 125 127 129 131 133 135 137 139 141 143 145 147 149 151 153 155 157 159 161 163 165 167 169 171 173 175 177 179 181 183 185 187 189 191 193 195 197 199 201 203 205 207 209 211 213 215 217 219 221 223 225 227 229 231 233 235 237 239 241 243 245 247 249 251 253 255 257 259 261 263 265 267 269 271 273 275 277 279 281 283 285 287 289 291 293 295 297 299 301 303 305 307" ``` [Answer] ### Haskell, 206 characters ``` import Data.List r t e f=unwords.map(show.snd)$(\(x,y:_)->x++[y])$span(\(s,_)->abs(t-s)>e)$m 0$partition(<(0,0))$zip f[1..] where m s(a@((b,c):d),w@((x,y):z))|s<t=(x+s,y):m(x+s)(a,z)|1>0=(b+s,c):m(b+s)(d,w) ``` The sequence itself is an implicit last argument. Usage: ``` r 2 0.001 [(-1)**(n+1) / n | n <- [1..]] ``` Beaten before even having been posted, but - oh well. Posted anyways. I also took the liberty of accepting an infinite list as my first argument. readable version: ``` import Data.List import Debug.Trace riemannConverge :: (Integral ix, Num v, Ord v, Show ix, Show v) => (ix -> v) -> v -> v -> String riemannConverge target maxError series = unwords $ map (show . \(_,ix) -> ix) $ (\(xs,y:_) -> xs++[y]) $ span (\(s,_) -> abs (target - s) > maxError) $ map (\x -> traceShow x x) $ mergeNP 0 $ partition (\(x,_) -> x<0) $ zip series [1..] where mergeNP s (nss@((nVal,nIx):ns), pss@((pVal,pIx):ps)) | s < target = (pVal + s, pIx) : mergeNP (pVal + s) (nss,ps) | otherwise = (nVal + s, nIx) : mergeNP (nVal + s) (ns,pss) ``` [Answer] ## Python – 88 ``` def R(x,S,t): I=[0,0] while abs(S)>t: i=I[S>0]=I[S>0]+1 if x(i)*S>0:S-=x(i);print i, ``` `I` stores the indices for positive and negative numbers and to reduce the number of variables, I do not sum up to `0` until I reach `S`, but subtract from `S` until I reach `0`. I am not entirely sure whether this complies with the restrictions on the input. The used algorithm should be very nice for a stack-based language. ]
[Question] [ For those of you who have seen the popular daytime TV show [Countdown](http://en.wikipedia.org/wiki/Countdown_(game_show)), you will know that the contestants are given 9 randomly selected letters and must then find the longest word they can in 30 seconds. Your challenge is, given a string of 9 letters, to find the longest word that is an anagram of the largest subset of input letters, this means that you don't have to use all of the letters in the input string. Input/output can be stdin/stdout, or whatever the equivalent in your language is. ## Rules * Input will always a 9 letter string, all lower-case * You can use as few or as many of the letters from the input string * A word is allowed if it is found in the specified dictionary file, the dictionary file containing all the allowed words can be [found here](https://drive.google.com/file/d/0B6sWI3KhHyfQUVpBQnM3YXVkTms/edit?usp=sharing) (note: I didn't compile this, credit goes to the [github uploader](https://github.com/jes/cntdn/)). The file is is a .txt file which contains ~101,000 words with each word on a new line - approx 985kB. * You **must** use the dictionary file specified above, this is to ensure that all fairness across all the entries, e.g. so everyone has the same chance of finding the longest word. * You are allowed to manipulate the dictionary file in such a way that none of the words are edited in any way and no new ones are added, for example copying all the words to an array, making all words comma separated or copying the whole contents of the file to another file would be allowed. * Inputs may contain any number of vowels and consonants, e.g. 9 vowels or 8 consonants and 1 vowel * If there are multiple words with the same length, then you must output all of them (up to a limit of 5 - to prevent long lists of 5/6 letter words). Multiple words must be delimited, but this can be done in any way - comma, space etc. ## Test Cases Input: `mhdexaspo` Output: `hexapods, mopheads` Input: `iesretmng` Output: `regiments` Input: `cmilensua` Output: `masculine calumnies` Input: `floiufhyp` Output: `huffily puffily` Input: `frtuasmjg` Output: `frusta,jurats,jumars,tragus,grafts` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins! [Answer] # CJam, 51 bytes ``` Laeas$W%{1$f++}/:A;qN/{$aA&},{,~}$5<_0=,:L;{,L=},S* ``` CJam has no file I/O, so I opted to read the dictionary (converted to Unix format) from STDIN and read the string of letters as a command-line argument. ### Test cases ``` $ for w in mhdexaspo iesretmng cmilensua floiufhyp frtuasmjg > do cjam countdown.cjam $w < dictionary.txt > echo > done hexapods mopheads regiments calumnies masculine huffily puffily frusta gamuts grafts jumars jurats ``` ### How it works ``` La " Push T := [ '' ]. "; eas " Push the command-line argument (R) as a string. "; $W% " Sort its letters, then reverse. "; {1$f++}/ " Iterate over the letters; prepend them to copies of the strings in T. "; :A; " Save in A and discard. A contains all sorted substrings of R. "; qN/ " Read from STDIN and split at linefeeds. "; {$aA&}, " Filter; keep dictionary words D such that {sort(D)} ∩ A ≠ ∅. "; {,~}$ " Sort by negated word length. "; 5< " Keep only the first five words. "; _0=,:L; " Save the length of the first in L. "; {,L=}, " Filter; keep dictionary words D such that len(D) = L. "; S* " Separate by spaces. "; ``` [Answer] # Python 3, 171 bytes This requires the dictionary to be stored in a file named `w` with each word separated by spaces. Thanks to @wjandrea ``` s=input() z=lambda s,f:all(f>{c}and not f.remove(c)for c in s) l=[i for i in open('w').read().split()if z(i,set(s))] print([x for x in l if len(x)==max(len(x)for x in l)]) ``` ## Examples ``` gbahrcswn # Input ['branch', 'whangs'] # Output andapandamandarandaonsdf ['fandoms', 'pardons'] ``` [Answer] ## Python, 175 Instead of checking if each word in the dictionary is an anagram of the input, this program calculates all the anagrams of the input and looks for them in ths dictionary. If the dictionary is pre-sorted, this scales logarithmically, instead of linearly, with the size of the dictionary; it's probably also shorter :) ``` from itertools import* s=raw_input() n=9 J="".join while n: W=[J(p)for c in combinations(s,n)for p in set(permutations(c))if J(p)+"\n"in open("d")];n-=1 if W:print W[:5];n=0 ``` Assumes the dictionary is in a newline-terminated file named `d` in the current directory. Note that the golfed program is ridiculously slow since it re-reads `d` on every search. If you want to test it, add `D=set(open("d"))` at the beginning, and replace `open("d")` with `D`. [Answer] # JavaScript (ES6), 165 bytes I fear I may have gone down the wrong path with this one - it's pretty ugly! It works, but it's *very* resource intensive - I thought my machine might explode if I tried a combination of letters that only contained 6 (or fewer) letter words! I was so focused on getting this to work that I didn't leave myself much time to golf it; any help would be appreciated. In particular, I'm trying to figure out why, when I pass the initial string of letters as a single element array, thus allowing me to remove the 2 `split`s and the `join`, it throws an error on `y.replace()` Assumes the dictionary is already available in an array variable named `d`. ``` f=s=>(a=d.filter(w=>s.split`,`.some(n=>r(n)==r(w)),r=x=>[...x].sort()+"")).length?a.slice(0,5):s.length&&f(s.split`,`.map(y=>[...y].map(v=>y.replace(v,""))).join`,`) ``` --- ## Try It As I said, this solution is resource intensive so the following Snippet uses a limited dictionary, with only the words necessary for the 2 test cases I've included. If you're brave enough to try the *full* dictionary and your own input, you can do so [here](https://jsfiddle.net/petershaggynoble/sgk7Lru8/). ``` d=["dapping","genipap","huffily","kepping","knapped","peaking","puffily"] f=s=>(a=d.filter(w=>s.split`,`.some(n=>r(n)==r(w)),r=x=>[...x].sort()+"")).length?a.slice(0,5):s.length&&f(s.split`,`.map(y=>[...y].map(v=>y.replace(v,""))).join`,`) console.log(f("floiufhyp")) console.log(f("ingpepkad")) ``` ]
[Question] [ In the color spelling game, you are shown a list of color names, but rather than reading the words that are written, you have to say the name of the color of the letters. The game is over as soon as you say the wrong color, and the player who spelled the most words correctly wins. To make the game more challeging, each word is written on a different background color. And here is your challenge: Write a program that creates a color spelling game. * Print every second or so the name of a color. * Use different colors for the background and the foreground. * The name of the color you print should be different than both the background and the foreground. * Do not repeat the same color name, foreground or background color in two consecutive rows. It's still ok to reuse the same color in succession for different purposes, like printing the word "red" after a word on a red background. * Choose each color (pseudo)randomly from a palette of at least 6 colors. * Use a programming language of your choice. Here is my solution for JavaScript, change as you like: <http://jsfiddle.net/xb8rqsbr/> This is a code golf challenge, so keep your code short. Have fun! [Answer] # BBC Basic, ~~187~~ 176 ASCII characters, tokenised filesize ~~155~~ 140 Download emulator at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html> Saved some characters: instead of using MOD to always generate random numbers that differ than the previous value, I simply generate any number and perform a check instead. ``` b=0f=0w=0REPEATc=b g=f x=w REPEATb=RND(6)f=RND(6)w=RND(6)UNTIL(b-f)*(f-w)*(w-b)*(b-c)*(f-g)*(w-x)VDU17,b+128,17,f:PRINTMID$("Red LimeGoldBluePinkAqua",w*4-3,4):WAIT 99UNTIL0 ``` I used the original BBC Basic 3-bit colour codings, which are based on 1's bit=Red, 2's bit=Green, 4's bit=Blue. I renamed Yellow as `Gold`, Magenta as `Pink` and Green as `Lime` (justifiable given the shade produced) in order to shorten colour names. I also renamed Cyan as `Aqua` just because. Therefore I use colours 1 to 6 from the 3-bit scheme. I exclude 0=black and 7=white (a very light grey, as the full white belongs to the extended 16-colour set in which the 8`s bit refers to brightness.) ``` b=0 f=0 w=0 :REM initialise "old" values for background, foreground and word. REPEAT c=b g=f x=w :REM c,g and x contain the old values for background, foreground and word. REPEAT b=RND(6)f=RND(6)w=RND(6) :REM pick random numbers between 1 and 6 UNTIL(b-f)*(f-w)*(w-b)*(b-c)*(f-g)*(w-x) :REM until all colours are different from each other and their previous values VDU17,b+128,17,f,12 :REM VDU 17 sets colour, using the 128's bit to say if it is foreground or background. VDU 12 clears the screen. PRINTMID$("Red LimeGoldBluePinkAqua",w*4-3,4) :REM MID$ picks the colour. The string is considered 1-indexed. WAIT 99 :REM wait 99 centiseconds UNTIL0 ``` **Output** The first few images show the program as written, running in screen mode 6. The bottom image shows the program with the `,12` removed so that the screen is not cleared in between word printings. That way it is easier to verify that the colours comply with the rules. ![enter image description here](https://i.stack.imgur.com/gFRZl.png) [Answer] # Algoid - 349 Although Algoid isn't the best for golfing, it's perfect for these types of challenges. ``` set x=math.random;set m;while(true){set c=array{{"black",0},{"brown",6},{"blue",8},{"green",10},{"red",12},{"yellow",14},{"white",15}};set l=c.length();algo.clear();algo.hide();set b=0;set t=0;set w=0;while(b==t||w==t||b==w){b=c[x(l-1)];t=c[x(l-1)];w=c[x(l-1)]}if(m!=w){algo.setColor(t[1]);algo.setBgColor(b[1]);algo.text(w[0]);util.wait(2000);m=w}} ``` ## Example outputs ![](https://i.stack.imgur.com/Bt9xd.jpg) ![](https://i.stack.imgur.com/3fJop.jpg) [Answer] ## JavaScript ES6 - 163 Test on Firefox console. I'll try golfing it more later. ``` setInterval(s=>{c="Red0Lime0Gold0Blue0Pink0Aqua".split(0);r=x=>c.splice(~~(Math.random()*9)%c.length,1);console.log('%c'+r(),'background:'+r()+';color:'+r())},999) ``` [Answer] ## Ruby 165 ``` x,y,z=9 loop{f,b,t=(0..5).to_a.sample 3 x!=f&&y!=b&&z!=t&&(puts %W{\e[0 \e[3#{f} \e[4#{b} #{%w/black red green brown blue magenta/[t]}}.join ?m sleep 1 x,y,z=f,b,t)} ``` ### Screenshot: ![Screenshot](https://i.stack.imgur.com/pzMA7.png) [Answer] # Python - 260 Not amazing, but it works ``` from random import randint ps = ['pink','green','yellow','red'];cs=['\033[94m','\033[92m','\033[93m','\033[91m'] print "1 pink, 2 green, 3 yellow, 4 red" while True: c=randint(0,3);p=randint(0,3);g=raw_input(cs[c]+ps[p]+'\033[0m') if int(g)!=c+1: exit() ``` ]
[Question] [ Given a number, starting with 1, create new numbers (children) by taking the last digit, n, and concatenating 1 through n+1. This seems to be a much better explanation of the sequence [A071159](http://oeis.org/A071159). > > Integers whose decimal expansion start with 1, do not contain zeros and each successive digit to the right is at most one greater than the previous. > > > 1, 11, 12, 111, 112, 121, 122, 123, 1111, 1112, 1121, 1122, 1123, 1211, 1212, 1221, 1222, 1223, 1231, 1232, 1233, 1234, 11111, 11112, ... > > > Personally I find the description for the sequence rather unhelpful, and find it is easier to understand with a graph. ``` 1 11-------------------------------------12 111----112 121---------122----------123 1111-1112 1121-1122-1123 1211-1212 1221-1222-1223 1231-1232-1233-1234 ``` I find the graph rather interesting as it is very self-repeating. For instance, the left-most node on a branch is always identical to the root node. Might be easier to see on [this graph](https://i.stack.imgur.com/EjpRZ.png). # Challenge Submit a solution that can output the nth item of sequence A071159. # Rules Your submission should be able to calculate any item before number 23713. A071159(23713) is the first time a `10` would appear as a single digit (12345678910; comma-separated 1,2,3,4,5,6,7,8,9,10). [Answer] ## GolfScript (29 chars) ``` ~([1]{.{.10*)\10%{.)}*}%|}9*= ``` This is a pretty naïve implementation, although reasonably fast. ``` ~( # Evaluate input, decrement to get a 0-based index [1] # Initial row of tree { # Loop: stack is the first n rows of the tree as an array . # Duplicate the array { # Map: extend each element of the array into its children .10*) # Get the first child; stack is rows x 10x+1 \10% # How many more children does x have? {.)}* # Those children are found by successive incrementation }% # End map | # Add the new unique elements (i.e. the new bottom row) to the rows }9* # Repeat 9 times, so that the array has 23713 correct values and one incorrect = # Array lookup ``` [Answer] # Python 2 (83) (86) ``` r=[1] exec"r=[1]+[i+w*10for w in r for i in range(1,w%10+2)];"*9 print r[input()-1] ``` Explanation to come. A completely different approach of counting up an testing for membership in the sequence (87 chars). Take ridiculously long for larger numbers, ``` n=0 k=input() while k:n+=1;k-=all(0<int(b)<2+int(a)for a,b in zip('0'+`n`,`n`)) print n ``` [Answer] # JAVA (146) I know I'm not winning this, but oh well: ``` public class a{public static void main(String[]a){float b=Float.parseFloat(a[0]);float c=1;for(int i=2;i<=b;i++)c*=(i+b)/i;System.out.print(c);}} ``` Just straightforward from Wikipedia, any tips for further golfing this will be appreciated. [Answer] ## Powershell (136) ``` $n=Read-Host;$x=,'1';$a=1;While($x.length-lt$n){$b=[int]$x[$a-1].Substring($x[$a-1].length-1);1..($b+1)|%{$x+=$x[$a-1]+$_};$a++}$x[$n-1] ``` Probably some wasted characters here, but I'm still learning. $a traverses the list as it's being built (each level of the tree). $b takes the last digit of the current item, then the loop after that adds on 1 to $b+1 to the end of the current item and adds it to the array $x. Loop is a bit inefficient, as the $n-1 index is necessary because it doesn't always stop on the nth number of the sequence that you want. But hey, it's my first draft. And it replicated the correct sequence output based on the input [here](http://oeis.org/A071159/b071159.txt). Also an input of 23713 produces an output of 12345678910. [Answer] ## Haskell (73) ``` c=1:((\n->[10*n+d|d<-[1..n`mod`10+1]])=<<)c;main=readLn>>=print.((0:c)!!) ``` And ungolfed: ``` step n = [ 10*n + d | d <- [1 .. lastDigit+1] ] where lastDigit = n `mod` 10 soln = 1 : concatMap step soln main = do n <- readLn let nthTerm = soln !! (n - 1) print nthTerm ``` soln is a list containing the entire A071159 sequence. The step function is not very interesting, just a straightforward list comprehension that takes a number to the list of its children in the OP's tree. The main function's only trick is to do 1-based indexing of [1,11,12,...] by using 0-based indexing on [0,1,11,12,...], saving a character. The real fun is in the recursive definition of soln, which does the breadth-first traversal of the OP's tree. A couple characters are saved by replacing concatMap with its generalization =<<. ]
[Question] [ You are locked in a massive fortress, slowly starving to death. Your guards inform you that there is food in the fortress, and even tell you where it is and provide a map of the building. However, you are not sure that you can actually reach the food, given that the every door is locked, and every room is its own labyrinth. Are you able to reach the food? If you're in the same room, you should try. If you're not in the same room, then you might as well stay put, preserving your strength in case help from the outside world comes. # Input Two arrays: 3 coordinates of where you are, and 3 coordinates of where the food is. (Both are 0-based) :Optional: an array of three numbers, indicating the size of the following fortress in each dimension. A three dimensional array of the fortress, where each point in the array is either 1/true (if that point is a wall) or 0/false (if the point is empty). The array is a rectangular prism, and there is no guarantee that the structure follows the laws of physics. (Thus, the bottom floor might be completely empty.) The place where you are and the place where the food is both have a 0/false. # Output Are the two points in the same room, unseparated by a wall? Note that you can not move through a diagonal. # Format You may write a program or a function. The input may be through STDIN, command line or function arguments, or reading from a file. If you choose a text-based input (like STDIN) you may use any delimiters to help your program parse the input. The output may be through STDOUT or the function result. You can output/return "true"/"false", 0/1, or the like. # Examples In these examples, I put a Y where you are, and a F where the food is. This is just to help you understand the examples; in the actual input they would be 0/false. ## Input ``` [0 0 1] // You are at x = 0, y = 0, z = 1 [1 2 2] // The food is at x = 1, y = 2, z = 2 [[[0 0 0] // z = 0, y = 0 [0 0 0] // z = 0, y = 1 [1 1 1]] // z = 0, y = 2 [[Y 0 0] [0 0 0] // z = 1 [1 1 1]] [[0 0 0] [1 1 0] // z = 2 [0 F 0]]] ``` ## Output True. (The places are connected. You can move from [0 0 1] > [2 0 1] > [2 0 2] > [2 2 2] > [1 2 2].) ## Input ``` [3 0 1] [1 1 0] [4 2 2] // If you want, you can include this in the input, to indicate the fortress's size [[[0 1 0 0] // z = 0, y = 0 [0 F 1 0]] // z = 0, y = 1 [[0 0 1 Y] [0 1 0 0]]] ``` ## Output False. (There are two rooms. Your room includes [2 0 0], [2 1 1], [3 0 0], [3 0 1], [3 0 1], and [3 1 1]. The food's room includes the other empty spaces. Note that a wall of 1's divides the fortress in half. # Winning criterion Code golf. Shortest code for your function/program wins. [Answer] # Python 2.x - 177 168 167 bytes Basic flood fill to kick the game going. Requires the dungeon size. ``` f,(a,b,c),(w,h,d),p=input() def l(x,y,z): if w>x>-1<y<h>0<=z<d and p[z][y][x]<1:p[z][y][x]=2;[(l(x+i,y,z),l(x,y+i,z),l(x,y,z+i))for i in-1,1] l(*f) print p[c][b][a]>1 ``` Examples: ``` Input: [0,0,1],[1,2,2],[3,3,3],[[[0,0,0],[0,0,0],[1,1,1]],[[0,0,0],[0,0,0],[1,1,1]],[[0,0,0],[1,1,0],[0,0,0]]] Output: True Input: [3,0,1],[1,1,0],[4,2,2],[[[0,1,0,0],[0,0,1,0]],[[0,0,1,0],[0,1,0,0]]] Output: False ``` Ungolfed code: ``` (e,f,g),(a,b,c),(w,h,d),field=input() def fill(x,y,z): if 0<=x<w and 0<=y<h and 0<=z<d and field[z][y][x]<1: field[z][y][x]=2 fill(x+1,y,z) fill(x-1,y,z) fill(x,y-1,z) fill(x,y+1,z) fill(x,y,z-1) fill(x,y,z+1) fill(e,f,g) print field[c][b][a]==2 ``` [Answer] ## Mathematica, 173 bytes ``` f=(v=#;(v=ReplacePart[v,Reverse[#+1]->#2])&@@@{{#3,2},{#4,3}};VertexConnectivity[VertexDelete[GridGraph[#2],Join@@(l=Flatten@v)~(s=Position)~1],(h=s[l,#][[1,1]]&)@2,h@3]>0)& ``` This defines a function `f` which can be called like ``` f[{{{0,1,0,0},...}, {4,2,2}, {3,0,1}, {1,1,0}] ``` using your second example. Ungolfed: ``` f = ( v = #; (v = ReplacePart[v, Reverse[# + 1] -> #2]) & @@@ {{#3, 2}, {#4, 3}}; VertexConnectivity[ VertexDelete[ GridGraph[#2], Join @@ (l = Flatten@v )~(s = Position)~1 ], (h = s[l, #][[1, 1]] &)@2, h@3] > 0 ) & ``` I'm simply creating a grid graph for the entire building, then delete all walls (and their adjacent edges) from the graph and then check that the two vertices are connected. [Answer] ### GolfScript, 93 characters ``` ~[[]]@{,`{{1$+}%\;~}+%}/:A[\{{~}/}%]zip{~!*}%:S;]1/~{{3,{)1$/.())+\+\()(+\+}%{[]*}/}%S&}A,*&, ``` The code expects the input as specified above (including the fortress' dimensions) on STDIN. The result is `1` if food is reachable and `0` otherwise. Try the code [online](http://golfscript.apphb.com/?c=OyJbMCAwIDFdClsxIDIgMl0KWzMgMyAzXQpbW1swIDAgMF0KICBbMCAwIDBdCiAgWzEgMSAxXV0KIFtbMCAwIDBdCiAgWzAgMCAwXQogIFsxIDEgMV1dCiBbWzAgMCAwXQogIFsxIDEgMF0KICBbMCAwIDBdXV0iCgp%2BW1tdXUB7LGB7ezEkK30lXDt%2BfSslfS86QVtce3t%2BfS99JV16aXB7fiEqfSU6UztdMS9%2Be3szLHspMSQvLigpKStcK1woKSgrXCt9JXtbXSp9L30lUyZ9QSwqJiwK&run=true). [Answer] # Javascript (E6) 123 ~~128 132 140 167 286 344~~ ~~First try. Simple fill, not recursive, fortress size not needed. *Must simplify multidimensional array handling (90 chars!!).*~~ **Edit** Recursive fill, no need to know the fortress dimensions, should work even for irregular shapes. **Edit** Tip***s*** by TheRare to shorten the recursive call & golf more **Edit** Contribution by MT0, cut same () and use exact equal **Edit** Contribution by nderscore, multidimensional array handling (learned sth new again) **Edit** With a clever trick, nderscore bring the food check back inside the loop, where it belongs. Now returning a boolean, 'some' is more fit than 'map' (and shorter) ``` A=(Y,F,M)=>(S=(x,y,z)=>(t=(M[z]||0)[y]||0)[x]-1&&[x,y,z]+''==F|[-1,t[x]=1].some(d=>S(x+d,y,z)|S(x,y+d,z)|S(x,y,z+d)))(...Y) ``` **Usage** ``` A([0,0,1],[1,2,2], [[[0,0,0],[0,0,0],[1,1,1]], [[0,0,0],[0,0,0],[1,1,1]], [[0,0,0],[1,1,0],[0,0,0]]]) ``` Return 1 ``` A([3,0,1],[1,1,0], [[[0,1,0,0],[0,0,1,0]],[[0,0,1,0],[0,1,0,0]]]) ``` Return 0 **Ungolfed** ``` A=(Y,F,M)=> (S=(x,y,z)=> (t=(M[z]||0)[y]||0)[x]-1 // NaN==out,-1==open,0==wall or visited && [x,y,z]+''==F // compare with food position converting to string | [-1,t[x]=1] // mark as visited, then recurse popping out the return value if true .some(d=>S(x+d,y,z)|S(x,y+d,z)|S(x,y,z+d)) )(...Y) ``` ]
[Question] [ # Introduction From [Esolangs.org](http://esolangs.org/wiki/Pi) : > > **Pi** is based on the brainfuck language and uses the same instructions as it. Pi works by calculating pi digits and introducing errors in some random digits of them, encoding obfuscated brainfuck instructions. > Instructions are encoded as below: > > > > ``` > '>' '<' '+' '-' '.' ',' '[' ']' > 0 1 2 3 4 5 6 7 8 > > ``` > > But, as we need to identify which pi digits are incorrect, we move each instruction in the table one position to the right starting at the position that is initially over the correct pi digit that is where we are inserting the instruction. > For example, if the pi digit in the position we are inserting the instruction is 4, the table would be moved as follows: > > > > ``` > '>' '<' '+' '-' '.' ',' '[' ']' > 0 1 2 3 4 5 6 7 8 9 > > ``` > > Then the instruction would be converted to a digit that would be inserted replacing the correct digit. > > > # Brainfuck explanation Brainfuck is not very difficult. Imagine an infinite byte array, initialized to zero, and a pointer on a value of this array. * `>` increments the pointer * `<` decrements the pointer * `+` increments the pointed value * `-` decrements the pointed value * `.` prints the pointed value * `,` sets the pointed value (value is taken from stdin) * `[` defines the beginning of a loop, this loop is entered if current value is not zero * `]` is the end of the loop # Objective In any language, write an interpreter for the esoteric **Pi** language. * Correct pi digits must be taken from `http://pastebin.com/raw.php?i=gUbdbzLr`, no URL shortener allowed. (JavaScript is allowed to run from pastebin.com domain but the full URL must appear in the code) * Only `[]<>+-.` equivalent have to be handled, you can ignore inputs (`,` equivalent) * The input string length will be below 100,000 * You can write a full program and take the input string from stdin, or write a function and take the input string from argument. * You don't have to support *inifinite* array (100 bytes is fine), but you have to support negative pointers. * In case of overflow, wrap the value : `-1 => 255` and `256 => 0`. # Examples ``` 3.14159265358979323842264332327250288412716939927513582397492459230721640628220899867803480534311206298214838653322233664709084463955358323172235940832848311725028410370193853110525964460294895293032196422880097562591344612147514823378178346528120090214562856642346134861345532264821332360736034914137372428700663631558417448152392396222925459170536432789259026051133013014882046252138214295194153160243205227036275959395309212613732192261379310211855807440237946274952735182575273489122743848301134912983467436444065634308652133494633522473749030217386093370277033921317659317670238267581846066440 ``` This input value must return `Hello World!` ``` 3.14152322358878323222264326032220288236031386837182584807480228230223643448624338864343482343244432222334808651322320664708322260855054333172535843232848113435028410274433852444334335 ``` Taken from [here](https://codegolf.stackexchange.com/a/21857/16120) and converted to Pi, outputs `6*7=42` (don't forget to upvote this awesome answer) ``` 3.1415826535887832384626433832785028846644334334334433443333333344433433434334433333434470302114801731130077382277380418061543333433343344443434333434433344433344334443443702032238007311300810737227041222326030211380073113008107373170312223223233332323222222222322232222332222324738807122323233223233222322223322322322223222232332332443434334343434352222232232233332232232222332222332225222232232332322223223232222222232223233223344343443443344434433334333344333343333334343333343433344433434344443334433443344432232222223223332222222223322223232333222232222332232223323223223222232222222322222243434444443335434534343343433333344343333333434343434333443333343444433343444333333334353232233222223222322233322223333323332232223222323222322322222232322232322323335333333334453423522233222232232344334433335722222764333434443343444434344333334434343444334348644444433433343333333444434343443434333334334443704811648806122222233222232222232222222222232222232222232233444433433444443442222333222323322333222223223223333225222223222222223222232322223232332233222332253333333343443333443344333443334343334443433333334343334343333343433444433343433422223223222232222222222222323223232332322332233223322222323332222232322222322233322354343343333335333533333433333334334333333433334434333433334434333334334333344344443334442223233322233233222223323223223233222333222232233222222233222222223222323223234434333443443432422232223322232353344433434654434444334732222222324737038217381103711688856808272107 ``` This one is taken from my answer [here](https://codegolf.stackexchange.com/a/28696/16120) and can be used to test input if you decide to handle it. # Winning criteria This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score wins ! ### Score computation : * 1 byte = 1 point * +100 points if you choose to take the pi digits from a local file. * -50 points if you handle inputs (`,`) too (single ASCII character per input; if your language does not support STDIN, prompt for input once and then read a character at a time from that input). * -100 points if you compute the pi digits yourself. [Answer] # PHP, 532 - 50 = 482 ``` <?php $P=file_get_contents("http://pastebin.com/raw.php?i=gUbdbzLr");$I=trim(fgets(STDIN));$i=2;$l=strlen($I)-1;$A=$R=array_fill(0,999,0);$a=$r=0;while($i<$l){$X=intval($I[$i]);$Z=intval($P[$i]);if($X==$Z){$i++;continue;}$O=($X>$Z)?$X-1:$X;switch($N[$X]){case 0:$A[$a]=($A[$a]+1)%256;break;case 1:$A[$a]-=$A[$a]==-1?-256:1;break;case 2:$a+=$a==998?-998:1;break;case 3:$a-=$a==0?-998:1;break;case 4:echo chr($A[$a]);break;case 5:$A[$a]=fgetc(STDIN);break;case 6:$R[$r++]=$i;break;case 7:$A[$a]==0?$R[$r--]=0:$i=$R[$r-1];break;}$i++;} ``` `allow_url_fopen` should be 1. Run this in command line like `php 28718.php`, because it takes input from STDIN. Array size is 999. It handles negative pointers, overflow, and `,`. So I can get -50 points. Tested with the code above, and ``` 3.14159265358979323846262338227250282419716929927510782090492459233781640638623899262833482534311206728234808621328230264709314460935058223872535941812844111745008410220193853110552964262292895493028192443881097266523344712047564223378672316522123190934562856693346034261045422624821339160726424914827372058703665631558217288153092396282225439171532436789559536003133023024882044652108412695192151163943305737036565959095309212611738393261379210511254207426237992274952735388572272489222793813301174910983367536244265624308632129494679502473713070247986034370277453921711629317375838467480846766440513202056822724526351082178577132275778260917362717672046844093122295323014624928531103079228968920892354501995011202902196586203421812981362477473130996451870724134999399337297803995104973473281603634859504445345544690330263252250825304468003522193158817101 ``` from <http://blog.progopedia.com/2011/mar/14/pi-programming-languages/>. Can I have more test code? ## Readable ``` <?php // get pi digits $P = file_get_contents("http://pastebin.com/raw.php?i=gUbdbzLr"); // input $I = trim(fgets(STDIN)); $i = 2; $l = strlen($I)-1; // bf init $A = $R = array_fill(0, 999, 0); $a = $r = 0; while($i < $l) { $X = intval($I[$i]); $Z = intval($P[$i]); if($X == $Z) { $i++; continue; } // operations $O = ($X > $Z) ? $X - 1 : $X; // bf process switch($O) { case 0: $a += $a == 998 ? -998 : 1; break; case 1: $a -= $a == 0 ? -998 : 1; break; case 2: $A[$a] = ($A[$a] + 1) % 256; break; case 3: $A[$a] -= $A[$a] == -1 ? -256 : 1; break; case 4: echo chr($A[$a]); break; case 5: $A[$a] = fgetc(STDIN); break; case 6: $R[$r++] = $i; break; case 7: if($A[$a] == 0) $R[$r--] = 0; else $i = $R[$r-1]; break; } $i++; } ``` [Answer] **Update 2 (on hold)** This code does not accommodate nested loops. Under revision. Mathematica: 415 (bytes) - 100 (pi -- apparently this counts) - 50 (input) = 265 Handles overflow, only prompts user once when first `,` is encountered. ``` v@u_ := ( f = RealDigits[##][[1]] &; q@x_ := q@x = 0; r@x_ := q@x~Mod~256; z = Length; n = Input; k = StringSplit[#, ""] &; i = k["><+-.,[]"][[If[#1 < #2, #1 + 1, #1]]] & @@@ Select[Transpose@{d = f[u], f[Pi, 10, z@d]}, ! Equal @@ ## &]; j = 1; p = 1; y = 1; w = 1; FromCharacterCode@ Last@Reap@ While[j <= z@i, Switch[i[[j]], "[", l = j, "]", If[r@p != 0, j = l - 1], ">", p++, "<", p--, "+", q[p]++, "-", q[p]--, ".", Sow[r@p], ",", If[y-- == 1, c = k@ToString@n[]]; q@p = ToCharacterCode[c[[w++]]][[1]]]; j++]); ``` **Original** Mathematica: 439 bytes - 50 (input) - 100 (pi calc) = 289. Updated to accept interactive input at start. Readable: ``` in = StringSplit["><+-.,[]", ""][[#]] &; c = Input[]; s1 = Cases[ SequenceAlignment[ (rd = RealDigits)[ N[Sum[(i!)^2*2^(i + 1)/(2 i + 1)!, {i, 0, Infinity}], StringLength@c - 1]][[1]], rd[ToExpression@c][[1]]] /. {{r_}, {w_}} :> in@If[r > w, w + 1, w], _String] //. {h___, "[", b___, "]", t___} :> {h, {b}, t}; p = 1; rt[x_] := rt[x] = 0; sc[l_] := Scan[Switch[#, ">", p++, "<", p--, "+", rt[p]++, "-", rt[p]--, ".", Sow[rt[p]], ",", Input[], lp_List, While[rt[p] != 0, sc[#]]] &, l]; FromCharacterCode@Last@Reap@sc@s1 ``` > > {"Hello World! > "} > > > Dense: ``` in=StringSplit["><+-.,[]",""][[#]]&;c=Input[];s1=Cases[SequenceAlignment[(rd=RealDigits)[N[Sum[(i!)^2*2^(i+1)/(2 i+1)!,{i,0,Infinity}],StringLength@c-1]][[1]],rd[ToExpression@c][[1]]]/.{{r_},{w_}}:>in@If[r>w,w+1,w],_String]//.{h___,"[",b___,"]",t___}:>{h,{b},t};p=1;rt[x_]:=rt[x]=0;sc[l_]:=Scan[Switch[#,">",p++,"<",p--,"+",rt[p]++,"-",rt[p]--,".",Sow[rt[p]],",",Input[],lp_List,While[rt[p]!=0,sc[#]]]&,l];FromCharacterCode@Last@Reap@sc@s1 ``` [Answer] ## Mathematica, 362 bytes - 100 (π) = 262 ``` f=(c=Which[#>#2,#,#<#2,#+1,0<1,9]&@@@Thread@{d=(r=RealDigits[##][[1]]&)@#,r@@{Pi,10,(g=Length)@d}};b=0&~Array~100;l=b[[#]]&;p=50;i=0;j={};While[++i<=g@c,{++p&,--p&,++b[[p]]&,--b[[p]]&,j~AppendTo~FromCharacterCode@l@p&,0&,If[l@p>0,j~PrependTo~i,d=1;While[d>0,Switch[c[[++i]],7,++d,8,--d]]]&,If[l@p>0,i=j[[1]],j=Rest@j]&,0&}[[c[[i]]]][];b[[p]]=l@p~Mod~256];j<>"")& ``` I didn't look at the other Mathematica solution at all to write this. If I hardcode the input variable (which the other answer currently does), I'll save another 5 characters. This snippet defines a function `f` though, which takes the input as a string, like ``` f = (c = Which[# > #2, #, # < #2, # + 1, 0 < 1, 9] & @@@ Thread@{d = (r = RealDigits[##][[1]] &)@#, r @@ {Pi, 10, (g = Length)@d}}; b = 0 &~Array~100; l = b[[#]] &; p = 50; i = 0; j = {}; While[++i <= g@c, { ++p &, --p &, ++b[[p]] &, --b[[p]] &, j~AppendTo~FromCharacterCode@l@p &, 0 &, If[l@p > 0, j~PrependTo~i , d = 1; While[d > 0, Switch[c[[++i]], 7, ++d, 8, --d ] ] ] &, If[l@p > 0, i = j[[1]], j = Rest@j] &, 0 & }[[c[[i]]]][]; b[[p]] = l@p~Mod~256 ]; j <> "") & ``` ]
[Question] [ This is a pure code-golf question. **Input:** A non-negative integer n **Output:** Sum of the indices of the second least significant set bit in the binary representation of the integers 0...n. If the number doesn't have two set bits then the contribution to the sum should be zero. Your code should be runnable on a standard linux machine using free software and shouldn't take more than n+1 seconds to run. Sample answers for `n` from `0..20` ``` 0 0 0 1 1 3 5 6 6 9 12 13 16 18 20 21 21 25 29 30 ``` Here is some sample ungolfed python code. ``` def get_2nd_least_bit(x): sum = 0 for i in range(0,x.bit_length()): sum += (x >> i) & 1 if sum == 2 : return i return 0 for x in xrange(20): print sum(get_2nd_least_bit(i) for i in xrange(x+1)), ``` [Answer] # k [21 chars] ``` {+/{(&|0b\:x)1}'!x+1} ``` ### Example ``` {+/{(&|0b\:x)1}'!x+1}[3] 1 {+/{(&|0b\:x)1}'!x+1}[7] 6 {+/{(&|0b\:x)1}'!x+1}[10] 12 {+/{(&|0b\:x)1}'!x+1}[500] 1410 ``` [Answer] ## GolfScript (31 chars) ``` ,{)2base-1%.,,\`{=}+,1=}%0+{+}* ``` This takes input on the stack and leaves output on the stack. [Online demo](http://golfscript.apphb.com/?c=MTIsewogICAgLHspMmJhc2UtMSUuLCxcYHs9fSssMT19JTAreyt9Kgp9JXA%3D) which wraps it in a loop to output the first 12 values. That implementation does the obvious thing of computing the base-2 representation of the integers in range. A more interesting approach, which sadly I haven't been able to golf as far, is to analyse the sequence. It's a sum of indices: let `i2(n)` be the index of the second LSB of `n`. We have `i2(2^x) = 0` (given as a special case). What can we say about the values which `i2` takes between `2^x` and `2^(x+1)`? * Case 1: `2^x < k < 2^x + 2^(x-1)`. Then `k ^ (2^x + 2^(x-1)) = k - 2^(x-1)`. If `i2(k - 2^(x-1)) < x-1` then `i2(k) = i2(k - 2^(x-1))`; otherwise `i2(k) = x = 1 + i2(k - 2^(x-1))`. * Case 2: `k = 2^x + 2^(x-1)`. Obviously `i2(k) = x` since there are two bits set. * Case 3: `2^x + 2^(x-1) < k < 2^(x+1)` has bit `x-1` set and at least one less significant bit set, so `i2(k) = i2(k - 2^x)`. In other words: the sequence of indices between consecutive powers of two can be found by splicing together three sequences: the previous sequence under the substitution `s/x-1/x/`; the sequence `[x]`; and the previous sequence unmodified. * `[]` * `[] + [1] + [] = [1]` * `[2] + [2] + [1] = [2 2 1]` * `[3 3 1] + [3] + [2 2 1] = [3 3 1 3 2 2 1]` * `[4 4 1 4 2 2 1] + [4] + [3 3 1 3 2 2 1] = [4 4 1 4 2 2 1 4 3 3 1 3 2 2 1]` * etc. This leads to (40 chars) ``` ([]{,2$<}{..0+0=:x+{.x=+}%\+}/1,*<0+{+}* ``` (Note for GS aficionados: a rare use for unfold!) [Answer] ## J (and mathematics), way too much (aka. 45 chars), cubic memory and terrible runtime ``` +/,(*v>(2&^*1+a*2:)+/2^i.)"0]a=.i.v=.".1!:1]1 ``` If I wanted to aim for length, I could of course do it the obvious, straightforward way and get something considerably shorter... however, I found it more interesting to investigate the properties of "index of second least significant set bit". The J program above is an instance of the formula derived below. The idea is to build a huge table of numbers per bit index, then filter out those below the number we seek, then multiply by the bit index, then sum it all up. --- So, I started with the slightly different case "index of *the* least significant set bit" (LSSB), because it's always best to start simple when looking for patterns... I plotted the index of the LSSB for numbers [0..40]: ``` 1111111111222222222233333333334 01234567890123456789012345678901234567890 -0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 = 2k + 1 1 1 1 1 1 1 1 1 1 1 = 4k + 2 2 2 2 2 2 = 8k + 4 3 3 3 = 16k + 8 4 5 ``` (Here, `-` means N/A.) Well, that's a very obvious pattern. Joining the cases together we get `2^v * (2k + 1)` for row `v`, for integers `k` (or, `2^v * m` for odd `m`, if you prefer). This is sequence [A007814](http://oeis.org/A007814) in OEIS. Okay, so, back to our real case of the *second* least significant set bit (2LSSB). Let's do a similar plot for this case and see if there's any pattern here too, and if so, how it relates to the previous pattern. ``` 1111111111222222222233333333334 01234567890123456789012345678901234567890 --- - - - - 1 1 1 1 1 1 1 1 1 1 22 22 22 22 22 33 3 33 3 44 4 4 55 5 5 ``` Well... huh. That looks a bit strange, but there's still some sort of repetition going on. Let's take a look at what numbers get assigned which indices. ``` 0: 0 1 2 4 8 16 32 ... 2^k 1: 3 7 11 15 19 23 27 31 35 39 ... 4k + 2 + {1} = 2*(2k + 1) + 2^{0} 2: 5 6 13 14 21 22 29 30 37 38 ... 8k + 4 + {1,2} = 4*(2k + 1) + 2^{0,1} 3: 9 10 12 25 26 28 ... 16k + 8 + {1,2,4} = 8*(2k + 1) + 2^{0,1,2} 4: 17 18 20 24 ..? 32k + 16 + {1,2,4,8} = 16*(2k + 1) + 2^{0,1,2,3} 5: 33 34 36 40 ..? 64k + 32 + {1,2,4,8,16} = 32*(2k + 1) + 2^{0,1,2,3,4} ``` Okay, yeah, definitely a pattern. The general case here is `2^v * (2k + 1) + 2^j`, `j < v`. While we're at it, let's do one more just to see how this all generalises for the n:th least significant set bit. ``` 111111111111111111111111111111 111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999000000000011111111112222222222 0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789 01 012 4 012 4 8 16 012 4 8 16 32 ... 012 012 4 8 012 4 8 16 32 ... ------- --- - --- - - --- - - - --- - - - - = 2^k + 2^l, l < k 0 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 = 8*k + 4 + {3} 2 3 33 3 33 3 33 3 33 3 33 3 33 3 33 3 33 = 16*k + 8 + {3,5,6} 3 4 44 44 4 4 44 44 4 4 44 44 4 4 44 44 4 = 32*k + 16 + {3,5,6,9,10,12} 4 5 55 55 5 55 5 5 5 55 55 5 55 5 5 = 64*k + 32 + {3,5,6,9,10,12,17,18,20,24} 5 6 66 66 6 66 6 6 66 6 6 6 = 128*k + 64 + {3,5,6,9,10,12,17,18,20,24,...} 6 ``` Phew. 40 digits didn't cut it for finding patterns here, so I had to extend it a bit. Sorry about that horizontal scrollbar. Here's the table to the far right again, to spare you from having to scroll back and forth. ``` 2^k + 2^l, l < k 0 1 8*k + 4 + {3} 2 16*k + 8 + {3,5,6} 3 32*k + 16 + {3,5,6,9,10,12} 4 64*k + 32 + {3,5,6,9,10,12,17,18,20,24} 5 128*k + 64 + {3,5,6,9,10,12,17,18,20,24,...} 6 ``` Huh. That's weird, what are *those* numbers? They're certainly not powers of two... maybe I should've been able to guess it from the earlier two tables, but instead I went to OEIS and found it's actually the set of [sums of two distinct powers of two](http://oeis.org/A018900). So it seems like a qualified guess to generalise this by taking the sum of `n` distinct powers of two for the index of the n:th least significant set bit. All in all, the final expression looks [like so](http://mathb.in/13535): ![Screenshot of expression](https://i.stack.imgur.com/dVamz.png) [Answer] ## Ruby, 64 Here's a regex-based solution. I hope it's correct, the spec could use some test cases... ``` p (0..gets.to_i).inject{|s,n|n.to_s(2)=~/10*10*$/?s+$&.size-1:s} ``` Examples: ``` >echo 3 | ruby sum-of-indices.rb 1 >echo 7 | ruby sum-of-indices.rb 6 >echo 10 | ruby sum-of-indices.rb 12 >echo 500 | ruby sum-of-indices.rb 1410 ``` [Answer] ## **Postscript**, 179 Not to compete in golf, just for fun. I like it, that `1`'s indexes (which are *post-match* lengths in a string scanned left to right starting with *most* significant bits) are accumulated on stack and so to find second least significant, one operand is popped, next added to sum, the rest are discarded (stack cleared). ``` /s 0 def 0 1(%stdin)(r)file token pop {2 32 string cvrs mark exch {(1)search{pop pop dup}{pop exit}ifelse}loop counttomark 2 ge{pop length s add/s exch def}if cleartomark}for s = ``` Un-golfed, and with timer attached: ``` /s 0 def 0 1 (%stdin) (r) file token pop realtime 4 1 roll { 2 32 string cvrs mark exch { (1) search {pop pop dup}{pop exit}ifelse } loop counttomark 2 ge {pop length s add /s exch def} if cleartomark } for s = realtime (Time elapsed, s: )= exch sub 1000 div = ``` And: ``` echo 10 | gs -q -dBATCH sum.ps 12 Time elapsed, s: 0.0 echo 500 | gs -q -dBATCH sum.ps 1410 Time elapsed, s: 0.0 echo 1000000 | gs -q -dBATCH sum.ps 2999655 Time elapsed, s: 3.218 ``` [Answer] # Smalltalk (Smalltalk/X) (105 chars) ``` (0 to:20) injectAndCollect:0 into:[:sumSoFar :n | sumSoFar + (([(n clearBit:n lowBit) lowBit] ifError:0) - 1 max:0) ] ``` -> 0 0 0 1 1 3 5 6 6 9 12 13 16 18 20 21 21 25 29 30 34 injectAndCollect:into: is not part of Ansi Smalltalk, though. [Answer] # JavaScript, 69 68 ``` for(s=k=prompt(r=0);k--;r=k&k+1)for(s-=!r;r*!(r&2);r/=2)s++;alert(s) ``` The approach is to strip the lowest bit (the result is stored in `r`) then count the trailing zeroes. *Longer alternate, 79 chars* ``` for(k=prompt(s=0);k--;s+=/.(0*)$/.exec((k&k+1).toString(2))[1].length);alert(s) ``` The takes the `r` from above, converts it to a binary string, and uses a regular expression to count the trailing zeroes. I include it because I like the idea of doing the counting with string processing. [Answer] ## 32-bit x86 assembly code, 22 bytes Accepts input in ecx register, output is in eax register. ``` 00000000 33 c0 xor eax, eax 00000002 e3 11 jecxz 00000015 00000004 51 push ecx 00000005 0f bc d1 bsf edx, ecx 00000008 0f b3 d1 btr ecx, edx 0000000B 0f bc d1 bsf edx, ecx 0000000E 74 02 je 00000012 00000010 03 c2 add eax, edx 00000012 59 pop ecx 00000013 e2 ef loop 00000004 00000015 c3 ret ``` ]
[Question] [ One of the annoying bits about PowerShell, which helps amplify its disadvantage against other languages in [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), is that there are no symbolic comparison or logical operators. A comparison that could be as short as this: ``` $x<10&&$x>5 ``` Has to be: ``` $x-lt10-and$x-gt5 ``` This bloats the code for even the simplest of comparisons by about 50% compared to many other regular scripting and programming languages, never mind any golfing languages. Even an Excel formula for a similar comparison comes up shorter by one character! ``` =AND(A1<10,A1>5) ``` Another one that really bugs me: ``` $x==$k&&$i>9&&$i%10!=0 ``` Has to be: ``` $x-eq$k-and$i-gt9-and$i%10-ne0 ``` Interestingly, this one's *exactly* as long as the comparable formula for Excel, but that's mainly due to Excel's lack of a symbolic modulus operator. ``` =AND(A1=B1,C1>9,MOD(C1,10)<>0) ``` Is there a way this can be shortened at all, or is this strictly a limitation of the language? Are there any particular scenarios to keep in mind where shortcuts can be used for joining multiple comparisons? [Answer] I found a semi-edge case where a multiple comparison *can* be shortened. This is useful when you need to test two or more variables for equality, and only return true if all tests are true. Instead of this: ``` $a-eq$b-and$c-eq$d ``` You might be able to do this: ``` "$a$c"-eq"$b$d" ``` It's worked for me in a Pisano Period script, where I changed: ``` $a-eq1-and$b-eq0 ``` To: ``` "$a$b"-eq10 ``` Another example: ``` $a-eq'apple'-and$b-eq'orange' ``` Can be cut down to: ``` "$a$b"-eq'appleorange' ``` [Answer] You can also use the integer-to-boolean conversion trick [mentioned by Danko](https://codegolf.stackexchange.com/a/15979/9387) to check prime numbers for inequality against other prime numbers. This could also work for composite numbers, provided that none of the numbers involved are evenly divisible by any of the others. Example: ``` $x-ne$y-and$x-ne$z ``` Can be shortened to: ``` $x%$y-and$x%$z ``` Because non-zero integers are handled as `True` in PowerShell, any prime numbers will return `True` for `$x%$y` if they are different and `False` if they are the same. [Answer] Note that `[int]$x` is `0`(i.e. false) for all `$x` in the interval `[-0.5, 0.5]`, and `not 0`(i.e. true) for all `$x` outside of the interval (`[int]` rounds the number). So, to check `$x -lt $m -or $x -lt $n` - you can use the [following](http://www.wolframalpha.com/input/?i=solve%20a%2am%2bb=-0.5%20and%20a%2an%2bb=0.5%20for%20a,b): ``` [int]( $a * $x + $b ) ``` where `$a = 1 / ( $n - $m )` and `$b = ( $m + $n ) / ( 2 * ( $m - $n ) )` For example, to check that `$x` is not between `3` and `5`, you have `$a = 1 / 2` and `$b = -2` so: ``` [int]($x/2-2) ``` which is two characters shorter than ``` $x-lt3-or$x-gt5 ``` To reverse the condition (i.e. to check that `$x` is between `3` and `5`), you could: ``` ![int]($x/2-2) ``` which is still shorter than ``` $x-ge3-and$x-le5 ``` It may not always be possible to get a short expression - it depends, of course, on what you get for `$a` and `$b`. However, if `$m = -$n` then `$b=0`, so the expression becomes rather trivial, e.g. to check that a number is between `-3` and `3` you can simply: ``` ![int]($x/6) ``` --- Another possibility to consider is `"1"[$x]` which evaluates to `"1"` (i.e. true) if `$x` is rounded to `-1` or `0`, and "nothing" (i.e. false) otherwise. So, the expression will be true for all $x in the interval `(-1.5, 0.5]`. Note that `-1.5` is not included in the interval, as `[int]-1.5 = -2`. With this method you can shorten an expression such as `$x -gt $m -and $x -le $n` into: ``` "1"[ $a * $x + $b ] ``` If you [do the math](http://www.wolframalpha.com/input/?i=solve%20a%2am%2bb=-1.5%20and%20a%2an%2bb=0.5%20for%20a,b) as above, you get: `$a=-2/($m-$n)` and `$b=($m+3*$n)/(2*$m-2*$n)`. So, for example: ``` $x-gt3-and$x-le5 ``` becomes: ``` "1"[$x-4.5] ``` ]
[Question] [ This Perl code is supposed to calculate the Leibniz formula. [The original problem is here.](https://www.hackerrank.com/codesprint4/challenges/leibniz) The input format is: ``` T <T test cases, each on their own line> ``` Each test case is a number < 10^7. The output format should be the same, minus the first line. For example, an input: ``` 2 10 20 ``` And for output: ``` 0.760459904732351 0.77290595166696 ``` My first solutions, at 62 and 61 characters respectively. ``` for(1..<>){$s=0;map{$s+=($_&1||-1)/(2*$_-1)}1..<>;print"$s\n"} for(1..<>){$s=0;$s+=($_&1||-1)/(2*$_-1)for 1..<>;print"$s\n"} ``` Edit: The best solution so far is 53 characters, by @teebee: ``` <>;print${\map$a-=(-1)**$_/(2*$_-1),1..$_},$a=$/for<> ``` [Answer] # Perl 53 bytes You can save two more strokes: ``` <>;print${\map$a-=(-1)**$_/(2*$_-1),1..$_},$a=$/for<> ``` [Answer] ## Perl 55 bytes ``` <>;map($s-=(-1)**$_/(2*$_-1),1..$_),$s=!print$s,$/for<> ``` Without using any Perl non-standard features (such as `say`). 3 bytes are wasted removing the first value from the input. Sample usage: in.dat ``` 2 10 20 ``` ``` $ perl leibniz.pl < in.dat 0.760459904732351 0.77290595166696 ``` --- ## Alternative, also 55 bytes ``` map{$s-=(-1)**$_/($_*2-1)for 1..<>;$s=!print$s,$/}1..<> ``` The alternative may be run interactively, without requiring an input file. Which, as I understand, is what you meant by running indefinitely. ]
[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/6304/edit). Closed 8 years ago. [Improve this question](/posts/6304/edit) A magic hexagon is a hexagon where every row and every diagonal add up to the same value. In this case the value is 38. Each number from 1 to 19 must be used exactly once. ![Hexagon](https://i.stack.imgur.com/USCiU.gif) This image shows a solution but I want a program that derives this result. Your challenge is to solve the magic hexagon as fast as possible. You must derive the result yourself, no hard-coding. [Answer] ## C++ Uses some macros to enumerate the possible values. (A-S, assigned lexicographically in the problem image.) `m` is a bitmask of values that have been used so far. ``` #include <stdio.h> #define LOOP(V) for(int V=1;V<20;V++){if(m&1<<V){m&=~(1<<V); #define ENDLOOP(V) m|=1<<V;}} #define SET(V,e) int V=e;if(m&1<<V){m&=~(1<<V); #define UNSET(V) m|=1<<V;} int main() { int m=1048574; LOOP(A); LOOP(B); SET(C,38-A-B); LOOP(D); SET(H,38-A-D); LOOP(G); SET(L,38-C-G); LOOP(E); SET(F,38-D-E-G); LOOP(I); SET(M,38-B-E-I); SET(Q,38-H-M); LOOP(J); SET(N,38-C-F-J-Q); SET(R,38-D-I-N); SET(S,38-Q-R); SET(P,38-L-S); SET(K,38-B-F-P); SET(O,38-M-N-P); printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n",A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S); UNSET(O); UNSET(K); UNSET(P); UNSET(S); UNSET(R); UNSET(N); ENDLOOP(J); UNSET(Q); UNSET(M); ENDLOOP(I); UNSET(F); ENDLOOP(E); UNSET(L); ENDLOOP(G); UNSET(H); ENDLOOP(D); UNSET(C); ENDLOOP(B); ENDLOOP(A); } ``` Runs in 30msec and generates the following: ``` 3 17 18 19 7 1 11 16 2 5 6 9 12 4 8 14 10 13 15 3 19 16 17 7 2 12 18 1 5 4 10 11 6 8 13 9 14 15 9 11 18 14 6 1 17 15 8 5 7 3 13 4 2 19 10 12 16 9 14 15 11 6 8 13 18 1 5 4 10 17 7 2 12 3 19 16 10 12 16 13 4 2 19 15 8 5 7 3 14 6 1 17 9 11 18 10 13 15 12 4 8 14 16 2 5 6 9 19 7 1 11 3 17 18 15 13 10 14 8 4 12 9 6 5 2 16 11 1 7 19 18 17 3 15 14 9 13 8 6 11 10 4 5 1 18 12 2 7 17 16 19 3 16 12 10 19 2 4 13 3 7 5 8 15 17 1 6 14 18 11 9 16 19 3 12 2 7 17 10 4 5 1 18 13 8 6 11 15 14 9 18 11 9 17 1 6 14 3 7 5 8 15 19 2 4 13 16 12 10 18 17 3 11 1 7 19 9 6 5 2 16 14 8 4 12 15 13 10 ``` The 4th line is the example solution. [Answer] So this somewhat ugly code crashes spectacularly in the REPL (its own words!), but compiles and executes fine. Uppercase letters indicate values, I pick from the set to iterate over them. Lowercase letters are generated. z = 38 - X - Y for example, and e = 38 - X - A. With e and J we get n and so on. ``` /** X Y z A B c d e f g h i J k l m n o p */ object MagicHexagon extends App { val set =(1 to 19)toSet // row 1 for (x <- set; y <-(set - x); z = 38 - y - x; dummy <- ((set - x - y) -- (set - x - y - z)); rest1=(set - x - y - z); a <- rest1; e = 38 - x - a; dummy2 <- ((rest1 - a) -- (rest1 - a - e)); j <- rest1 - a - e; n = 38 - e - j; dummy3 <- ((rest1 - a - e - j) -- (rest1 - a - e - j - n)); b <- rest1 - a - e - n; rest2=(rest1 - a - e - j - n - b); f = 38 - y - b - j; dummy4 <- ((rest2) -- (rest2 - f)); c <- rest2 - f; d = 38 - a - b - c; dummy5 <- ((rest2 - f - c) -- (rest2 - f - c - d)); i = 38 - z - d; dummy6 <- ((rest2 - f - c - d) -- (rest2 - f - c - d - i)); rest3 = rest2 - f - c - d - i; g <- rest3; h = 38 - e - f - g - i; dummy7 <- ((rest3 - g) -- (rest3 - g - h)); k = 38 - z - c - g - n; dummy8 <- ((rest3 - g - h) -- (rest3 - g - h - k)); o = 38 - a - f - k; rest4 = (rest3 - g - h - k - o); dummy9 <- ((rest3 - g - h - k) -- rest4); m = 38 - y - c - h; dummyA <- (rest4 -- (rest4 - m)); p = 38 - i - m; dummyB <- (rest4 - m) -- (rest4 - m - p); l = 38 - j - k - m; dummyC <- (rest4 - m - p) -- (rest4 - m - p - l); buf = List( List(" ",x,y,z), List(" ",a,b,c,d), List("",e,f,g,h,i), List(" ",j,k,l,m), List(" ",n,o,p))) { println (buf.map (_.mkString ("", ", ", "")).mkString ("\n")) println () } } ``` The dummy-variables are a kind of hack to allow the loop to terminate prematurely if a generated value doesn't match one of the left values from the set, especially 0 or negative values must be avoided. Result: ``` scala MagicHexagon , 10, 12, 16 , 13, 4, 2, 19 , 15, 8, 5, 7, 3 , 14, 6, 1, 17 , 9, 11, 18 , 10, 13, 15 , 12, 4, 8, 14 , 16, 2, 5, 6, 9 , 19, 7, 1, 11 , 3, 17, 18 , 9, 11, 18 , 14, 6, 1, 17 , 15, 8, 5, 7, 3 , 13, 4, 2, 19 , 10, 12, 16 , 9, 14, 15 , 11, 6, 8, 13 , 18, 1, 5, 4, 10 , 17, 7, 2, 12 , 3, 19, 16 , 3, 19, 16 , 17, 7, 2, 12 , 18, 1, 5, 4, 10 , 11, 6, 8, 13 , 9, 14, 15 , 3, 17, 18 , 19, 7, 1, 11 , 16, 2, 5, 6, 9 , 12, 4, 8, 14 , 10, 13, 15 , 18, 11, 9 , 17, 1, 6, 14 , 3, 7, 5, 8, 15 , 19, 2, 4, 13 , 16, 12, 10 , 18, 17, 3 , 11, 1, 7, 19 , 9, 6, 5, 2, 16 , 14, 8, 4, 12 , 15, 13, 10 , 16, 19, 3 , 12, 2, 7, 17 , 10, 4, 5, 1, 18 , 13, 8, 6, 11 , 15, 14, 9 , 16, 12, 10 , 19, 2, 4, 13 , 3, 7, 5, 8, 15 , 17, 1, 6, 14 , 18, 11, 9 , 15, 13, 10 , 14, 8, 4, 12 , 9, 6, 5, 2, 16 , 11, 1, 7, 19 , 18, 17, 3 , 15, 14, 9 , 13, 8, 6, 11 , 10, 4, 5, 1, 18 , 12, 2, 7, 17 , 16, 19, 3 ``` Runs in 17s on 7y'o' Laptop. [Answer] It takes 121 seconds to run and is incredibly inefficient. Any tips to improve efficiency would be appreciated instead of down votes. ## C# ``` static void Main(string[] args) { DateTime time = DateTime.Now; int n1 = 0, n2 = 0, n3 = 0, n4 = 0, n5 = 0, n6 = 0, n7 = 0, n8 = 0, n9 = 0, n10 = 0, n11 = 0, n12 = 0, n13 = 0, n14 = 0, n15 = 0, n16 = 0, n17 = 0, n18 = 0, n19 = 0; List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; List<int> c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19; c1 = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; for (int x1 = 0; x1 < c1.Count; x1++ ) { n1 = c1[x1]; c2 = c1.Select(i => i).ToList(); c2.Remove(n1); for (int x2 = 0; x2 < c2.Count; x2++) { n2 = c2[x2]; c3 = c2; c3 = c2.Select(i => i).ToList(); c3.Remove(n2); for (int x3 = 0; x3 < c3.Count; x3++) { n3 = c3[x3]; if (n1 + n2 + n3 == 38) { c4 = c3.Select(i => i).ToList(); c4.Remove(n3); for (int x4 = 0; x4 < c4.Count; x4++) { n4 = c4[x4]; c5 = c4.Select(i => i).ToList(); c5.Remove(n4); for (int x5 = 0; x5 < c5.Count; x5++) { n5 = c5[x5]; c6 = c5.Select(i => i).ToList(); c6.Remove(n5); for (int x6 = 0; x6 < c6.Count; x6++) { n6 = c6[x6]; c7 = c6.Select(i => i).ToList(); c7.Remove(n6); for (int x7 = 0; x7 < c7.Count; x7++) { n7 = c7[x7]; if(n4 + n5 + n6 + n7 == 38) { c8 = c7.Select(i => i).ToList(); c8.Remove(n7); for (int x8 = 0; x8 < c8.Count; x8++) { n8 = c8[x8]; if(n1 + n4 + n8 == 38) { c9 = c8.Select(i => i).ToList(); c9.Remove(n8); for (int x9 = 0; x9 < c9.Count; x9++) { n9 = c9[x9]; c10 = c9.Select(i => i).ToList(); c10.Remove(n9); for (int x10 = 0; x10 < c10.Count; x10++) { n10 = c10[x10]; c11 = c10.Select(i => i).ToList(); c11.Remove(n10); for (int x11 = 0; x11 < c11.Count; x11++) { n11 = c11[x11]; c12 = c11.Select(i => i).ToList(); c12.Remove(n11); for (int x12 = 0; x12 < c12.Count; x12++) { n12 = c12[x12]; if(n8 + n9 + n10 + n11 + n12 == 38) { if(n3 + n7 + n12 == 38) { c13 = c12.Select(i => i).ToList(); c13.Remove(n12); for (int x13 = 0; x13 < c13.Count; x13++) { n13 = c13[x13]; if (n2 + n5 + n9 + n13 == 38) { c14 = c13.Select(i => i).ToList(); c14.Remove(n13); for (int x14 = 0; x14 < c14.Count; x14++) { n14 = c14[x14]; c15 = c14.Select(i => i).ToList(); c15.Remove(n14); for (int x15 = 0; x15 < c15.Count; x15++) { n15 = c15[x15]; c16 = c15.Select(i => i).ToList(); c16.Remove(n15); for (int x16 = 0; x16 < c16.Count; x16++) { n16 = c16[x16]; if (n13 + n14 + n15 + n16 == 38) { if (n2 + n6 + n11 + n16 == 38) { c17 = c16.Select(i => i).ToList(); c17.Remove(n16); for (int x17 = 0; x17 < c17.Count; x17++) { n17 = c17[x17]; if (n3 + n6 + n10 + n14 + n17 == 38) { c18 = c17.Select(i => i).ToList(); c18.Remove(n17); for (int x18 = 0; x18 < c18.Count; x18++) { n18 = c18[x18]; if (n4 + n9 + n14 + n18 == 38) { if (n7 + n11 + n15 + n18 == 38) { c19 = c18.Select(i => i).ToList(); c19.Remove(n18); n19 = c19[0]; if(n17 + n18 + n19 == 38) { if(n1 + n5 + n10 + n15 + n19 == 38) { if(n12 + n16 + n19 == 38) { Console.Out.WriteLine("Success"); Console.Out.WriteLine(n1); Console.Out.WriteLine(n2); Console.Out.WriteLine(n3); Console.Out.WriteLine(n4); Console.Out.WriteLine(n5); Console.Out.WriteLine(n6); Console.Out.WriteLine(n7); Console.Out.WriteLine(n8); Console.Out.WriteLine(n9); Console.Out.WriteLine(n10); Console.Out.WriteLine(n11); Console.Out.WriteLine(n12); Console.Out.WriteLine(n13); Console.Out.WriteLine(n14); Console.Out.WriteLine(n15); Console.Out.WriteLine(n16); Console.Out.WriteLine(n17); Console.Out.WriteLine(n18); Console.Out.WriteLine(n19); } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } Console.Out.WriteLine(DateTime.Now - time); Console.In.Read(); } ``` [Answer] 39 ms, 363k recurrence calls. Greetings Lukasz. Java code: ``` package game_numbers; public class Numbers { public static int counter=0; public static byte get_next(byte[] numbers) { byte elem=0; int i=0; do { elem=numbers[i]; i++; } while(elem==0 && i<19) ; return elem; } // main recur alg public static boolean findNext(byte[] gameBoard, byte[] numbers) { boolean found = false; byte tmpNumbers[] = copyNumbers(numbers); byte elem = get_next(tmpNumbers); do { counter++; tmpNumbers = removeFromNumbers(tmpNumbers, elem); gameBoard = putOnBoard(gameBoard,elem); //printBoard(gameBoard); if(match(gameBoard)) { numbers = removeFromNumbers(numbers, elem); if(win(numbers)) found=true; else { found=findNext(gameBoard, numbers); if( !found) { gameBoard = removeFromBoard(gameBoard); numbers = addToNumbers(numbers, elem); } } } else removeFromBoard(gameBoard); elem=get_next(tmpNumbers); } while (elem!=0 && !found) ; return found; } private static byte[] addToNumbers(byte[] numbers1, byte elem) { numbers1[elem-1] = elem; return numbers1; } private static byte[] copyNumbers(byte[] numbers) { byte[] newNumbers={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; for(byte i=0; i<19; i++) newNumbers[i] = numbers[i]; return newNumbers; } private static void printBoard(byte[] gameBoard) { System.out.println(); for(byte temp: gameBoard) { System.out.print(temp + " "); } } private static boolean win(byte[] numbers) { if( get_next(numbers) == 0) return true; else return false; } private static byte[] removeFromNumbers(byte[] numbers1, byte elem) { numbers1[elem-1] = 0; return numbers1; } private static byte[] removeFromBoard(byte[] gameBoard) { byte i=0; while( gameBoard[i] > 0 ) i++; gameBoard[i-1] = 0; return gameBoard; } //evaluation function private static boolean match(byte[] gameBoard) { byte SUM = 38; // mapping of permutation to board game //spiral from outside - quick 300k byte a=gameBoard[0]; byte b=gameBoard[1]; byte c=gameBoard[2]; byte g=gameBoard[3]; byte l=gameBoard[4]; byte p=gameBoard[5]; byte t=gameBoard[6]; byte s=gameBoard[7]; byte r=gameBoard[8]; byte m=gameBoard[9]; byte h=gameBoard[10]; byte d=gameBoard[11]; byte e=gameBoard[12]; byte f=gameBoard[13]; byte k=gameBoard[14]; byte o=gameBoard[15]; byte n=gameBoard[16]; byte i=gameBoard[17]; byte j=gameBoard[18]; /* /a|b|c\ /d|e|f|g\ /h|i|j|k|l\ \m|n|o|p/ \r|s|t/ */ if( checkVeriables3(a,b,c) == SUM) if (checkVeriables4(d,e,f,g) == SUM) if (checkVeriables5(h,i,j,k,l) == SUM) if (checkVeriables4(m,n,o,p) == SUM) if (checkVeriables3(r,s,t) == SUM) if (checkVeriables3(a,d,h) == SUM) if (checkVeriables4(b,e,i,m) == SUM) if (checkVeriables5(c,f,j,n,r) == SUM) if (checkVeriables4(g,k,o,s) == SUM) if (checkVeriables3(l,p,t) == SUM) if (checkVeriables3(c,g,l) == SUM) if (checkVeriables4(b,f,k,p) == SUM) if (checkVeriables5(a,e,j,o,t) == SUM) if (checkVeriables4(d,i,n,s) == SUM) if (checkVeriables3(h , m , r) == SUM) return true; return false; } private static byte checkVeriables5(byte h, byte i, byte j, byte k, byte l) { byte SUM=38; if (h==0) return SUM; if (i==0) return SUM; if (j==0) return SUM; if (k==0) return SUM; if (l==0) return SUM; SUM=(byte)(h+i+j+k+l); return SUM; } private static byte checkVeriables4(byte h, byte i, byte j, byte k) { byte SUM=38; if (h==0) return SUM; if (i==0) return SUM; if (j==0) return SUM; if (k==0) return SUM; SUM=(byte)(h+i+j+k); return SUM; } private static byte checkVeriables3(byte h, byte i, byte j) { byte SUM=38; if (h==0) return SUM; if (i==0) return SUM; if (j==0) return SUM; SUM=(byte)(h+i+j); return SUM; } private static byte[] putOnBoard(byte[] gameBoard, byte elem) { byte i=0; while( gameBoard[i] > 0 ) i++; gameBoard[i] = elem; return gameBoard; } public static void main(String[] args) { byte[] availableNumbers={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19}; byte[] gameBoard={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; boolean found = false; long time = System.currentTimeMillis(); while (!found) { found = findNext(gameBoard,availableNumbers); } long time1 = System.currentTimeMillis(); for(byte temp: gameBoard) System.out.print(temp + " "); System.out.println(); System.out.println("runing time:" + (time1-time)); System.out.println("number of recurrence calls:" + counter); } } ``` ]
[Question] [ Write the shortest program, in the language of your choice, that takes as input a year on the [Hebrew calendar](http://www.jewfaq.org/calendr2.htm), and outputs the corresponding Gregorian date for [Rosh Hashana](http://en.wikipedia.org/wiki/Rosh_Hashanah), in YYYY-MM-DD format. ``` ~$ rh 5771 2010-09-09 ~$ rh 5772 2011-09-29 ~$ rh 5773 2012-09-17 ``` * The input may come from either the command line or from stdin, whichever is more convenient. * You may assume that the year will be between 5600 (1839) and 6000 (2239), inclusive. [Answer] ### Ruby, 192 181 165 characters ``` require'date' s=(-6+235*n=gets.to_i)/19*765433+73848;e=s/u=25920 $><<Date.jd(347641+e+([h=s%u/19440,84>>e%7+h&1,v=e%7*(374454>>n%19&1-h&s%u/9923),v,n-5765].count 1)) ``` Input is given as a single number on STDIN. *Edit 1:* Several arithmetic transformations saved quite a few characters. *Edit 2:* There was some room for improvement. [Answer] ## C#, 212 This might seem cheap, but here I go: ``` using System;using System.Globalization;class P{static void Main(){int y=int.Parse(Console.ReadLine())-5771;var a=new HebrewCalendar().AddYears(new DateTime(2010,9,9),y);Console.Write(a.ToString("yyyy-MM-dd"));}} ``` with spacing ``` using System; using System.Globalization; class P { static void Main() { int y = int.Parse(Console.ReadLine()) - 5771; var a = new HebrewCalendar().AddYears(new DateTime(2010, 9, 9), y); Console.Write(a.ToString("yyyy-MM-dd")); } } ``` [Answer] ## CPAN 5.10, 109 This is even cheaper than the C# solution, for reasons enumerated below. Code first: (character count as a difference to `perl -E''` as usual) ``` $ perl -E'$_="DateTime::Calendar::Hebrew";/:/;eval"require $_";say$`->from_object(object,$_->new(year,<>,month,7))->ymd' ``` * steals Peter Olson's idea of just outsourcing it to the library * CPAN's current release of `DateTime::Calendar::Hebrew` doesn't install out of the box, you need to [patch it](http://www.perlmonks.org/?node_id=802664). * needs Perl 5.10. No earlier, no later. At least it's short. ]
[Question] [ What general tips do you have for golfing in Uiua? I'm looking for ideas that can be applied to code golf problems in general that are specific to Uiua. (e.g. "remove comments" would not be an answer.) Please post one tip per answer. [Answer] # Use complex numbers The length of a vector given by a pair of numbers can be found with `sqrt + both(pow 2)` for 7 glyphs (or more idiomatically `under both un sqrt +` for 5). But using complex numbers, this problem can be solved in just 2 glyphs: `abs complex`. Other problems can benefit from clever uses of complex numbers, e.g. to represent transformations. [Answer] # Use an SBCS (single-byte character set) Uiua uses Unicode glyphs that would usually take up multiple bytes each. But with an SBCS, each character is represented with one byte. Because Uiua is currently in flux, such an encoding will also have to change to fit the changes in the language. I have been updating one since the beginning of this year. Here is the link to today's revision for Uiua 0.8.0, with the new glyphs `◴◰`: <http://tinyurl.com/Uiua-SBCS-Jan-18>. [Answer] # Use `/f` instead of `f°⊟` If you have an array with two rows, and want to apply a `|2.1` function to its rows, use `/ reduce` instead of `°⊟ un couple`. An example [(Pad)](https://uiua.org/pad?src=0_8_0__4oavMl8z4oehNgriioMoCiAgK8Kw4oqfICMgM181XzcKfCAvKyAgIyBhbHNvIDNfNV83CikK): ``` ↯2_3⇡6 ⊃( +°⊟ # 3_5_7 | /+ # also 3_5_7 ) ``` ]
[Question] [ My doubles pickleball group often has five people. Four are playing and one is awaiting the next game. We can represent the state of the game with a string of five characters like abCde. This indicates that a and b are playing against c and d with c serving. We want to write a routine that gives the possible positions after the next rally is complete. The examples below will assume we start with this configuration. For those unfamiliar with the game, two players are paired to play against the other two. One of the players serves to put the ball in play. A rally consists of play until one side fails to hit the ball back legally, at which point it is won by the side that did not fail. Only the serving side scores points for winning a rally. The receiving side only moves the serve along by winning a rally. There are four possible outcomes of a rally. 1. The serving side wins the rally but does not win the game. The players on the serving side change places and the same player serves, so we go to abdCe. 2. The serving side wins the rally and thereby wins the game. The players rotate one position right and the serve goes to the first position, so we go to Eabcd 3. The receiving side wins the rally, but the partner of the server has not served yet. The players stay in position and the serve goes to the partner, so we go to abcDe 4. The receiving side wins the rally and the partner of the server has served. The players stay in position and the serve goes to the first player of the other side, the one in first or third position. Here we go to Abcde Your task is to write a routine that takes a configuration at the start of a rally and returns or prints the four possible configurations at the end of the rally in the order of the possibilities above. A configuration has the five characters in any order with the server any of the first four. This is code golf, so the shortest solution wins. You can use other characters and other ways of indicating the server if you wish, like digits and making the server negative or adding $5$ to the server or putting an asterisk after the server. There needs to be a clear break between the four possibilities, like a space, a newline, or separate elements of a list. You can take your input in any convenient way, as a string or array for example. The characters used should be the same on input and output. Test cases-input first column, output the remaining four ``` Abcde bAcde Eabcd aBcde abCde caBed caeBd Dcabe cabEd Cabed dBace Bdace Edbac Dbace dbAce bcdAe bcAde Ebcda bcDae Bcdae ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 40 bytes ``` AN⁸NM’ỊḤ‘¤¦,@ṙ-AN1¦Ɗż@s2WU,NƊṠE$?€ŒpF€ƲẎ ``` [Try it online!](https://tio.run/##y0rNyan8/9/R71HjDj/fRw0zH@7uerhjyaOGGYeWHFqm4/Bw50xdRz/DQ8uOdR3d41BsFB6q43es6@HOBa4q9o@a1hydVOAGpI5terir7//DnfusHzXMUdC1U3jUMNf6cDtQQIXLP97MJMXY6OHO2X61h3ba6wOVH27nerh7y@F2IDMSaHdSckoqV3KiU2oKV4pTYnIqF1DAMRUA "Jelly – Try It Online") A monadic link taking a list of integers and returning a list of lists of integers in the order specified. Servers are indicated by negative numbers. If the order of results could be more flexible, I can save three bytes. ## Explanation ``` AN⁸NM’ỊḤ‘¤¦,@ṙ-AN1¦Ɗż@s2WU,NƊṠE$?€ŒpF€ƲẎ­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏⁠⁠‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁢⁡⁤‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁣⁤​‎‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁤⁡​‎‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁣⁢⁣‏‏​⁡⁠⁡‌⁤⁢​‎‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏‏​⁡⁠⁡‌⁤⁣​‎⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏⁠‎⁡⁠⁣⁡⁡‏⁠‎⁡⁠⁣⁡⁢‏‏​⁡⁠⁡‌⁤⁤​‎‎⁡⁠⁢⁣⁡‏‏​⁡⁠⁡‌⁢⁡⁡​‎‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏‏​⁡⁠⁡‌⁢⁡⁢​‎‎⁡⁠⁣⁡⁣‏⁠‎⁡⁠⁣⁡⁤‏‏​⁡⁠⁡‌⁢⁡⁣​‎‎⁡⁠⁣⁢⁡‏⁠‎⁡⁠⁣⁢⁢‏‏​⁡⁠⁡‌⁢⁡⁤​‎‎⁡⁠⁣⁢⁤‏‏​⁡⁠⁡‌­ A # ‎⁡Absolute N⁸ ¤¦ # ‎⁢Negate at the index given by running the following on the original argument: N # ‎⁣- Negate M # ‎⁤- Indices (here single index) of max (will be the index of the server) ’ # ‎⁢⁡- Decrement by 1 Ị # ‎⁢⁢- <= 1 Ḥ # ‎⁢⁣- Double ‘ # ‎⁢⁤- Increment by 1 ,@ Ɗ # ‎⁣⁡Pair in reverse order with the result of running the following on the original argument: ṙ- # ‎⁣⁢- Rotate once to the right A # ‎⁣⁣- Absolute N1¦ # ‎⁣⁤- Negate first index ż@ Ʋ # ‎⁤⁡Zip in reverse order with the result of applying the following to the original argument: s2 # ‎⁤⁢- Split into lists of length 2 ṠE$?€ # ‎⁤⁣- For each of these sublists, if the signs are equal: W # ‎⁤⁤ - Then wrap in a further list U,NƊ # ‎⁢⁡⁡ - Else pair the reversed sublist with the negated sublist Œp # ‎⁢⁡⁢- Cartesian product F€ # ‎⁢⁡⁣- Flatten each Ẏ # ‎⁢⁡⁤Join outermost lists 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # APL+WIN, ~~93~~ 85 bytes Prompts for players as integers 1 to 5 with the server shown as negative: ``` m←⎕⋄m⋄t←⊂[2]2 2⍴m⋄m←4↓m⋄(∊(+/¨0>¨t)⌽¨t),m⋄(-m),∊s←|t⋄(∊t×2/¨u←×/¨×t),m⋄(∊s×(⌽u),¨1),m ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tfy6QCRR61N2SC8QlIF5XU7RRrJGC0aPeLblg8bYJJo/aJoPYGo86ujS09Q@tMLA7tKJE81HPXhClA5bSzdXUAUoXA5XXlEDVlhyebgRUXQoUOzwdyDg8HaYapPLwdA2gCaWaOodWGAKF/wMdxPU/jevQekMFIwVjBRMFUy51BXWuNC5jBUOFQ@uNFEwVTKAiJmC@IVAVTA1EB0ivKQA "APL (Dyalog Classic) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 57 bytes ``` ⟦⭆⪪θ²⎇⊙ι№αλ⮌ιι⁺↥§θ⁴↧…θ⁴⭆⪪θ²⭆ι⎇№α§ι¬μ↥λ↧λ⭆θ⎇⁼κ⊗⊙…θ²№αλ↥ι↧ι ``` [Try it online!](https://tio.run/##dZCxboMwEIZfxeMhuUvVLROiHSq1FQrJFGUw5tRYuWJjDAlP7x6IlnroZOs@6/@/s74or62iGEtv2gCnKvD5@a4cVI5MgE6Kx0yKA/pW@QnydgIjRWEHfqykoIzhHkf0PYLhu5kHJQ09HJ1DrxXP8/DaNnifs55m/GZvKykmTVhcrFsZw38EtrHZbH41fhqYfdgAX0vSJkBJKTunRd2W@NINinq4SvFsh5qwWTZONGebv/unVSap4t/IztkuxrzWDcaHkb4B "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⟦ ``` Print each of the following expressions on their own line. ``` ⭆⪪θ²⎇⊙ι№αλ⮌ιι ``` Split the input into pairs of letters and reverse the pair which contains an uppercase letter. (The last letter is always unaffected; even if it was in upper case, reversing it would have no effect.) ``` ⁺↥§θ⁴↧…θ⁴ ``` Uppercase the last letter of the input and concatenate that with the lowercased first four letters. ``` ⭆⪪θ²⭆ι⎇№α§ι¬μ↥λ↧λ ``` Split the input into pairs of letters and set each letter's case to that of the other letter in the pair. (The last letter becomes set to its case, which has no effect.) ``` ⭆θ⎇⁼κ⊗⊙…θ²№αλ↥ι↧ι ``` If one of the first two letters is in uppercase then uppercase only the third letter otherwise uppercase only the first letter. [Answer] # [C (GCC)](https://gcc.gnu.org), ~~238~~ 226 bytes ``` #define Q),q( q(x){putchar(x+48);}f(a,b,c,d,e,z){z=(a|b)&1;z?q(b Q a Q c Q d):(q(a Q b Q d Q c)Q e Q'/'Q e|1 Q~1&a Q~1&b Q~1&c Q~1&d Q'/'Q a^z Q b^z Q!z^c Q!z^d Q e Q 47);z?q(a&~1 Q~1&b Q c|1 Q d):(q(a|1 Q b Q~1&c Q~1&d)Q e);} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVHBTsMwDL3vK8yQtkQENSlllFWIA_TMKm0Sh2koTVLoYWXNWjR1Yz_CZZf9A7_ClS8hCa0QkfyeHdvPjvJxFE_PQhwOx7rKzsOv71OpsrxQkGBSol6JNni7qivxwjXanAUhjt4zxElKBJFEkQZvmxvEdykesKi5LVEKCXBjwpjEY1QiG9lbaW9xAkZ66A0N7xgkezbgDlOHwqFsK_iisb0WT5qFcGhVjAIEV9jN44M96wRAWMlurPP_ydrhZv_2pZ95UcGS5wXCsO2BOZ4Hr1JCUS9TpSFfw1rpN6VdbqVNeYb68-JhNp3MpmOYV30cuVyGaEopZQQsM-qY0ZZ_YxPStvxPKn6cxHfT-H48r3wWjEK4pn4wAnphfepfjkI7wjVpVdW6ABr12v27H_sB) While it looks daunting, the way this works is actually simple. `f` takes 5 players as parameters, where odd numbers denote the server (aka least-significant bit). That is, numbers 0 and 1 are the same player, 2 and 3, etc. The function `q` outputs a digit. `z` tests whether one of the first players is the server and is used later for some conditions. The random-looking 47 is the separator between the outcomes, as 47+48=95, so an underscore. Any number from 10 to 99 or even -1 to -9 would work. Sadly, one digit is not possible, as all numbers from 0 through 9 are possible players. The outputs are constructed using bit manipulation to set, remove or flip the LSB. -12 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) ]
[Question] [ [Qat](https://www.quinapalus.com/qat.html) is a tool that lets you search for words matching a given pattern, often used by crossword and other word puzzle writers and solvers. In this challenge, you will have to implement a specific part of Qat, namely a subset of the "equation solver". ## Equations The output of a Qat query depends on the dictionary you use (i.e. the list of words you are pattern matching against) and the pattern you input. The most basic thing you can do in Qat is define **simple patterns**, which are sequences of symbols which should match some words (similar to regular expressions). In this problem, we will only include two different types of symbols: * A *lowercase* letter, which just matches that letter * A period `.`, which can match any letter (equivalent to the regular expression `[a-z]`). For example, using the base Qat dictionary, the simple pattern `l.......v` matches `leitmotiv` and `lermontov`, so the output is `leitmotiv lermontov`. (There are many more complicated patterns you can also define, but we'll ignore them for this challenge.) In Qat, you can also describe **equations**. From the website (description simplified and modified to only use our simple patterns): > > Qat's equation solver is based around *variables*, represented by capital letters from A to Z. > > > An equation consists of a left-hand side (LHS) followed by an equals sign `=` and a right-hand side (RHS). > > > The LHS consists of a sequence of variables and simple patterns. > The RHS is a simple pattern, which matches any word that fits that pattern [which is then output as a result]. > > > **Qat will try to assign strings of characters to the variables so that the whole LHS matches the RHS.** > > > Multiple equations are separated by semicolons, in which case all of the equations must be satisfied, the solution to each of the equations is shown in sequence. If there are multiple valid solutions, each of them is output in sequence. ### Examples It's probably easiest to understand with some examples. Suppose we are using the dictionary `[one two onetwo onesix]`. Then: * The pattern `A=o..` is an equation which says "`A` must match a three letter word starting with 'o'"; the only option here is `one`, so the output is `one`. * The pattern `A=o..;A=..e` is an equation which says "`A` must match a three letter word starting with 'o' and also a three letter word ending with 'e'"; the only option here is `one`, so the output is `one one` (because there are two equations). * The pattern `A=...` says "`A` must match a three letter word"; there are two options here (`one` and `two`), so the output is `one; two`. * The pattern `A=oneB;B=...` says "`A` must `one` prepended to `B`, where `B` is a three-letter word"; the only option here is that `B` is `two`, making `A` equal to `onetwo`. Thus, the output is `onetwo two`. (Note the solutions to the equations are output in order.) * The pattern `o..A=ones..` says "look for a sequence of characters `A` where the pattern `o..A` can match `ones...`". The only option in this case is that `A` equals `six`, in which case we find a word in the dictionary which matches both `o..six` and `ones..`; the only solution here is `onesix`, so this produces the output `onesix`. * The pattern `A=...;B=...;C=AB` says "`C` must be the combination of two three-letter words"; the output is thus `one two onetwo`. ## Challenge Given a dictionary (i.e. a list of valid words) and a pattern, produce the sequence of solutions to the equations matching the pattern. You can take in the input pattern in any format you want as long as it is reasonable and has a direct mapping to the format described above, and output in any reasonable format. You can assume that the dictionary contains only strings of lowercase letters and the pattern only contains a sequence of valid equations *which has at least one solution*. You do not need to handle recursive inputs. ## Test cases | Dictionary | Pattern | Output | | --- | --- | --- | | `[one two onetwo onesix]` | `A=o..` | `one` | | `[one two onetwo onesix]` | `A=o..;A=..e` | `one one` | | `[one two onetwo onesix]` | `A=...` | `one; two` | | `[one two onetwo onesix]` | `A=oneB;B=...` | `onetwo two` | | `[one two onetwo onesix]` | `o..A=ones..` | `onesix` | | `[one two onetwo onesix]` | `A=...;B=...;C=AB` | `one two onetwo` | Standard loopholes are forbidden. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest program wins. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 298 bytes ``` from itertools import* import re P=product def F(W,E): V={ord(i)for i in E if'@'<i<'['};E=E.split(';') for t in P(set().union(*[sum((l:=[i]+[x+i for x in l]for i in s),l:=[])for s in W]),repeat=len(V)):yield from P(*[[c for c in W if re.fullmatch(e.translate(dict(zip(V,t))),c+'='+c)]for e in E]) ``` [Try it online!](https://tio.run/##VZJNj9sgEIbP4VeMtIeBDeLSSxUvUpNVes4pe7B8sGysnQoDAqJmW/W3p@B8dOsLZt5n3pkBwkd@9@7L1xAvlyn6GSibmL23CWgOPuZndl0hGnbQIfrxNGQ2mgm@8ze5FxsGR/3bx5GTmHwEAnKwB5rwG77QC7b4p9nrvUrBUubYoGBQuVy5A08mc6FOjrzjz206zZzbjW6pW7fnNS3kuZK2e5gnISvSLeVSjbx1QkYTTJ@1NY4fhdh8kLEjLBMdinE7LFbDQpfmyjRqOlk793l450bl2Ltk@2z4SEPmvyjwo8xCCDmsUeN6EEt9swzXiYsFDS16Z1AC5p@@LmX37y/RGTvGQp/LebpUcbbCrfZKoVytnqAw90Cz1UqZR/ghqU9sA8X7muDMrtn9JxbpJhe3hUif1NLK3e6a17zq7Q5vxWru1YKVfuuQoQ55b7xcb/lCJFcvD1D98OT43AeOt40sD8FKCOWwxOUv "Python 3.8 (pre-release) – Try It Online") Brute force. Tries assigning every substring from every word to each variable. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 45 bytes ``` ₄↔ƛ⁰kAfnvvV₅¹↔$vZ'ƛ÷Mƛ÷εnh=;A;A;vvh;ÞfUvṄ‛; j ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLCueKBsFxcO+KCrFxcPXbigqxXwqhTIiwi4oKE4oaUxpvigbBrQWZudnZW4oKFwrnihpQkdlonxpvDt03Gm8O3zrVuaD07QTtBO3Z2aDvDnmZVduG5hOKAmzsgaiIsIiIsIltcIm9uZVwiLCBcInR3b1wiLCBcIm9uZXR3b1wiLCBcIm9uZXNpeFwiXVxuXCJBPS4uLjtCPS4uLjtDPUFCXCIiXQ==) (times out) or [try a version with only three variables.](https://vyxal.pythonanywhere.com/#WyIiLCLCueKBsFxcO+KCrFxcPXbigqxXwqhTIiwiM+KGlMab4oGwYEFCQ2BmbnZ2VuKChcK54oaUJHZaJ8abw7dNxpvDt861bmg9O0E7QTt2dmg7w55mVXbhuYTigJs7IGoiLCIiLCJbXCJvbmVcIiwgXCJ0d29cIiwgXCJvbmV0d29cIiwgXCJvbmVzaXhcIl1cblwiQT0uLi47Qj0uLi47Qz1BQlwiIl0=) Tries all possible substitutions and all possible equation results so it's extremely slow. ]
[Question] [ **Description** Inspired by [this question](https://cs.stackexchange.com/questions/155836/storing-n-bits-on-the-smallest-possible-space-in-a-real-computer/155842), write a program/function to encode a number and a program (possibly the same as the first) to decode a bitstream in variable-length encoding as follows (taken from that question's answer, slightly modified): > > Represent the string x using the following encoding: > > > $$0, x\_k, \dots, 0, x\_2, 0, x\_1, 1, x\_0$$ > > > where \$x\_0\$ is just \$x\$, then \$x\_{i+1} = \mathrm{len}(x\_i)\$ is a binary > representation of the length of \$x\_i\$ in bits (namely, > \$\mathrm{len}(x\_i)=\mathrm{ceil}(\log\_2 x\_i)\$, for \$i \ge 1\$), and \$k\$ is the > smallest \$k \ge 1\$ such that \$x\_k \le 3\$. > > In particular, you always encode \$x\_k\$ with 2 bits, and encode \$x\_i\$ with \$x\_{i+1}\$ bits. > > > Some example encodings: | Decimal | Encoded | | --- | --- | | 0 | 00110 | | 1 | 00111 | | 2 | 010110 | | 3 | 010111 | | 4 | 0111100 | | 8 | 011010011000 | | 127 | 011011111111111 | Note that based on this encoding, the first bit is always 0, and the next 2 bits afterwards always encode the length of the next part. **Input/Output** For the encoder, it will take as input a list of non-negative integers, which may be empty (in any list representation you like), and output the string as per the encoding above. When encoding multiple numbers, simply concatenate the encoding. If the input is an empty list, output empty string. For the decoder, it will take as input a (possibly invalid encoding, but always consists only of 0 and 1) bit string, and output a list of integers it encodes (in the same representation as the input to your encoder). If the string is an invalid encoding, you can output anything that cannot be misconstrued as a valid list of integers. For example, you can just output "INVALID" as the whole output, or you output "X" after outputting partially decoded list of integers (e.g., when the first part of the string is valid, but the later one isn't). As long as your invalid output cannot be read as a list of integers as a whole (in the same representation you use for the encoder input), it's fine. This includes terminating with an exception or a non-zero exit code (since it's also not a valid input to the encoder). **Scoring** This is code golf, the score of an answer is the sum of the number of bytes in both programs. If your program can do both in the same program, the length of that program is the score. Lowest score wins. Standard code golf rules apply. **Test Cases** Some test cases (input, then output on the next line, separated by a blank line): **Encoder** ``` 2 010110 1 5 3 001110111101010111 0 0 1 001100011000111 8 127 512 987654321 0110100110000110111111111110110100010101100000000001101010111101111010110111100110100010110001 ``` The last test case is an empty list as input, and empty string as output **Decoder** ``` 010110 2 001110111101010111 1 5 3 001100011000111 0 0 1 00111011110010111 Invalid (a new number starts with 1) 1 Invalid (a new number starts with 1) 0011000110001 Invalid (not complete) 001100011001101001100 Invalid (not complete) 0011000110011010 Invalid (not complete) 0110100110000110111111111110110100010101100000000001101010111101111010110111100110100010110001 8 127 512 987654321 ``` The last test case is an empty string, outputting empty list (which is empty string in this case, but it depends on your list representation) [Answer] # JavaScript (ES6), 170 bytes ## Encoder, 85 bytes ``` a=>a.map(g=(n,_,i,b=n.toString(2))=>(i=+!!i)|n>3?g(b.length)+i+b:i+=n<2?0+b:b).join`` ``` [Try it online!](https://tio.run/##RclLDoIwFIXhOau4ztq0NjxiNOqFkStwSIgUhFKCt4QSR@4dH4manMF38vf6rn092XFek7s2S4uLxlSrmx6ZQUbyIq2skNTszvNkybCYc0yZRbFaWf6gNMkMq9TQkJk7Lqyo9lYgHeMsfLHiqneWynI55AFADjEU8oNIwkZC8r2hfC/61Xj75w6KoAhU66aTrjvmAVOoHXk3NGpwhrXMc86XJw "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array a.map(g = ( // g is a recursive callback function taking: n, // n = current integer _, // the index is ignored i, // the reference to the array is used as a flag // (either defined or undefined) b = n.toString(2) // b = binary representation of n ) => // (i = +!!i) | // turn i into either 0 or 1 n > 3 ? // if i = 1 or n is greater than 3: g(b.length) + // do a recursive call with the length of b i + b // append i, followed by b : // else: i += // append i, followed by: n < 2 ? // if n is less than 2: 0 + b // a leading '0' and b : // else: b // just b ).join`` // end of map(); join everything ``` ## Decoder, 85 bytes Throws an error if the input is invalid. ``` f=(s,n=3,S=s.slice(n))=>s?(k='0b'+s.slice(1,n))[n]?s>k?[+k,...f(S)]:f(S,-~k):_:n-3||s ``` [Try it online!](https://tio.run/##bY3BisIwEIbvfYqQiwmmIcFbJe1pn8BjKVJjqm5LsmTKwtK6r14TsSrqHH5mvvmY@a5/a9D@9NOn1u3NNDWKALNqxTYKOHQnbYilVOVQkFYtxG6xnLFkYVHaqoC8LcplyzjnDdnQKgvJ0v@WZtvMpqtxhGldJghhIYWUArNrH9o4xrhy@eDiHjO8qbd6gtGa9Vhvx59vf3qBkyrhjfNftT4SQCpHQ3B6/4cGpJ0F1xneuQNpCFCKzmGn6z6ohr4I2HjvPI7OmU4X "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: s, // s = input string n = 3, // n = length of current bit block S = s.slice(n) // S = remaining string after the current block ) => // s ? // if s is not empty: ( k = // define k as: '0b' + // the binary prefix followed by s.slice(1, n) // the current bit block without the leading digit )[n] ? // if k is as long as expected: s > k ? // if the leading digit is '1': [ +k, // append k, coerced to an integer ...f(S) ] // followed by the result of a recursive call with S : // else: f(S, -~k) // do a recursive call with S and n = k + 1 : // else: _ // force an error (undefined variable) : // else: n - 3 || // force an error if n is not equal to 3 [] // otherwise, stop the recursion properly ``` [Answer] # Python3, 300 bytes ## Encoder, 142 bytes ``` def e(x,l='1'):return''.join(e(s)for s in x)if type(x)is list else '0'+f"{x>>1}{x&1}"if x<4 and l=='0'else e(len(bin(x)[2:]),'0')+l+bin(x)[2:] ``` [Try it online!](https://tio.run/##RY7BCoMwEETv/YrFQ5NgKEbbi1R/RDy0uKEpIUqSQkT89jSKpXt5zM6ws9PsX6OpYhxQAtLAdUMEYbVF/7GGkMt7VIYidUyOFhwoA4EpCX6eUpopB1o5D6gdAilILrMltK1Yl3AWa5aC4X6FhxlAN03y9xxSjYY@093AurLuGU8Oy3X@X8WtLWxt3QnSlHxHJ/iNV/0hCl5w8RMH@3rHZJXxdPuQxS8 "Python 3 – Try It Online") ## Decoder 158 bytes ``` def d(s,l=2,t=0):return''if s==''and t==0else d(s[1+l:],int(s[1:1+l],2),1)if s[0]=='0'else str(int(s[1:1+l],2))+' '+d(s[1+l:],2,0)if s[0]=='1'and t==1else 1/0 ``` [Try it online!](https://tio.run/##bU/NDoIwDL77FAuXsrDEFm8kewCfgXAwbkQSMskoBp8et4mKxh7afn9bOtz5cnWHZTG2FSYfVa9LxRpl5S1P3gF0rRi1Bjg5I1hrtP1oo7Omoq8a1TmOexVQo0qpSMZAjU3IICTzyD7/sckCBBSfV0qFmxy9PqOUpz0u7dWLWXRO1DsRKkNCIszUigKIRGxJoa2C70Z/At/@/8GVBEijqdJgf38usQYfLzT5LGXi7Hy2A//q2dHdTn1nwiHDxJlcHg "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 115 bytes ## Encoder, 43 bytes ``` FEA⟦ι⟧«W∨⁼¹Lι‹³⌊ι⊞ιL⍘⌊ι²⪫⮌Eι⁺¬λ⁺…0∧λ‹κ²⍘κ²ω ``` [Try it online!](https://tio.run/##TU/JCsIwED3rVwyeJhDBBU@etHhQXIoeSw@hRhuMSc2iiPjtMdWi3mbeMu9NUTJTaCZDOGgDuGIVzlXlHRIKmcgJgUe7dSuF5IAbg7OLZ9Jin8KSq6MrURBSz9bikMJKKHH25xqMxtTbyH@VU2b5zhmhjvjTURhE6bjdSiPhcKGFwi2/cmP5u0u0p9JbXGuHkjRLci8kT0pdYafXoTBRe5RNidPnIIW/tAar0Vud9Qwhy@IHIwrDPA/dq3wB "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FEA⟦ι⟧« ``` Loop over the input list, but wrap each number in its own list. ``` W∨⁼¹Lι‹³⌊ι ``` Repeat until the list has at least two elements and the smallest element is no more than `3`. ``` ⊞ιL⍘⌊ι² ``` Push the length in binary of the smallest element to the list. ``` ⪫⮌Eι⁺¬λ⁺…0∧λ‹κ²⍘κ²ω ``` Output the elements in binary in ascending order prefixing the last one with `1` and the rest with `0` or `00` if it is less than `2`. ## Decoder, 72 bytes ``` W∧θ⁼§θ⁰0«≔²ηW∧∧‹ηLθ⁼§θ⁰0θ«≔Φκ›μηθ≔⍘…κ⊕η²η»¿‹ηLθ«⟦I⍘…Φθλη²⟧≔Φθ›ληθ»≔1θ»Lθ ``` [Try it online!](https://tio.run/##fY49a8MwEIZn@1ccnk6ggpzVk2vaEMhQ6Fg6CPtqiSpKbKlflPx21fIH9hA6SIjTe8/71Er29VmaEL6UNgRY2gY7Dg/dhzQOS3@wDX3HiWAcMpExxuA3TUrndGtxx0GxIk02y/EcyTlUHI5kW6@wY@xfIoduoi7YR2089fjOYd@TjM9TLBqDxRq7l46efa9ti9VPbahS50tcOti6pxNZTw2OWzs2e17TRL/BDb@p/mlgeXyppPO34bPYIG9GZESz163TmljUzVZ9ECDjCOZ0lmfTxzWdulejIgQh8lwsV7j7NH8 "Charcoal – Try It Online") Link is to verbose version of code. Will output at least one `-` at some point if the string is invalid. Explanation: ``` W∧θ⁼§θ⁰0« ``` Repeat until the string has been processed. ``` ≔²η ``` The first block is of length `2`. ``` W∧∧‹ηLθ⁼§θ⁰0θ« ``` Repeat while there's a valid bit block starting with `0`... ``` ≔Φκ›μηθ ``` ... cut the string after the block, and... ``` ≔⍘…κ⊕η²η ``` convert the block from binary to give the length of the next block. ``` »¿‹ηLθ« ``` If there's still a valid bit block, then... ``` ⟦I⍘…Φθλη²⟧ ``` ... output its value on its own line, and... ``` ≔Φθ›ληθ ``` ... cut the string after the block. ``` »≔1θ ``` Otherwise set the string to an invalid value. ``` »Lθ ``` Output at least one `-` if the string was invalid. [Answer] # [Python 3](https://docs.python.org/3/), 117+154 = 271 bytes Represents a list as space-separated integers. Each is a full program, taking input from stdin, outputting to stdout. ## Encoder, 117 bytes ``` f=lambda n,s=1:f'{f(len(f"{n:b}"),0)if n>3or s else""}{s}{n:0{2-s}b}' print(''.join(map(f,map(int,input().split())))) ``` [Try it online!](https://tio.run/##bVK7TsQwEOz9Fas0caRwsu9EEylIFBRUFLRIKI8NZy5xLMfR3SlKSccnwM/xI8HO6wCxxVqe2Z2ddaLOZl/L3VDouoKslgZPphQpiErV2oDGXGjMzHNj8ro1ZCwT9UI/Gi3ky/0DmWiIV4QG5LgXJQKPCNg4CrP/q0anI5gqXOAJM@r7/lDEZVKleQIybGIeFX5X0BIlLbxORmnvBSELRAHyZldraADLBj2v75re0qzbXjV92vtEWS/G6m1eayFplShahC5bNBRSWQfBplGlsKeLwU4ORi@TsU2DeKBsgpLMtElpN5w5jUnu2u2@iv7qMrqVWWJw6fxHDE/KPgPmVm718UPIbraMi9faCOZ1vj7eZptu7Qv8@T7DE1D4d0tnt2j0T/J2Eoaom0b0c5PR58t3mE2td/djCNnibD5DZSJI7RMchi1hnHHOCOFwDTvC7MUBLo0MJ4QBAz4ybE0WJuQb "Python 3 – Try It Online") Prints each encoding backward, from the number itself, then consecutively prints the length of the previous number in binary, separated by the right separator. The parameter `s` represent the separator to be output. Recurse when length is still more than 3, or it is the original number (`s=1`). ## Decoder, 154 bytes ``` s=input() r=[] def f(i,l,z): if len(s)==i:return 1/z p=int(s[i]);m=int(s[i+1:i+1+l],2)//(1-z*p);p and r.append(m);f(i+1+l,[m,2][p],p) f(0,2,1) print(*r) ``` [Try it online!](https://tio.run/##jVLBjpswEL3PV8wNe5dNcFa9EHHYQw976qHHNKoIDI21YCxjmmxWe@ytn9D@XH8kNRjCUqXSWgI8M@/5jR@jn@2@VvfnwtQVZrWydLSl3KGsdG0sGsqlocx@bWxetxZ6mKzH8mdrpPr2@Al8GZNLhnE47GVJKGJAtw7S7v89jfkP94huWfM8Bd2iI2UsCIJzk0ilHYWDSTZbyKnAgsmwDE8dXRZYkmINTxIZG7KtUSiWJ0DtaE5nI7d8XY37WxG757bchiu@XDJxd7rRfK0xVTmaRao1qZxVfO0EOli4qcLVdqO3oeZQsChchYKDNt1pN4afXXt81rS/1qIhemLRvJRmtk1L59OAMZTmjC8a55pmE5SOGWkbX6cGj@p7Wso8gDdi1rQqSy2Ngld6oKN23lPujhi8nOk6D0eJZMLWBtkYOHhqbNP9SnZpgve2eeZ1AI/RmxX8@fVjsIrKhqb0759D2ieK4OOgGL@M2q9f1IPvDuMXr/Y6kGZDM07JGHcjLVVL8MZW3Dnbn86RiISIYAUQuU0XdK8@K0DgB7z3lejyEhBhhGJGGPDDbZGlqOiAqq12ZND74YffzQy8FzeTnTiqtu5ClS7J0hzVd97v3o3@LxDgLw "Python 3 – Try It Online") Interpret the length of the next binary number repetitively, until separator `1` is found, which indicates the final number. Handles invalid encoding by raising `ZeroDivisionError` (if first bit in a number is not 0, or bitstream ended while original number is not yet found) or `ValueError` (trying to interpret empty string as number). The tricky part is handling the invalid encoding. ]
[Question] [ This is the second version of the task. The original task had a defect that the given range of integers was too small. This was pointed out by @harold that other methods couldn't defeat the way of hard-coding all the possible prime divisors. Now you have a larger range of integers to test from `0` to `2000000`. Also, the result of your program must be sane for all possible input. Multiplication now stores the overflowed bits in the `r0` register. You can name labels with minimum restriction, and the added `dbg` instruction dumps the value of all registers. --- Write a program in assembly that will find out whether the input is a prime number. The program will run through **mjvm** which has a simple set of instructions and a determined number of clock cycles for each instruction. The input will be from `0` to `2000000` inclusive, and the objective is to write the most optimized program spending the least number of clock cycles to determine the primality of all inputs. This is an example program doing a primality test in mjvm assembly. ``` . ind r1 . ; r1 = input ; originally meant input as decimal . lti r1 2 ; r0 = r1 < 2 ; test less than immediate . cjmp false . ; if (r0) goto false . eqi r1 2 ; r0 = r1 == 2 . cjmp true . ; if (r0) goto true . mv r2 r1 ; r2 = r1 . andi r2 1 ; r2 &= 1 . eqi r2 0 ; r0 = r2 == 0 . cjmp false . ; if (r0) goto false . mvi r3 3 ; r3 = 3 loop mv r2 r3 ; r2 = r3 . mul r2 r2 ; r2 *= r2 . gt r2 r1 ; r0 = r2 > r1 . cjmp true . ; if (r0) goto true . mv r2 r1 ; r2 = r1 . div r2 r3 ; r2 /= r3, r0 = r2 % r3 . lnot r0 . ; r0 = !r0 ; logical not . cjmp false . ; if (r0) goto false . addi r3 2 ; r3 += 2 . jmp loop . ; goto loop true mvi r1 0xffffffff ; r1 = -1 . outd r1 . ; print r1 as decimal . end . . ; end program false mvi r1 0 . outd r1 . . end . . ``` For input from `0` to `2000000`, this program consumes total `4043390047` cycles. While some obvious optimizations have been done, there is still a lot of room for improvement. Now if you're interested, this is the whole list of instructions. Each instruction takes a fixed number of arguments, which can either be a register, an immediate (constant), or a label (address). The type of the argument is also fixed; `r` means register, `i` means immediate, and `L` means label. An instruction with an `i` suffix takes an immediate as the third argument while the same instruction without an `i` takes a register as the third argument. Also, I'll explain later, but `r0` is a special register. ``` end - end program dbg - dumps the value of all registers and pause the program ind r - read the input in decimal digits and store the value in `r` outd r - output the value in `r` as decimal digits not r - bitwise not; set `r` to `~r` (all bits reversed) lnot r - logical not; if `r` is 0, set `r` to ~0 (all bits on); otherwise, set `r` to 0 jmp L - jump to `L` cjmp L - if `r0` is non-zero, jump to L mv(i) r1 r2(i) - copy `r2(i)` to `r1` cmv(i) r1 r2(i) - if `r0` is non-zero, copy `r2(i)` to `r1` eq(i) r1 r2(i) - if `r1` equals `r2(i)`, set `r0` to ~0; otherwise set `r0` to 0 neq(i), lt(i), le(i), gt(i), ge(i) - analogus to eq(i) and(i) r1 r2(i) - set `r1` to `r1 & r2(i)`; bitwise `and` or(i), xor(i) - analogus to and(i) shl(i), shr(i) - shift left and shift right; analogus to and(i); add(i), sub(i) - analogus to and(i) mul(i) r1 r2(i) - from the result of `r1 * r2(i)`, the high bits are stored in `r0` and the low bits are stored in `r1`; if the first argument is `r0`, the low bits are stored in `r0`; the high bits are 0 when there is no overflow div(i) r1 r2(i) - set `r0` to `r1 % r2(i)` and set `r1` to `r1 / r2(i)`; if the first argument is `r0`, `r0` is `r1 / r2(i)` ``` As you can see, the result of comparison instructions and the remainder part of division is stored in `r0`. The value is also used to perform a conditional jump or move. These instructions consume 2 clock cycles. ``` cjmp, cmv(i), mul(i) ``` These instructions consume 32 clock cycles. ``` div(i) ``` These instructions consume 10 clock cycles. ``` ind, outd ``` `dbg` does not consume any clock cycle. All other instructions, including `end` consume 1 clock cycle. When the program starts, a cycle is consumed per each instruction of the whole program. That means, for example, if your program has 15 instructions in total, initially 15 cycles will be counted. There are 16 registers from `r0` to `rf` each holding a 32-bit *unsigned* integer. The number after `r` is hexadecimal. The initial value of all registers is 0. There is no memory other than the registers. The result of an operation after an overflow is guaranteed to be `result % pow(2, 32)`. This also applies to an immediate value outside the range of unsigned 32-bits. Division by zero is undefined, but most likely you'll get a hardware interrupt. Labels can be any sequence of characters except whitespaces and `.`. The maximum length of each label is 15 characters, and there can be total 256 labels in a single program. An immediate operand can be hexadecimal starting with `0x` or `0X`, or octal starting with `0`. You start the program by reading an input with `ind`. The input will be automatically given by the VM. You end the program by a sequence of `outd` and `end`. The VM will determine whether your final output is correct. If the input is not prime, the output shall be `0`. If the input is prime, the output shall be `~0`. 0 and 1 are not prime numbers. All the comparison instructions result as `~0` for a `true` value, and you can often use this for efficient bitwise logic. In the assembly code file, each line should start with 4 instructions divided by one or more whitespaces, and `.` is used as a placeholder. Everything else in the line is ignored and thus can be used as comments. The current implementation of the VM may have bugs, you can report any faulty code in the comments. An alternative implementation is also welcomed. I will post here if there is any. This is the code of the VM to measure your program's correctness and efficiency. You can compile with any C compiler, and the program will interpret your assembly file given as the first argument. ``` #include <stdint.h> #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> static uint32_t prime(uint32_t n) { if (n < 2) return 0; if (n == 2) return -1; if (!(n % 2)) return 0; for (int d = 3; d * d <= n; d += 2) { if (!(n % d)) return 0; } return -1; } enum { NOP, DBG, END, IND, OUTD, NOT, LNOT, JMP, CJMP, MV, CMV, EQ, NEQ, LT, LE, GT, GE, AND, OR, XOR, SHL, SHR, ADD, SUB, MUL, DIV, MVI, CMVI, EQI, NEQI, LTI, LEI, GTI, GEI, ANDI, ORI, XORI, SHLI, SHRI, ADDI, SUBI, MULI, DIVI, }; _Noreturn static void verr_(const char *m, va_list a) { vprintf(m, a); putchar('\n'); exit(1); } _Noreturn static void err(const char *m, ...) { va_list a; va_start(a, m); verr_(m, a); } static void chk(int ok, const char *m, ...) { if (!ok) { va_list a; va_start(a, m); verr_(m, a); } } #define LBL_DIC_CAP 0x100 typedef struct { struct { char id[0x10]; int i; } _[LBL_DIC_CAP]; int n; } lblDic_t; static void lblDic_init(lblDic_t *_) { _->n = 0; } static void lblDic_add(lblDic_t *_, const char *id, int i) { chk(_->n < LBL_DIC_CAP, "too many labels"); strcpy(_->_[_->n].id, id); _->_[_->n++].i = i; } static int cmp_(const void *a, const void *b) { return strcmp(a, b); } static void lblDic_sort(lblDic_t *_) { qsort(_, _->n, sizeof(*_->_), cmp_); } static int lblDic_search(lblDic_t *_, const char *id) { int o = &_->_->i - (int *)_; int *p = bsearch(id, _, _->n, sizeof(*_->_), cmp_); if (!p) return -1; return p[o]; } static int ins(const char *s) { if (!strcmp(s, "dbg")) return DBG; if (!strcmp(s, "end")) return END; if (!strcmp(s, "ind")) return IND; if (!strcmp(s, "outd")) return OUTD; if (!strcmp(s, "not")) return NOT; if (!strcmp(s, "lnot")) return LNOT; if (!strcmp(s, "jmp")) return JMP; if (!strcmp(s, "cjmp")) return CJMP; if (!strcmp(s, "mv")) return MV; if (!strcmp(s, "cmv")) return CMV; if (!strcmp(s, "eq")) return EQ; if (!strcmp(s, "neq")) return NEQ; if (!strcmp(s, "lt")) return LT; if (!strcmp(s, "le")) return LE; if (!strcmp(s, "gt")) return GT; if (!strcmp(s, "ge")) return GE; if (!strcmp(s, "and")) return AND; if (!strcmp(s, "or")) return OR; if (!strcmp(s, "xor")) return XOR; if (!strcmp(s, "shl")) return SHL; if (!strcmp(s, "shr")) return SHR; if (!strcmp(s, "add")) return ADD; if (!strcmp(s, "sub")) return SUB; if (!strcmp(s, "mul")) return MUL; if (!strcmp(s, "div")) return DIV; if (!strcmp(s, "mvi")) return MVI; if (!strcmp(s, "cmvi")) return CMVI; if (!strcmp(s, "eqi")) return EQI; if (!strcmp(s, "neqi")) return NEQI; if (!strcmp(s, "lti")) return LTI; if (!strcmp(s, "lei")) return LEI; if (!strcmp(s, "gti")) return GTI; if (!strcmp(s, "gei")) return GEI; if (!strcmp(s, "andi")) return ANDI; if (!strcmp(s, "ori")) return ORI; if (!strcmp(s, "xori")) return XORI; if (!strcmp(s, "shli")) return SHLI; if (!strcmp(s, "shri")) return SHRI; if (!strcmp(s, "addi")) return ADDI; if (!strcmp(s, "subi")) return SUBI; if (!strcmp(s, "muli")) return MULI; if (!strcmp(s, "divi")) return DIVI; err("invalid instruction: %s", s); } static int reg(const char *s) { chk(*s == 'r', "invalid register: %s", s); if ('0' <= s[1] && s[1] <= '9') return s[1] - '0'; if ('a' <= s[1] && s[1] <= 'f') return s[1] - 'a' + 10; err("invalid register: %s", s); } int main(int argc, char **argv) { chk(argc == 2, "must have 1 argument"); int sz; uint32_t p[0x10000][3]; uint32_t r[0x10]; lblDic_t l; lblDic_init(&l); FILE *f = fopen(argv[1], "r"); chk((int)f, "failed to open file: %s", argv[1]); for (int i = 0;; ++i) { char s[0x100]; int m = fscanf(f, "%s", s); if (m < 0) break; chk(strlen(s) < 0x10, "%s is too long", s); if (*s != '.') { if (lblDic_search(&l, s) < 0) { lblDic_add(&l, s, i); lblDic_sort(&l); } } int c; while ((c = getc(f)) != '\n' && m > 0); } rewind(f); char s[4][0x10]; for (int i = 0;; ++i) { int m = fscanf(f, "%s %s %s %s", *s, s[1], s[2], s[3]); if (m < 0) { sz = i; break; } chk(m == 4, "parse error at line %d", i + 1); *p[i] = ins(s[1]); if (*p[i] <= END) { p[i][1] = NOP; } else if (*p[i] == JMP || *p[i] == CJMP) { p[i][1] = lblDic_search(&l, s[2]); chk(p[i][1] != -1u, "unknown label: %s", s[2]); } else { p[i][1] = reg(s[2]); } if (*p[i] <= CJMP) { p[i][2] = NOP; } else if (*p[i] >= MVI) { p[i][2] = strtoul(s[3], NULL, 0); } else { p[i][2] = reg(s[3]); } while ((m = getc(f)) != '\n' && m > 0); } chk(!fclose(f), "sth's very twisted with your system"); for (int i = 0; i < l.n; ++i) { printf("%16s%6d\n", l._[i].id, l._[i].i); } for (int i = 0; i < sz; ++i) { printf("%6d%4u%4u %u\n", i, *p[i], p[i][1], p[i][2]); } long long c = 0; for (int n = 0; n <= 2000000; ++n) { memset(r, 0, sizeof(r)); uint32_t o = 1; c += sz; for (uint32_t *i = *p; i < p[sz]; i += 3) { start: switch(*i) { case DBG: { for (int i = 0; i < 010; ++i) { printf("r%x%11u r%x%11u\n", i, r[i], i + 010, r[i + 010]); } fputs("press ENTER to continue", stdout); getchar(); break; } case END: ++c; goto end; case IND: c += 10; r[i[1]] = n; break; case OUTD: c += 10; o = r[i[1]]; break; case NOT: ++c; r[i[1]] = ~r[i[1]]; break; case LNOT: ++c; r[i[1]] = r[i[1]] ? 0 : -1; break; case JMP: ++c; i = p[i[1]]; goto start; case CJMP: c += 2; if (*r) {i = p[i[1]]; goto start;} break; case MV: ++c; r[i[1]] = r[i[2]]; break; case CMV: c += 2; if (*r) r[i[1]] = r[i[2]]; break; case EQ: ++c; *r = r[i[1]] == r[i[2]] ? -1 : 0; break; case NEQ: ++c; *r = r[i[1]] != r[i[2]] ? -1 : 0; break; case LT: ++c; *r = r[i[1]] < r[i[2]] ? -1 : 0; break; case LE: ++c; *r = r[i[1]] <= r[i[2]] ? -1 : 0; break; case GT: ++c; *r = r[i[1]] > r[i[2]] ? -1 : 0; break; case GE: ++c; *r = r[i[1]] >= r[i[2]] ? -1 : 0; break; case AND: ++c; r[i[1]] &= r[i[2]]; break; case OR: ++c; r[i[1]] |= r[i[2]]; break; case XOR: ++c; r[i[1]] ^= r[i[2]]; break; case SHL: ++c; r[i[1]] <<= r[i[2]]; break; case SHR: ++c; r[i[1]] >>= r[i[2]]; break; case ADD: ++c; r[i[1]] += r[i[2]]; break; case SUB: ++c; r[i[1]] -= r[i[2]]; break; case MUL: { c += 2; uint64_t p = (uint64_t)r[i[1]] * r[i[2]]; *r = p >> 0x20; r[i[1]] = p; break; } case DIV: { c += 32; uint32_t rm = r[i[1]] % r[i[2]]; uint32_t q = r[i[1]] / r[i[2]]; *r = rm; r[i[1]] = q; break; } case MVI: ++c; r[i[1]] = i[2]; break; case CMVI: c += 2; if (*r) r[i[1]] = i[2]; break; case EQI: ++c; *r = r[i[1]] == i[2] ? -1 : 0; break; case NEQI: ++c; *r = r[i[1]] != i[2] ? -1 : 0; break; case LTI: ++c; *r = r[i[1]] < i[2] ? -1 : 0; break; case LEI: ++c; *r = r[i[1]] <= i[2] ? -1 : 0; break; case GTI: ++c; *r = r[i[1]] > i[2] ? -1 : 0; break; case GEI: ++c; *r = r[i[1]] >= i[2] ? -1 : 0; break; case ANDI: ++c; r[i[1]] &= i[2]; break; case ORI: ++c; r[i[1]] |= i[2]; break; case XORI: ++c; r[i[1]] ^= i[2]; break; case SHLI: ++c; r[i[1]] <<= i[2]; break; case SHRI: ++c; r[i[1]] >>= i[2]; break; case ADDI: ++c; r[i[1]] += i[2]; break; case SUBI: ++c; r[i[1]] -= i[2]; break; case MULI: { c += 2; uint64_t p = (uint64_t)r[i[1]] * i[2]; *r = p >> 0x20; r[i[1]] = p; break; } case DIVI: { c += 32; uint32_t rm = r[i[1]] % i[2]; uint32_t q = r[i[1]] / i[2]; *r = rm; r[i[1]] = q; break; } } } end: chk(o == prime(n), "wrong result for %d", n); } printf("total cycles: %lld\n", c); return 0; } ``` [Answer] Stuff at the bottom is for the earlier version of the question. Here's a simple technique to optimize the basic trial division from the example code, at 2736719982 cycles. It hopefully won't be the fastest (it's a bit boring), but at least it's a new target to beat. Techniques used were: * Rewritten loop logic to have the branch at the bottom, and no jmp. * Change the trial division base from { 2 } to { 2, 3 }. There are an explicit div-by-3 test, and a special case for small numbers, before the loop to enable that. The alternating increment pattern of 2, 4, 2, 4 .. is achieved with `xori r6 6` which changes a 2 to a 4, and a 4 to a 2. The base { 2, 3, 5 } with its increment pattern of `[4, 2, 4, 2, 4, 6, 2, 6]` by contrast wouldn't be anywhere near that nice to implement. * Reuse an `outd/end` pair by using a `jmp`, saving code-size that way was worth over a million cycles. * > > Also, the result of your program must be sane for all possible input. > > > I did not verify this, so maybe I cheated, who knows. Actually I tried to test more inputs, but that was too slow and I gave up. Code: ``` . ind r1 . . lti r1 2 . cjmp F . . eqi r1 2 . cjmp T . . mv r2 r1 . andi r2 1 . eqi r2 0 . cjmp F . . lei r1 8 . cjmp T . . mv r2 r1 . muli r2 -1431655765 . lei r2 1431655765 . cjmp F . . mvi r3 5 . mvi r6 4 L mv r2 r1 . div r2 r3 . lnot r0 . . cjmp F . . xori r6 6 . add r3 r6 . mv r2 r3 . mul r2 r2 . le r2 r1 . cjmp L . T mvi r1 -1 . jmp X . F mvi r1 0 X outd r1 . . end . . ``` --- For previous version of the question: I have tried a couple of approaches. So far, the one that is winning is a relatively boring one.. namely an unrolled trial division, at ~~886783~~ 795197 (using Anders Kaseorg's suggestion) cycles: ``` . ind r2 . . eqi r2 2 . cjmp T . . mv r0 r2 . andi r0 1 . lnot r0 . . cjmp F . . lei r2 68 . cjmp A . . mv r1 r2 . muli r2 -1431655765 . lei r2 1431655765 . cjmp F . . muli r2 1717986919 . lei r2 858993459 . cjmp F . . muli r2 -1840700269 . lei r2 613566756 . cjmp F . . muli r2 390451573 . lei r2 390451572 . cjmp F . . muli r2 1982292599 . lei r2 330382099 . cjmp F . . muli r2 1010580541 . lei r2 252645135 . cjmp F . . muli r2 -1356305461 . lei r2 226050910 . cjmp F . . muli r2 1493901669 . lei r2 186737708 . cjmp F . . muli r2 592409283 . lei r2 148102320 . cjmp F . . muli r2 -2078209981 . lei r2 138547332 . cjmp F . . muli r2 -1741202957 . lei r2 116080197 . cjmp F . . muli r2 -104755299 . lei r2 104755299 . cjmp F . . muli r2 -1598127365 . lei r2 99882960 . cjmp F . . muli r2 1644881093 . lei r2 91382282 . cjmp F . . muli r2 -1215556781 . lei r2 81037118 . cjmp F . . muli r2 1019144783 . lei r2 72796055 . cjmp F . . muli r2 2112278999 . lei r2 70409299 . cjmp F . . lti r1 4489 . cjmp T . . muli r2 -769247873 . lei r2 64103989 . cjmp F . . lti r1 5041 . cjmp T . . muli r2 1935759909 . lei r2 60492497 . cjmp F . . lti r1 5329 . cjmp T . . muli r2 1882725391 . lei r2 58835168 . cjmp F . . lti r1 6241 . cjmp T . . muli r2 -1196066841 . lei r2 54366674 . cjmp F . . lti r1 6889 . cjmp T . . muli r2 1397158037 . lei r2 51746593 . cjmp F . . lti r1 7921 . cjmp T . . muli r2 579096715 . lei r2 48258059 . cjmp F . . lti r1 9409 . cjmp T . . muli r2 132834041 . lei r2 44278013 . cjmp F . T mvi r1 -1 . outd r1 . . end . . F mvi r1 0 . outd r1 . . end . . A mvi r1 1689570158 . shri r2 1 . shr r1 r2 . andi r1 1 . mvi r0 0 . sub r0 r1 . outd r0 . . end . . ``` First I test whether the input is 2 (output True), then whether it is even (output False), then there is a small bitmap of odd primes, and then there is a bunch of divisibility tests by primes from 3 up through 97, which is enough to cover everything up to 10000. The divisibility tests are basically of the form `if (n * mulinv(d) <= 0xFFFFFFFF / d) output False` where `mulinv` is the multiplicative inverse modulo 232, except that instead of using the actual `n` each time, the result of the multiplication is carried forward and that multiplication is implicitly "undone" by multiplying by `d1 * mulinv(d2)` where `d1` is the previous divisor and `d2` is the current one. Some of them have an extra test first to see if the input is smaller than the square of the divisor, and then output True. Oddly it seems that the main effect of the small "bitmap of primes"-test for small numbers is that it gets rid of some of those extra "input is smaller than square of divisor"-tests, which is not why I added it, but so be it. I also tried a deterministic Miller Rabin test with bases 2 and 3, which I was very hopeful for, but it was actually quite bad: over 3 million cycles initially, then I added some of those divisibility tests from above so the main MR-test would run less often, but it turned out that the best thing to do was to add *all* of them .. and then remove the actual MR-test. [Answer] **hard-coded divisibility test to its extreme - 2156770452 cycles** During an attempt to optimize @harold's solution, I discovered that every time I add an hard-coded divisibility test, the number of cycles decrease. The reason is actually quite simple. A `div` instruction consumes 32 cycles, but a hard-coded divisibility test can be achieved by a sequence of `mv -> muli -> lei -> cjmp`, which is total 6 cycles plus 3 cycles for the increased code size. `div` can only be optimized out when the value of the operand is specified. The result is a program with **917** instructions, and the few instructions at the end are just there to produce correct output outside the given range of the task. Of course I did not write this by hand, I generated it with a Python script. --- Out of curiosity, I wanted to check if the hard-coded division method scales well at least to the range of 32-bit unsigned integers. I found [this paper](http://ceur-ws.org/Vol-1326/020-Forisek.pdf) that describes an efficient algorithm (FJ32\_256) doing a primality test in the range of 32-bit unsigned integers. I decided to use this algorithm for comparison, then generated a C program ([pastebin](https://pastebin.com/mJUUM7Dn)) with the same Python script tuned to generate C instead of mjvm assembly ([pastebin](https://pastebin.com/q7cm82Vk)), for a larger range of possible input from \$0\$ to \$2^{32}\$ The test was done through these 5 ranges ``` [0, 20000000) [100000000, 120000000) [200000000, 220000000) [300000000, 320000000) [400000000, 420000000) ``` This is the result where the numbers are the counted (real) clock cycles from my 2.4GHz CPU. ``` range 0 - hard-coded 1966207882 range 0 - FJ32_256 1896766512 range 1 - hard-coded 1877253992 range 1 - FJ32_256 2118426310 range 2 - hard-coded 1874180510 range 2 - FJ32_256 2196823877 range 3 - hard-coded 5235061704 range 3 - FJ32_256 2244187362 range 4 - hard-coded 5173315658 range 4 - FJ32_256 2266020651 ``` From this non-rigorous test, we can see that hard-coded divisibility test actually performs well up to 220 million, and then the performance drops due to the increased number of divisibility tests for larger numbers. `FJ32_256` on the other hand has a very stable performance throughout the whole range. --- This is the actual generated assembly code. ``` . ind r1 . . lti r1 2 . cjmp F . . eqi r1 2 . cjmp T . . mv r0 r1 . andi r0 1 . lnot r0 . . cjmp F . . lti r1 9 . cjmp T . . mv r2 r1 . muli r2 0xaaaaaaab . lei r2 0x55555555 . cjmp F . . mv r2 r1 . muli r2 0xcccccccd . lei r2 0x33333333 . cjmp F . . mv r2 r1 . muli r2 0xb6db6db7 . lei r2 0x24924924 . cjmp F . . lti r1 121 . cjmp T . . mv r2 r1 . muli r2 0xba2e8ba3 . lei r2 0x1745d174 . cjmp F . . mv r2 r1 . muli r2 0xc4ec4ec5 . lei r2 0x13b13b13 . cjmp F . . mv r2 r1 . muli r2 0xf0f0f0f1 . lei r2 0xf0f0f0f . cjmp F . . mv r2 r1 . muli r2 0x286bca1b . lei r2 0xd79435e . cjmp F . . mv r2 r1 . muli r2 0xe9bd37a7 . lei r2 0xb21642c . cjmp F . . mv r2 r1 . muli r2 0x4f72c235 . lei r2 0x8d3dcb0 . cjmp F . . mv r2 r1 . muli r2 0xbdef7bdf . lei r2 0x8421084 . cjmp F . . mv r2 r1 . muli r2 0x914c1bad . lei r2 0x6eb3e45 . cjmp F . . mv r2 r1 . muli r2 0xc18f9c19 . lei r2 0x63e7063 . cjmp F . . mv r2 r1 . muli r2 0x2fa0be83 . lei r2 0x5f417d0 . cjmp F . . mv r2 r1 . muli r2 0x677d46cf . lei r2 0x572620a . cjmp F . . mv r2 r1 . muli r2 0x8c13521d . lei r2 0x4d4873e . cjmp F . . mv r2 r1 . muli r2 0xa08ad8f3 . lei r2 0x456c797 . cjmp F . . mv r2 r1 . muli r2 0xc10c9715 . lei r2 0x4325c53 . cjmp F . . mv r2 r1 . muli r2 0x7a44c6b . lei r2 0x3d22635 . cjmp F . . mv r2 r1 . muli r2 0xe327a977 . lei r2 0x39b0ad1 . cjmp F . . mv r2 r1 . muli r2 0xc7e3f1f9 . lei r2 0x381c0e0 . cjmp F . . mv r2 r1 . muli r2 0x613716af . lei r2 0x33d91d2 . cjmp F . . mv r2 r1 . muli r2 0x2b2e43db . lei r2 0x3159721 . cjmp F . . mv r2 r1 . muli r2 0xfa3f47e9 . lei r2 0x2e05c0b . cjmp F . . mv r2 r1 . muli r2 0x5f02a3a1 . lei r2 0x2a3a0fd . cjmp F . . mv r2 r1 . muli r2 0x7c32b16d . lei r2 0x288df0c . cjmp F . . mv r2 r1 . muli r2 0xd3431b57 . lei r2 0x27c4597 . cjmp F . . mv r2 r1 . muli r2 0x8d28ac43 . lei r2 0x2647c69 . cjmp F . . mv r2 r1 . muli r2 0xda6c0965 . lei r2 0x2593f69 . cjmp F . . mv r2 r1 . muli r2 0xfdbc091 . lei r2 0x243f6f0 . cjmp F . . lti r1 16129 . cjmp T . . mv r2 r1 . muli r2 0xefdfbf7f . lei r2 0x2040810 . cjmp F . . mv r2 r1 . muli r2 0xc9484e2b . lei r2 0x1f44659 . cjmp F . . mv r2 r1 . muli r2 0x77975b9 . lei r2 0x1de5d6e . cjmp F . . mv r2 r1 . muli r2 0x70586723 . lei r2 0x1d77b65 . cjmp F . . mv r2 r1 . muli r2 0x8ce2cabd . lei r2 0x1b7d6c3 . cjmp F . . mv r2 r1 . muli r2 0xbf937f27 . lei r2 0x1b20364 . cjmp F . . mv r2 r1 . muli r2 0x2c0685b5 . lei r2 0x1a16d3f . cjmp F . . mv r2 r1 . muli r2 0x451ab30b . lei r2 0x1920fb4 . cjmp F . . mv r2 r1 . muli r2 0xdb35a717 . lei r2 0x1886e5f . cjmp F . . mv r2 r1 . muli r2 0xd516325 . lei r2 0x17ad220 . cjmp F . . mv r2 r1 . muli r2 0xd962ae7b . lei r2 0x16e1f76 . cjmp F . . mv r2 r1 . muli r2 0x10f8ed9d . lei r2 0x16a13cd . cjmp F . . mv r2 r1 . muli r2 0xee936f3f . lei r2 0x1571ed3 . cjmp F . . mv r2 r1 . muli r2 0x90948f41 . lei r2 0x1539094 . cjmp F . . mv r2 r1 . muli r2 0x3d137e0d . lei r2 0x14cab88 . cjmp F . . mv r2 r1 . muli r2 0xef46c0f7 . lei r2 0x149539e . cjmp F . . mv r2 r1 . muli r2 0x6e68575b . lei r2 0x13698df . cjmp F . . mv r2 r1 . muli r2 0xdb43bb1f . lei r2 0x125e227 . cjmp F . . mv r2 r1 . muli r2 0x9ba144cb . lei r2 0x120b470 . cjmp F . . mv r2 r1 . muli r2 0x478bbced . lei r2 0x11e2ef3 . cjmp F . . mv r2 r1 . muli r2 0x1fdcd759 . lei r2 0x1194538 . cjmp F . . mv r2 r1 . muli r2 0x437b2e0f . lei r2 0x112358e . cjmp F . . mv r2 r1 . muli r2 0x10fef011 . lei r2 0x10fef01 . cjmp F . . mv r2 r1 . muli r2 0x9a020a33 . lei r2 0x105197f . cjmp F . . mv r2 r1 . muli r2 0xff00ff01 . lei r2 0xff00ff . cjmp F . . mv r2 r1 . muli r2 0x70e99cb7 . lei r2 0xf92fb2 . cjmp F . . mv r2 r1 . muli r2 0x6205b5c5 . lei r2 0xf3a0d5 . cjmp F . . mv r2 r1 . muli r2 0xa27acdef . lei r2 0xf1d48b . cjmp F . . mv r2 r1 . muli r2 0x25e4463d . lei r2 0xec9791 . cjmp F . . mv r2 r1 . muli r2 0x749cb29 . lei r2 0xe93965 . cjmp F . . mv r2 r1 . muli r2 0xc9b97113 . lei r2 0xe79372 . cjmp F . . mv r2 r1 . muli r2 0x84ce32ad . lei r2 0xdfac1f . cjmp F . . mv r2 r1 . muli r2 0xc74be1fb . lei r2 0xd578e9 . cjmp F . . mv r2 r1 . muli r2 0xa7198487 . lei r2 0xd2ba08 . cjmp F . . mv r2 r1 . muli r2 0x39409d09 . lei r2 0xd16154 . cjmp F . . mv r2 r1 . muli r2 0x6f71de15 . lei r2 0xcebcf8 . cjmp F . . mv r2 r1 . muli r2 0xbfce8063 . lei r2 0xc5fe74 . cjmp F . . mv r2 r1 . muli r2 0xf61fe7b1 . lei r2 0xc27806 . cjmp F . . mv r2 r1 . muli r2 0x70e046d3 . lei r2 0xbcdd53 . cjmp F . . mv r2 r1 . muli r2 0xf1545af5 . lei r2 0xbbc840 . cjmp F . . mv r2 r1 . muli r2 0x9a7862a1 . lei r2 0xb9a786 . cjmp F . . mv r2 r1 . muli r2 0x2a128a57 . lei r2 0xb68d31 . cjmp F . . mv r2 r1 . muli r2 0xb7747d8f . lei r2 0xb2927c . cjmp F . . mv r2 r1 . muli r2 0xbb5e06dd . lei r2 0xafb321 . cjmp F . . mv r2 r1 . muli r2 0x12e9b5b3 . lei r2 0xaceb0f . cjmp F . . mv r2 r1 . muli r2 0xec9dbe7f . lei r2 0xab1cbd . cjmp F . . mv r2 r1 . muli r2 0xec41cf4d . lei r2 0xa87917 . cjmp F . . mv r2 r1 . muli r2 0xaec02945 . lei r2 0xa513fd . cjmp F . . mv r2 r1 . muli r2 0x8382df71 . lei r2 0xa36e71 . cjmp F . . mv r2 r1 . muli r2 0x84b1c2a9 . lei r2 0xa03c16 . cjmp F . . mv r2 r1 . muli r2 0x75eb3a0b . lei r2 0x9c6916 . cjmp F . . mv r2 r1 . muli r2 0xfa86fe2d . lei r2 0x9baade . cjmp F . . mv r2 r1 . muli r2 0x3f8df54f . lei r2 0x980e41 . cjmp F . . mv r2 r1 . muli r2 0x975a751 . lei r2 0x975a75 . cjmp F . . mv r2 r1 . muli r2 0xc3efac07 . lei r2 0x9548e4 . cjmp F . . mv r2 r1 . muli r2 0xa8299b73 . lei r2 0x93efd1 . cjmp F . . mv r2 r1 . muli r2 0x9ba70e41 . lei r2 0x91f5bc . cjmp F . . mv r2 r1 . muli r2 0x23d9e879 . lei r2 0x8f67a1 . cjmp F . . mv r2 r1 . muli r2 0xc494d305 . lei r2 0x8e2917 . cjmp F . . mv r2 r1 . muli r2 0xab67652f . lei r2 0x8d8be3 . cjmp F . . mv r2 r1 . muli r2 0xfb10fe5b . lei r2 0x8c5584 . cjmp F . . mv r2 r1 . muli r2 0xbf54fa1f . lei r2 0x88d180 . cjmp F . . mv r2 r1 . muli r2 0xb98f81d7 . lei r2 0x869222 . cjmp F . . mv r2 r1 . muli r2 0xe90f1ec3 . lei r2 0x85797b . cjmp F . . mv r2 r1 . muli r2 0xbed87f3b . lei r2 0x8355ac . cjmp F . . mv r2 r1 . muli r2 0x16e70fc7 . lei r2 0x824a4e . cjmp F . . mv r2 r1 . muli r2 0x9dece355 . lei r2 0x80c121 . cjmp F . . mv r2 r1 . muli r2 0x73f62c39 . lei r2 0x7dc9f3 . cjmp F . . mv r2 r1 . muli r2 0xad46f9a3 . lei r2 0x7d4ece . cjmp F . . mv r2 r1 . muli r2 0x24e8d035 . lei r2 0x79237d . cjmp F . . mv r2 r1 . muli r2 0x2319bd8b . lei r2 0x77cf53 . cjmp F . . mv r2 r1 . muli r2 0xc7ed9da5 . lei r2 0x75a8ac . cjmp F . . mv r2 r1 . muli r2 0xfea2c8fb . lei r2 0x7467ac . cjmp F . . mv r2 r1 . muli r2 0xce0f4c09 . lei r2 0x732d70 . cjmp F . . mv r2 r1 . muli r2 0x544986f3 . lei r2 0x72c62a . cjmp F . . mv r2 r1 . muli r2 0x55a10dc1 . lei r2 0x7194a1 . cjmp F . . mv r2 r1 . muli r2 0x85e33763 . lei r2 0x6fa549 . cjmp F . . mv r2 r1 . muli r2 0xd84886b1 . lei r2 0x6e8419 . cjmp F . . mv r2 r1 . muli r2 0x31260967 . lei r2 0x6d68b5 . cjmp F . . mv r2 r1 . muli r2 0xd1ff25e9 . lei r2 0x6d0b80 . cjmp F . . mv r2 r1 . muli r2 0x5b84d99f . lei r2 0x6bf790 . cjmp F . . mv r2 r1 . muli r2 0x1335df6d . lei r2 0x6ae907 . cjmp F . . mv r2 r1 . muli r2 0x75d5add9 . lei r2 0x6a3799 . cjmp F . . mv r2 r1 . muli r2 0x3c619a43 . lei r2 0x69dfbd . cjmp F . . mv r2 r1 . muli r2 0x4767747 . lei r2 0x67dc4c . cjmp F . . mv r2 r1 . muli r2 0x663d81 . lei r2 0x663d80 . cjmp F . . mv r2 r1 . muli r2 0x671ddc2b . lei r2 0x65ec17 . cjmp F . . mv r2 r1 . muli r2 0xc1e12337 . lei r2 0x654ac8 . cjmp F . . mv r2 r1 . muli r2 0x9cd09045 . lei r2 0x645c85 . cjmp F . . mv r2 r1 . muli r2 0x91496b9b . lei r2 0x637299 . cjmp F . . mv r2 r1 . muli r2 0xc7d7b8bd . lei r2 0x632591 . cjmp F . . mv r2 r1 . muli r2 0x9f006161 . lei r2 0x6160ff . cjmp F . . mv r2 r1 . muli r2 0x5e28152d . lei r2 0x60cdb5 . cjmp F . . mv r2 r1 . muli r2 0xbfe803 . lei r2 0x5ff401 . cjmp F . . mv r2 r1 . muli r2 0x9e907c7b . lei r2 0x5ed79e . cjmp F . . mv r2 r1 . muli r2 0x76528895 . lei r2 0x5d7d42 . cjmp F . . mv r2 r1 . muli r2 0x1ce2c0d . lei r2 0x5c6f35 . cjmp F . . mv r2 r1 . muli r2 0xbed7c42f . lei r2 0x5b2618 . cjmp F . . mv r2 r1 . muli r2 0xd4b010e7 . lei r2 0x5a2553 . cjmp F . . mv r2 r1 . muli r2 0x1ebbe575 . lei r2 0x59686c . cjmp F . . mv r2 r1 . muli r2 0xb47b52cb . lei r2 0x58ae97 . cjmp F . . mv r2 r1 . muli r2 0x64f3f0d7 . lei r2 0x58345f . cjmp F . . mv r2 r1 . muli r2 0x316d6c0f . lei r2 0x5743d5 . cjmp F . . mv r2 r1 . muli r2 0x91c1195d . lei r2 0x5692c4 . cjmp F . . mv r2 r1 . muli r2 0xa27b1f49 . lei r2 0x561e46 . cjmp F . . mv r2 r1 . muli r2 0xe508fd01 . lei r2 0x5538ed . cjmp F . . mv r2 r1 . muli r2 0x133551cd . lei r2 0x54c807 . cjmp F . . mv r2 r1 . muli r2 0x2d8a3f1b . lei r2 0x5345ef . cjmp F . . mv r2 r1 . muli r2 0xc34ad735 . lei r2 0x523a75 . cjmp F . . mv r2 r1 . muli r2 0xa714919 . lei r2 0x510237 . cjmp F . . mv r2 r1 . muli r2 0x24eea383 . lei r2 0x50cf12 . cjmp F . . mv r2 r1 . muli r2 0x42ba771d . lei r2 0x4fd319 . cjmp F . . mv r2 r1 . muli r2 0x7772287 . lei r2 0x4fa170 . cjmp F . . mv r2 r1 . muli r2 0x5e69ddf3 . lei r2 0x4f3ed6 . cjmp F . . mv r2 r1 . muli r2 0x3b4a6c15 . lei r2 0x4f0de5 . cjmp F . . mv r2 r1 . muli r2 0xc606b677 . lei r2 0x4e1cae . cjmp F . . mv r2 r1 . muli r2 0x46d3e1fd . lei r2 0x4cd47b . cjmp F . . mv r2 r1 . muli r2 0x484a14e9 . lei r2 0x4c78ae . cjmp F . . mv r2 r1 . muli r2 0x1ce874d3 . lei r2 0x4c4b19 . cjmp F . . mv r2 r1 . muli r2 0x473189f . lei r2 0x4bf093 . cjmp F . . mv r2 r1 . muli r2 0x372b7e65 . lei r2 0x4aba3c . cjmp F . . mv r2 r1 . muli r2 0x4f9e5d91 . lei r2 0x4a6360 . cjmp F . . mv r2 r1 . muli r2 0x446bd9bb . lei r2 0x4a383e . cjmp F . . mv r2 r1 . muli r2 0xe777c647 . lei r2 0x49e28f . cjmp F . . mv r2 r1 . muli r2 0xf61f0c23 . lei r2 0x48417b . cjmp F . . mv r2 r1 . muli r2 0xa5cbbb6f . lei r2 0x47f043 . cjmp F . . mv r2 r1 . muli r2 0x69daac27 . lei r2 0x474ff2 . cjmp F . . mv r2 r1 . muli r2 0x637aa061 . lei r2 0x468b6f . cjmp F . . mv r2 r1 . muli r2 0x1fb15099 . lei r2 0x45f13f . cjmp F . . mv r2 r1 . muli r2 0x712c5825 . lei r2 0x45a522 . cjmp F . . mv r2 r1 . muli r2 0xff30637b . lei r2 0x45342c . cjmp F . . mv r2 r1 . muli r2 0x1131289 . lei r2 0x44c4a2 . cjmp F . . mv r2 r1 . muli r2 0xf5acdf7 . lei r2 0x43c5c2 . cjmp F . . mv r2 r1 . muli r2 0x4d3f89e3 . lei r2 0x437e49 . cjmp F . . mv r2 r1 . muli r2 0xd2253531 . lei r2 0x43142d . cjmp F . . mv r2 r1 . muli r2 0x7bf69fe7 . lei r2 0x42ab5c . cjmp F . . mv r2 r1 . muli r2 0xcfb1781f . lei r2 0x422195 . cjmp F . . mv r2 r1 . muli r2 0x318e81ed . lei r2 0x41bbb2 . cjmp F . . mv r2 r1 . muli r2 0x9f148d11 . lei r2 0x40f391 . cjmp F . . mv r2 r1 . muli r2 0x2c7a505d . lei r2 0x40b1e9 . cjmp F . . mv r2 r1 . muli r2 0x28728f33 . lei r2 0x405064 . cjmp F . . mv r2 r1 . muli r2 0xe5ec7155 . lei r2 0x403024 . cjmp F . . mv r2 r1 . muli r2 0x9fe829b7 . lei r2 0x3f90c2 . cjmp F . . mv r2 r1 . muli r2 0x6a50ca39 . lei r2 0x3f7141 . cjmp F . . mv r2 r1 . muli r2 0xb6d26aef . lei r2 0x3f1377 . cjmp F . . mv r2 r1 . muli r2 0xa8251829 . lei r2 0x3e7988 . cjmp F . . mv r2 r1 . muli r2 0x1b863613 . lei r2 0x3e5b19 . cjmp F . . mv r2 r1 . muli r2 0x20d077ad . lei r2 0x3dc4a5 . cjmp F . . mv r2 r1 . muli r2 0x2e3d2b97 . lei r2 0x3da6e4 . cjmp F . . mv r2 r1 . muli r2 0x3dc8eba5 . lei r2 0x3d4e4f . cjmp F . . mv r2 r1 . muli r2 0x3229ebbf . lei r2 0x3c4a6b . cjmp F . . mv r2 r1 . muli r2 0x7e01686b . lei r2 0x3c11d5 . cjmp F . . mv r2 r1 . muli r2 0x2c086e8d . lei r2 0x3bf5b1 . cjmp F . . mv r2 r1 . muli r2 0x9f632df9 . lei r2 0x3bbdb9 . cjmp F . . mv r2 r1 . muli r2 0xdff892af . lei r2 0x3b6a88 . cjmp F . . mv r2 r1 . muli r2 0x3f04d8fd . lei r2 0x3b183c . cjmp F . . mv r2 r1 . muli r2 0x9cfdeff5 . lei r2 0x3aabe3 . cjmp F . . mv r2 r1 . muli r2 0xbda9d4b . lei r2 0x3a5ba3 . cjmp F . . mv r2 r1 . muli r2 0x24f5cbd9 . lei r2 0x3a0c3e . cjmp F . . mv r2 r1 . muli r2 0x94cbbb7f . lei r2 0x38f035 . cjmp F . . mv r2 r1 . muli r2 0xb4f43b81 . lei r2 0x38d6ec . cjmp F . . mv r2 r1 . muli r2 0x34d4323 . lei r2 0x3859cf . cjmp F . . mv r2 r1 . muli r2 0x74f5b99b . lei r2 0x37f741 . cjmp F . . mv r2 r1 . muli r2 0xc68ea1b5 . lei r2 0x377df0 . cjmp F . . mv r2 r1 . muli r2 0x96c0cf0b . lei r2 0x373622 . cjmp F . . mv r2 r1 . muli r2 0xe33edf99 . lei r2 0x36ef0c . cjmp F . . mv r2 r1 . muli r2 0xb897c451 . lei r2 0x36915f . cjmp F . . mv r2 r1 . muli r2 0x8fb91695 . lei r2 0x36072c . cjmp F . . mv r2 r1 . muli r2 0xe5ea8b41 . lei r2 0x35d9b7 . cjmp F . . mv r2 r1 . muli r2 0x93fd7cf7 . lei r2 0x359615 . cjmp F . . mv r2 r1 . muli r2 0xb3f8805 . lei r2 0x35531c . cjmp F . . mv r2 r1 . muli r2 0xa912822f . lei r2 0x353cee . cjmp F . . mv r2 r1 . muli r2 0x13a9147d . lei r2 0x34fad3 . cjmp F . . mv r2 r1 . muli r2 0xc4c3f21 . lei r2 0x347884 . cjmp F . . mv r2 r1 . muli r2 0x7a6883c3 . lei r2 0x340dd3 . cjmp F . . mv r2 r1 . muli r2 0x2ab33855 . lei r2 0x3351fd . cjmp F . . mv r2 r1 . muli r2 0x82e6faff . lei r2 0x333d72 . cjmp F . . mv r2 r1 . muli r2 0x17be8dab . lei r2 0x33148d . cjmp F . . mv r2 r1 . muli r2 0x7cb91939 . lei r2 0x32d7ae . cjmp F . . mv r2 r1 . muli r2 0x42a09ea3 . lei r2 0x32c385 . cjmp F . . mv r2 r1 . muli r2 0x6d8b8bf1 . lei r2 0x328766 . cjmp F . . mv r2 r1 . muli r2 0xba8a223d . lei r2 0x325fa1 . cjmp F . . mv r2 r1 . muli r2 0x9c3182a7 . lei r2 0x324bd6 . cjmp F . . mv r2 r1 . muli r2 0x474bcd13 . lei r2 0x32246e . cjmp F . . mv r2 r1 . muli r2 0xc5311a97 . lei r2 0x31afa5 . cjmp F . . mv r2 r1 . muli r2 0xc00c6719 . lei r2 0x319c63 . cjmp F . . mv r2 r1 . muli r2 0x4b0b61cf . lei r2 0x3162f7 . cjmp F . . mv r2 r1 . muli r2 0x9b8e63b1 . lei r2 0x30271f . cjmp F . . mv r2 r1 . muli r2 0x41eb667 . lei r2 0x2ff104 . cjmp F . . mv r2 r1 . muli r2 0x896a76f5 . lei r2 0x2fbb62 . cjmp F . . mv r2 r1 . muli r2 0x4a55a46d . lei r2 0x2f7499 . cjmp F . . mv r2 r1 . muli r2 0x58046447 . lei r2 0x2ed84a . cjmp F . . mv r2 r1 . muli r2 0x69be3a81 . lei r2 0x2e832d . cjmp F . . mvi r3 1423 L mv r2 r3 . mul r2 r2 . gt r2 r1 . cjmp T . . mv r2 r1 . div r2 r3 . lnot r0 . . cjmp F . . addi r3 2 . jmp L . T not r4 . F outd r4 . . end . . ``` And this is the Python script used to generate the code, which actually steals a bit of optimized output from `gcc`. ``` import sympy import os p = [] m = [] c = [] M = sympy.sqrt(2000000) i = 3 while i < M: if (sympy.isprime(i)): p.append(i) i += 2 f = open("prime.c", "w") f.write("int main() {}\n") for i in range(len(p)): f.write("unsigned d" + str(p[i]) + "(unsigned a) {return !(a % " + str(p[i]) + ");}\n") f.close() os.system("gcc -S -masm=intel -O3 -oprime.s prime.c") f = open("prime.s", "r") s = f.read() f.close() def h(d): d = int(d) if d < 0: return str(hex(d + (1 << 32))) else: return str(hex(d)) def g(s): for i in range(len(s)): if s[i] == '-': s = s[i:] break; if s[i].isdigit(): s = s[i:] break; d = "" i = 0 while i < len(s): if s[i] == '-' or s[i].isdigit(): d += s[i] else: break i += 1 return h(d), s[i:] for i in range(len(p)): s = s[s.find("d" + str(p[i]) + ":"):] s = s[s.find("imul"):] n, s = g(s) m.append(n) n, s = g(s) c.append(n) f = open("prime.s", "w") f.write(". ind r1 .\n. lti r1 2\n. cjmp F .\n. eqi r1 2\n. cjmp T .\n" + ". mv r0 r1\n. andi r0 1\n. lnot r0 .\n. cjmp F .\n. lti r1 9\n. cjmp T .\n") l = 9 for i in range(len(p)): if p[i] > l: l = p[i] * p[i] f.write(". lti r1 " + str(l) + "\n. cjmp T .\n") f.write(". mv r2 r1\n. muli r2 " + m[i] + "\n. lei r2 " + c[i] + "\n. cjmp F .\n") f.write(". mvi r3 1423\nL mv r2 r3\n. mul r2 r2\n. gt r2 r1\n. cjmp T .\n" + ". mv r2 r1\n. div r2 r3\n. lnot r0 .\n. cjmp F .\n. addi r3 2\n. jmp L .\n" + "T not r4 .\nF outd r4 .\n. end . .\n") f.close() ``` ]
[Question] [ A triplet of real tensors \$(A,B,C)\$ of size \$\gamma \times \gamma \times \sigma\$ represents a [matrix multiplication algorithm](https://en.wikipedia.org/wiki/Strassen_algorithm) with \$\sigma\$ elementary multiplications iff the following function evaluates to zero: $$ \text{error}(A,B,C) \equiv \sum\_{i,j,k,l,m,n=1}^\gamma\left(\sum\_{r=1}^{\sigma}{A\_{ij}^r B\_{kl}^r C\_{nm}^r} - \delta\_{ni} \delta\_{jk} \delta\_{lm}\right)^2,$$ where \$\delta\_{ab} = 1\$ if \$a=b\$ and 0 otherwise. ## Reference implementation A reference implementation in C for the above formula is given below: ``` double error(size_t gamma, size_t sigma, double * A, double * B, double * C) { double E = 0.0; for (int i = 0; i < gamma; ++i) { for (int j = 0; j < gamma; ++j) { for (int k = 0; k < gamma; ++k) { for (int l = 0; l < gamma; ++l) { for (int m = 0; m < gamma; ++m) { for (int n = 0; n < gamma; ++n) { double s = 0.0, e = 0.0; for (int r = 0; r < sigma; ++r) { int rij = r*gamma*gamma + i*gamma + j; int rkl = r*gamma*gamma + k*gamma + l; int rnm = r*gamma*gamma + n*gamma + m; s += A[rij] * B[rkl] * C[rnm]; } e = s - (n==i) * (j==k) * (l==m); E += e*e; }}}}}} return E; } ``` ## Sample input & output for \$(\gamma=2,\sigma=7)\$ ``` double A[] = {1,-1,-1,0,1,-1,-1,1,0,-1,0,0,1,0,-1,0,1,-1,0,0,0,0,0,1,0,0,1,0}; double B[] = {-1,-1,-1,0,0,0,-1,0,1,1,1,1,1,0,1,0,-1,-1,0,0,0,0,0,1,0,-1,0,0}; double C[] = {1,-1,1,0,0,0,-1,0,0,-1,0,0,1,-1,0,0,-1,0,-1,0,0,0,0,1,1,-1,1,-1}; assert (0.0 == error(2, 7, A, B, C)); ``` ## Challenge Write a faster version of the reference implementation. While measuring the speed of your code the elements of \$(A,B,C)\$ should be doubles sampled uniformly from the \$[-1,1]\$ interval. ## Competition categories Your implementation can compete in one or more of the following categories: 1. \$(\gamma=3,\sigma=22)\$ 2. \$(\gamma=4,\sigma=48)\$ 3. \$(\gamma=5,\sigma=97)\$ 4. \$(\gamma=6,\sigma=159)\$ ## Rules * The submission must state the \$(\gamma,\sigma)\$ category/categories in which your code is competing. * The submission must contain easy-to-follow build instructions. * Your code must display the speed of your code **relative to the reference implementation** (e.g. being 3.2x faster than the reference implementation). * While measuring speed at least 10000 random evaluations must be made. * For any given input \$(A,B,C)\$ the difference between the output of the reference implementation and your implementation must be smaller than \$10^{-4}\$. * Any programming language and open source library (e.g. OpenBLAS) can be used. * Reference platform: Intel i7-8559U / Linux 5.9.0, GCC 10.3.0. The reference implementation is compiled with the `-O3` flag. ## Scoring * Submissions will be ordered based on their performance on my Intel i7-8559U. [Answer] # [C (gcc)](https://gcc.gnu.org/), score ≈ 6.7×, 8.5×, 13.6x, 19.5× For the four categories (3, 22), (4, 48), (5, 97), (6, 159). This algorithm runs in \$O(γ^3σ + γ^2σ^2)\$ rather than \$O(γ^6σ)\$, using the rearranged formula: \begin{multline\*} \textrm{error}(A, B, C) = γ^3 - 2\sum\_{r=1}^σ \sum\_{i,j,l=1}^γ A\_{ij}^rB\_{jl}^rC\_{il}^r \\ + \sum\_{r,s=1}^σ\left(\sum\_{i,j=1}^γ A\_{ij}^rA\_{ij}^s\right)\left(\sum\_{k,l=1}^γ B\_{kl}^rB\_{kl}^s\right)\left(\sum\_{n,m=1}^γ C\_{nm}^rC\_{nm}^s\right). \end{multline\*} ``` double error(size_t gamma, size_t sigma, double *A, double *B, double *C) { double E = 0.0; for (int r = 0; r < sigma; ++r) { for (int i = 0; i < gamma; ++i) { for (int j = 0; j < gamma; ++j) { double x = 0.0; for (int l = 0; l < gamma; ++l) { int rkl = r * gamma * gamma + j * gamma + l; int rnm = r * gamma * gamma + i * gamma + l; x += B[rkl] * C[rnm]; } int rij = r * gamma * gamma + i * gamma + j; E += A[rij] * x; } } } E = gamma * gamma * gamma - 2 * E; for (int r = 0; r < sigma; ++r) { for (int s = r; s < sigma; ++s) { double xa = 0.0, xb = 0.0, xc = 0.0; for (int ij = 0; ij < gamma * gamma; ++ij) { int rij = r * gamma * gamma + ij; int sij = s * gamma * gamma + ij; xa += A[rij] * A[sij]; xb += B[rij] * B[sij]; xc += C[rij] * C[sij]; } E += (1 + (r != s)) * xa * xb * xc; } } return E; } ``` [Try it online!](https://tio.run/##vVZtjxo3EP7Or5ikauXl5XKkaqWUUAm2KIqaO6S0HyrR02rPGM7g9UbehV4b8ddDZ@x98e6VhF51RYIde54ZD8@8ePlgzfnxK6m52i0FvM7kWsfq4u7HjreXL2X6YEvJ2@ZeLhPR3NlpiUDa60RRnOdG3u5yEUWM6VRqJbUIAjgu092tEiCMSQ3L5F8iymEdJ0nch2KFQdGqAHYntTitxTCAjx0olzMYw@XF5Qh3VqkBJnUOhvZG@HjtPI6g1zPOykNJh5KIslEQSpYoD7dxuI2P29S4KpL7OpKWB@U8KN@D8j0A2LC3BDTQdajq2cOza1mN2mY6OWEmT5ndQ28M0wUeeIOQcIEubmr9odNwLzdnuN/U5jNyPlmgHTm/LxXOK/3Sl9LW9Fc@B/AS5dkjEppRnCN8eKisprlMU@zy1If720rizdzVNVIkX1bZL@O01dIogy@Q5TFkg7XI7AtIDNYnc7JAMy9T@A9cIp162lZzUoelOmyoyyzbdLEhHswMPMOQsFW7dHCX3OMPHzUyZ0S@M5oSdDiebPZOQbYRK2GE5uJJ@/2znXxuH1e4rcNtfdzWT/S/6esKmzhs4mOTJtZDa4fWPlq30RUnWVnHoj2CWm4/20f@51GNf94s254aSudMNO3JyUPjrNEtJwdce8y5j7D9OACG5I9BUhewDYlbKyoSk6DtxbYPVimIpsb3fngwWg@nWqrTyfI4lxz2qcInJVeuscvSRHJsmGWq8ZwaI5dwF@ulEsZNQHupY0ItEP/PcIQHdGz9xVJbTGzWvA/8LkZ@u7jYu/z7/YmGeKJkpF0Mb4K@q5bG9ssbS0XVuqhMYqVSzhy2@2C80wnpijmLoGE9/U/W4aOsM4PEscugedGUA9/Yif@P7qyy1yvbpig3rFfyF8ALKI95P7n@Kbqa/OYKY3omLjwLR2WT5WbHc6DXseyD4JDvcQTk@yHpVarXwNOdzmlVFVM5RC0BtljYL2/fTN69v@qXhYSEoNKaWios0baYrByr2CRsaGnjSPk2WoucQmDhu3n4c3Q1v57/Or9@G/bhGwyoSFTBFQ3v@kqo7gJ7CeDwx6EfFg3W61XBH@CPO4qdPaM4zjx46FdIdWREeBgXTcgY4i7yfZQheQOir1gEdBkWOt1QaqvtwlAMXlFqqiA/GCyfFXteHfUDzMZfq5XNjhWy3/XzPsz6rWiemm73tv2/UZ38@fQcJ0huOX1PcFyE4cgt7TKeGouzqFZRvPBscCAYIdikFqe16GgrRvYlvQUdvz8Ov3v1ia9UvM6Og/m3fwM "C (gcc) – Try It Online") ]
[Question] [ # Introduction Dr. Leslie Lamport, of the eponymous [Lamport one-time signature scheme](https://www.microsoft.com/en-us/research/uploads/prod/2016/12/Constructing-Digital-Signatures-from-a-One-Way-Function.pdf), is getting rather old. But he can't die until his most famous algorithm gets all the kinks ironed out! In particular, that scheme had one internal component he was never satisfied with: > > We hope that someone can find a more elegant method for constructing the function `G` > > > # Challenge Today, we're helping him prepare to leave by constructing a function `R` that takes the output of our one-way function `φ` (likely a hash function), and injectively uses it to **select a subset** of the user's private key, according to the following specifications: * Your function takes two arguments: the output of hash function `φ` (as a data blob, octet stream, or similar appropriate native datatype), and an ordered set (in your choice of appropriate native datatype). + If your language's **standard library** has a bitstring datatype [[ex: Java](https://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html); [*not* Python](https://pypi.org/project/bitstring/)], you **may** choose to take `d` as it with no penalty; if it does not, then unpacking the bytestring (or finding some clever way to avoid or vectorize the doing-of!) is your responsibility. * The `n`th bit of `φ`'s output chooses whether the `2*n`th element or the `2*n+1`th element will be included in the subset. If `φ` outputs a 24-bit data blob, then 24 elements will be chosen. + FOR EXAMPLE: if the **second** bit of `φ(m)` is 1, then the **fourth** element of `pk` will be chosen. If this bit is, instead, 0, then the **third** element of `pk` will be chosen. (There are examples included below.) + Naturally, for 1-indexed languages, the `n`th bit chooses between the `2*n-1`th and `2*n`th elements. + behavior is **totally undefined** in the event that `φ` returns something with more bits than half the number of elements in `pk`; don't even consider this case. * Your function returns the thus-chosen subset of `pk`. + While the *input* set is ordered, the *output* set does **not need to be ordered** (and, if it is an ordered datatype, all possible orderings are allowed with no penalty). The function merely has to identify a *subset* of the ordered input set, so any ordering on its output would be redundant anyway. * This is a standard golfing challenge; shorter answers are better than longer answers. # Example Input and Output For all examples, `N = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64` * φ = MD5, with the digest truncated to the first 24 bits m = [empty string] φ(m) -> `\xd4\x1d\x8c` + R(φ(m), `N`) -> `2, 4, 5, 8, 9, 12, 13, 15, 17, 19, 21, 24, 26, 28, 29, 32, 34, 35, 37, 39, 42, 44, 45, 47` * φ = CRC32 m = "Hello, World" (ASCII) φ(m) -> `\x26\x5b\x86\xc6` + R(φ(m), `N`) -> `1, 3, 6, 7, 9, 12, 14, 15, 17, 20, 21, 24, 26, 27, 30, 32, 34, 35, 37, 39, 41, 44, 46, 47, 50, 52, 53, 55, 57, 60, 62, 63}` * d = `\x00\x00` = two bytes, with all bits "off" + R(d, `N`) -> `1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31` * d = `\xFF` = one byte, with all bits "on" + R(d, `N`) -> `2, 4, 6, 8, 10, 12, 14, 16` * φ = Constant function returning the single byte `\x1d` m = [any input] + R(φ(m), `N`) -> `1, 3, 5, 8, 10, 12, 13, 16` --- ## Python 3, 281 bytes: (281 does not include comments, type hints, docstrings, or the example φ) ``` def _iterbits(data): yield from (((byte & (0b1 << k)) >> k) for byte in data for k in reversed(range(8))) def R(digest: bytes, pk: OrderedSet | list | tuple) -> set: "Reference solution" included_indices = set(2 * n + bit for n, bit in enumerate(_iterbits(digest))) return set(k for i, k in enumerate(pk) if i in included_indices) def φ(m): "Example hash function to help you run your own test cases\n\nReturns an MD5 digest truncated to 24 bits" return hashlib.md5(m).digest()[:3] ``` [Answer] # [R](https://www.r-project.org/), ~~86~~ ~~83~~ 82 bytes (or **[64 bytes](https://tio.run/##XZDdaoNAEIXv8xRTiqBlQp0x/tJc584XKC1o0ChYte4GTF/eHoyEUobdZb7Zc3Zmp@V0XOprf7bt0Ls1517@bqpvt3zbm2IcuxvYo1x6pfPq6KcbZ77nOOp5L7p/Kj@W/ChZoLvdM0k00081DVS21mS7k3t2ffY9@BKKTAFTyBQzpUyCXAAERIAETMEUTMEUTMECgXEyk9xNaXXVMNxclenAFDElsPCxAAREIsj8NWQNnHdp@r@fv8pgU1Zz8TV2FTWFaWiqzLWzZJvCUmvIDgN1Q3@hepgAKyqmqbht06IzXvfHKwGHHHPKGBj2GFcSVlxR1gNrxLqm@MDlFw)** with additional `NA` values in output when length of hash result is greater than half the length of the private key N) ``` function(f,N,d=seq(b<-sapply(f,function(b)b%/%2^(7:0)%%2))*2)N[(d-!b)*!d>sum(N|1)] ``` [Try it online!](https://tio.run/##dZHdiuJAEIXvfYoaFiE9lGyqutMmss6td3mBYRaSGEfBMW4SQYd9d/fkZ2UUhpCE/vp0nTrV9XW1vG5Oh6LdVYdgwymvl035J8h/zZrseNxfwG7bucmnP6f6O5gvQjOdqjHPatLXYD17ys3z0/qlOX0E6V8xb9d0KQvvJpMfJP5Mn2VdUb5rm8VkFRRByKHh1BA2mSxTxDRnSpgEawEQEAESMAVTMAVTMAWzgsLxmWQoSn1VjaKxqjI5Js8Uo0SIF0BAxONY2D/SP/gPR5PHfr6etOPJ8px9HPclbbNmS3XZnPYttduspV1DbVXRvjq806aqAUvK6jq7jGnRGfffm4vliOecMAKjPOJKzAqJsjpWz9ovrXYD3JZnyi9tiZxrR1JQXAxNozkMQ1w/zHuheopyij0V/jaPIVXyJdTjlCGCN8F8mDJ0FsxCZ6GzYK6rBebA3Lzvw8acdDEcSxLfzdHf7vX/BYyOyHbv2FUPv3GU0dF3jogBXQRd1F0UdBGYB/Ng3k6u/wA "R – Try It Online") Input is an array `f` of single-byte integers (representing the output of the hash function phi) and an array `N` (representing the ordered array from which to select a subset). ``` G=function(f,N){ # G is function with args f=array of bytes, N=array of values bits= # calculate the bits of f: sapply(f,function(b) # for each byte b in f b%/%2^(7:0)%%2) # get its bits d=seq(bits) # define d as 1..number of bits N[ # now output the elements of N given by indices: (d*2-1+bits) # d*2-1+bits (these are the indices from the bytes of f) *!d>sum(N|1)/2 # multiplied by zero (FALSE) for bits that exceed the length of N ] } ``` [Answer] # JavaScript (ES6), ~~56~~ 55 bytes Expects `(N)(b)`, where `b` is `φ(m)`. ``` N=>b=>N.filter((_,i)=>((q=b[i>>4])>>7.5-i/2%8^~i)&q>=0) ``` [Try it online!](https://tio.run/##dZHRToMwFIbv9xTnRtfGrmspLTOGJrrpJS9A0MAc2mWOjS1mXuir4ykYtiyO5BD4@f/znR6W@We@m9dusx@tq9dFU8ZNEtsitgkv3Wq/qAl5YY7GlpBtXKTO2jCj1kZcj9w4uJo8/zh6vbWxoE0CMaSc8/u6zr@ICWnGP/KNz4OjEFtwcAOS3g0G6QAgFYdZyEAc5MzfJ9OMQXeNxxAwwG@awYTBLQOJ71JhoSIjLNQCiYWmwGChLUBNoU@hptCn0KdQC30v1ELUwqgD@4w46IcW3D5PDeIRjE2Rg1J0BIdHcCDOwB4iLoDlH9h4MJ4GfRp9GgEafRo1g5pBzajvbjIh/DRC9MvoV9JNpvvJ5IWVoBbobrJ2JbJr/PR01vJs16bdtRQnZzZdUs4y@D/Zj3SaVG0yG/Cyqh/z@Tsp/K@fV@tdtVrwVfVGSpJQUlC@rNyaDBkMKaXNLw "JavaScript (Node.js) – Try It Online") ### Commented ``` N => // outer function taking N[] b => // inner function taking b[] N.filter((_, i) => // for each entry at position i in N[]: ( // ( // q = // let q be the byte from b[] b[i >> 4] // at index floor(i / 16) ) >> // right shift it by 7.5 - i / 2 % 8 // 0 to 7 positions, according to floor(i / 2) mod 8 ^ ~i // XOR the result with i inverted ) // & // isolate the least significant bit, or force zero q >= 0 // if q is undefined ) // end of filter() ``` [Answer] # [R](https://www.r-project.org/), ~~80~~ ~~62~~ ~~54~~ 52 bytes ``` function(d,N)N[seq(b<-rawToBits(rev(d)))*2-rev(b<1)] ``` [Try it online!](https://tio.run/##hZFPT4MwHIbv@xTNvLSmM/Qv04yLH2AHs5t4gJZGkgVmYY5vjy/RMF0yd/iF8vQNPG8bx5CN4di4vm4b6vmWbV@76oOWm1UsTrv2ue47GqtP6hlj93I1LcuNYG9joO69iLv2pTjRZT54nQ/C58PaLRkn4slqtlgU@z29nSNZRhyVnGhODCdrTh6xg3ehMCAixYBJgUFIWgxiEkwhp8AUcgo5Baanb4FpMJ0yiFxISJsPpoQEns7@L3wl@y0NIThCJz1L67O0TC6kJ8HkirT4kbaTNE4COYOcwQ8McgbMglkwq6ZSd74OoYpV05O6ORx70h6mW@xIaCPB7aF10T1gQR1NeMLmmjNPhhB@0T@9hZ@7jl8 "R – Try It Online") As per OP we don't need to handle cases when bits from `φ` select elements outside `N`. *-4 bytes thanks to [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)* ``` function # a function (d, # taking first input as raw bytes (one of R data types) N) # and N as a vector N[ # subset N at following indices seq( # make sequence 1..length(l) - default behaviour for seq on a vector is seq_along b<- # assign the following to b rawToBits(rev(d)) # get bits from bytes in d (in reverse order) # as rawToBits returns bits from the least-significant first, we need to reverse the vector on output (to make most-significant bit first - later on), but also on input (to preserve byte order) )*2 # double every index -rev(b<1) # decrement corresponding indices when bit is off (taking rev here to save parentheses) # comparison is the shortest operator casting from raw to something `-` will handle ] ``` ]
[Question] [ Back in 2018, there has been introduced new law in Poland to ban trading on sundays, but certain exceptions have been made (listed below). The task today is to determine, can one trade on the sunday provided by the user (according to these rules). # Rules You can trade only if one of the following is satisfied: * The day is the last sunday of 1st, 4th 6th and 8th month. * The day is one of the two sundays preceding Christmas. * The day is the sunday preceding Easter ## Simplifications Obviously one can't trade on certain holidays, but you can omit the check for them in your code. The only exclusion to this rule is Easter or Christmas (for obvious reasons). For example, if the rules above allowed trading on 6th of January and albeit in reality you can't trade due to a holiday, you don't need to take that on the account (and assume that one can trade on 6th of January). ## I/O rules You can take the date in any reasonable format - "DDMMYYYY", "MMDDYYYY" and so on. The output should be a truthy or falsy value (answering the question - can you trade on this sunday?) You can assume the input date to always be a sunday. ## Examples A few examples: * You can trade on 27 January of 2019, due to rule 1. * You can't trade on 13 January of 2019. * You can't trade on 21 April of 2019 - it's Easter. * You can trade on 14 April of 2019, due to rule 3. * You can trade on 28 April of 2019, due to rule 1. * You can trade on 15 December of 2019, due to rule 2. * You can trade on 22 December of 2019, due to rule 2. ## Obvious clarifications * You'll have to calculate the date of Easter and Christmas in the process. * Your program has to work correctly with any other year than 2019. * You MUST take on the account that you can't trade on Easter or Christmas, even if the conditions are satisfied. * You don't need to check for other holidays. # Scoring criterion The shortest code (in bytes) wins. [Answer] # JavaScript (ES6), ~~173~~ 172 bytes Takes input as `(year, month, day)`. Returns **0** or **1**. As anticipated by @streetster, computing Easter is the biggest part. ``` (y,m,d)=>169>>--m&(D=new Date(y,m,d+7)).getMonth()!=m|m>10&(d+3)/14|+D==+new Date(y,2,56-(c=(y%19*351-~((b=(a=y/25>>2)>>2)+a*29.32+13.54)*31.9)/33%29|0)-~(a-b+c-24-y/.8)%7) ``` [Try it online!](https://tio.run/##jc6/boMwEAbwvU/hDkQ2xjZ3hiQe7Im1D@GASRvxJwq0FRLqq1OidsgSJcNN9/u@u5P/8kN5@TiPouursNR2oVPSJhWzDrbGOSHaDS1sF75J4cfwt@Q7xuQxjG99N75T9mrbuXWQbmjFNVOQzbywlt9kMMm3gpaWThGYWOcgfig9WOrtpDB3Dtl1uI/RSI0ctMwzFmuQhimtIzRzytaIFwdeCszEpOSeRTu2lH039E2QTX@kNcUUTEIIJATXDwlRioyXz/ByT4H@V7VvhjssW8vgKQbZw5vXsv0jBbhO/oxCvFHLLw "JavaScript (Node.js) – Try It Online") ## How? ### Last Sunday We use the binary mask `0b10101001` (or **169** in decimal) to encode the 0-indexed months for which it's allowed to trade on the last Sunday. We make sure that **m-1** is one of these months and that adding 7 days brings us to the next month. ``` 169 >> --m & (D = new Date(y, m, d + 7)).getMonth() != m ``` ### Christmas We simply test whether the month is December and the day is more than **10** and less than **25**. ``` m > 10 & (d + 3) / 14 ``` All possible cases are summarized in the following table: ``` Mo Tu We Th Fr Sa | **Su** | Mo Tu We Th Fr Sa | **Su** | Mo Tu We Th Fr Sa | **Su** | Mo Tu We -------------------+----+-------------------+----+-------------------+----+---------- 8 9[10]11 12 13 | **14** | 15 16 17 18 19 20 | **21** | 22 23 24[25]26 27 | 28 | 29 30 31 7 8 9[10]11 12 | **13** | 14 15 16 17 18 19 | **20** | 21 22 23 24[25]26 | 27 | 28 29 30 6 7 8 9[10]11 | **12** | 13 14 15 16 17 18 | **19** | 20 21 22 23 24[25]| 26 | 27 28 29 5 6 7 8 9[10]| **11** | 12 13 14 15 16 17 | **18** | 19 20 21 22 23 24 |[25]| 26 27 28 4 5 6 7 8 9 |[10]| 11 12 13 14 15 16 | **17** | 18 19 20 21 22 23 | **24** |[25]26 27 3 4 5 6 7 8 | 9 |[10]11 12 13 14 15 | **16** | 17 18 19 20 21 22 | **23** | 24[25]26 2 3 4 5 6 7 | 8 | 9[10]11 12 13 14 | **15** | 16 17 18 19 20 21 | **22** | 23 24[25] ``` ### Easter We test whether **D** (computed above) is equal to Easter. The algorithm was taken from [this page](http://web.archive.org/web/20150227133210/http://www.merlyn.demon.co.uk/estralgs.txt) (function *ShortGregorianEaster1*). It returns a day in March which may be greater than 31, in which case `Date()` quietly converts into a day in April. ``` +D == +new Date(y, 2, some_long_and_boring_formula) ``` [Answer] # [Python 2](https://docs.python.org/2/) + `dateutil`, ~~163~~ 157 bytes Possibly could be golfed some more. Even using a library function, calculating the date for Easter still takes up almost half of the code. *-6 bytes thanks to @Arnauld* ``` from dateutil.easter import* y,m,d=input() e=easter(y) print(e.month==m)*((e.day==d+7)-(e.day==d)*(m*d>99))+m/12*(d<25)*(d>10)+(m in[4,6])*d/24+(m%7==1)*d/25 ``` [Try it online!](https://tio.run/##RY7BboMwEETv/gouFTZsE3YNAao6P1L1gGJXWIoBUUctX08NBHp7M6PZnWHybd/RfOu1UXEcz19j7yLdePPw9n4yzbc3Y2Td0I8@YRM40Mp2w8NzwYzaYj4JNoy289ycXN/5ViknEh6UbialdFqK10OEwCX6WtdCpO6MlHD9TkVw9RUzkXIX2e4jh8unSPSZ8mC8lErhqoo5LGQ/rb2bCN/Mr7nxZbeYKaMMELBmK5VAl40qILlQyAjyQLKCHKgIhPXSkBsFDxnWdQkSZBa8bLlHewGrPSS5V6ncq5gfR6pnSoDFgUTsOfB/1vpkm4X4Bw "Python 2 – Try It Online") Accepts input in the form `YYYY, (M)M, (D)D`. Returns `1` if trading is allowed, `0` otherwise. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~109~~ ~~103~~ 101 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` т÷©>3*4÷DV¹19%DU19*15O®8*13+25÷-30%DX11÷+29÷-23+DY-¹D4÷++7%(91O31‰R»9bS30+6ÝδαεŽ5ÂNèδ»}˜12ÐÝ+sδ»«sª²å ``` Input as `year`, `day\nmonth` (multi-line string). [Try it online](https://tio.run/##yy9OTMpM/f//YtPh7YdW2hlrmRze7hJ2aKehpapLqKGllqGp/6F1FlqGxtpGpoe36xobqLpEGBoe3q5tZAnkGhlru0TqHtrpAtSlrW2uqmFp6G9s@KhhQ9Ch3ZZJwcYG2maH557bcm7jua1H95oebvI7vOLclkO7a0/PMTQ6POHwXO1iEPfQ6uJDqw5tOrz0/38jA0NjLiUlJSMTLmMgBQA) or [verify a few more test cases](https://tio.run/##Xc4/S8NAGMfxt1ICAcmlkOe5nO0tdrnZgqIoTUELHVziEBA6CNIhszi3g4PgH7AK0Qily3M4BQ77FvpG4sVBE8cP3@cHz3lyOjoblxcTejcZ3RazntPapDctpzc5KVJVpOV6qnN62OFeqHN1SAvzAdJVByA9EH167nrAGQqdt3ngqiMAnTOUlsiZOm5X98ouGeu4WxL6HDZXL3u0lKN9HrBtPTeZeTVvnyuhp7v63v6wvCxmgPpaz1lSkZ4SeqTF10rflT5l5WCAAXDfwTCKuTP0K0rLThTDH4E3iBDFYa2GDWK3WYXdYi3jP9c6BvYef@cVxY@G3w). (68 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) are used to calculate Easter Sunday.) **Explanation:** Calculate the week before Easter Sunday, using [*@PeterTaylor*'s formula in his GolfScript answer here](https://codegolf.stackexchange.com/a/11212/52210): ``` т÷ # Integer-divide the (implicit) input-year by 100 © # Store it in variable `®` (without popping) > # Increase it by 1 3* # Multiply it by 3 4÷ # Integer-divide it by 4 DV # Store a copy in variable `Y` ¹19% # Push the input-year modulo-19 DU # Store a copy in variable `X` 19* # Multiply the year-modulo-19 by 19 15 # Push 15 O # Sum the three values on the stack together: # year/100*3/4 + year%19*19 + 15 ®8* # Push variable `®` and multiply it by 8 13+ # Add 13 25÷ # Integer-divide it by 25 - # Subtract it from the earlier calculated number 30% # Modulo-30 D # Duplicate it X11÷ # Push `X` integer-divided by 11 + # Add it to top copy 29÷ # Integer-divide it by 29 - # Subtract it from the other copy 23+ # Add 23 D # Duplicate it Y- # Subtract `Y` from the top copy ¹D # Push the input-year two times 4÷ # Integer-divide to top year by 4 + # Add it to the year + # Add it to the earlier number 7% # Modulo-7 ( # Negate it 91 # Push 91 (three purposes: it adds 97; adds an additional 1 to make the # day 1-based; subtracts 7 since we want the week before Easter Sunday) O # Sum the three values on the stack 31‰ # Divmod it by 31 to extract the 1-based month and day » # And join those by newlines ``` Calculate all the other dates that could potentially be a truthy Sunday: ``` 9 # Push 9 bS # Convert it to a binary-list: [1,0,0,1] 30+ # Add 30 to each: [31,30,30,31] 6Ý # Push list [0,1,2,3,4,5,6] δ # Apply double-vectorized: α # Take the absolute difference # [[31,30,29,28,27,26,25],[30,29,28,27,26,25,24],[30,29,28,27,26,25,24],[31,30,29,28,27,26,25]] ε # Map each to: Ž5 # Push compressed integer 1468 Nè # Index the map-index into it δ» # And join it to each individual day with a newline delimiter }˜ # After the map: flatten the list 12Ð # Push 12 three times to the stack Ý # Pop one, and push list [0,1,2,3,4,5,6,7,8,9,10,11,12] + # Add each to 12: [12,13,14,15,16,17,18,19,20,21,22,23,24] s # Swap so the third 12 is at the top of the stack δ» # Join it to each individual day with a newline delimiter « # And merge these to the earlier flattened list ``` Merge it together to a single list: ``` sª # Add the earlier calculated Easter Sunday - 7 to the list ``` I.e. for the year 2019, we now have the following dates that are potentially a truthy Sunday: ``` ["31\n1","30\n1","29\n1","28\n1","27\n1","26\n1","25\n1", # January 31 to 25 "30\n4","29\n4","28\n4","27\n4","26\n4","25\n4","24\n4", # April 30 to 24 "30\n6","29\n6","28\n6","27\n6","26\n6","25\n6","24\n6", # June 30 to 24 "31\n8","30\n8","29\n8","28\n8","27\n8","26\n8","25\n8", # August 31 to 25 "12\n12","13\n12","14\n12","15\n12","16\n12","17\n12","18\n12","19\n12","20\n12","21\n12","22\n12","23\n12","24\n12", # December 12 to 24 "24\n3"] # Sunday week before Easter ``` And we check if the second input is in this list to complete the program: ``` ²å # And check if the second input-string is in this list # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž5Â` is `1468`. ]
[Question] [ **This question already has answers here**: [Calculate A190810](/questions/85411/calculate-a190810) (27 answers) Closed 4 years ago. One of the Klarner-Rado sequences is defined as follows: * the first term is \$1\$ * for all subsequent terms, the following rule applies: if \$x\$ is present, so are \$2x+1\$ and \$3x+1\$ * the sequence is strictly increasing This is [A002977](https://oeis.org/A002977). The first few terms are: ``` 1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ... ``` (\$3\$ is present because it's \$2\times1+1\$, \$4\$ is present because it's \$3\times1+1\$, \$7\$ is present because it's \$2\times3+1\$, etc.) ### Your task Given \$n\$, you must return the \$n\$th element of the sequence. You may use either 0-based or 1-based indexing. (Please specify your choice in your answer.) *0-indexed example:* ``` input = 10 output = 22 ``` Let's see who can get less bytes... *Also featured on [codewars](https://www.codewars.com/kata/5672682212c8ecf83e000050/train/)* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 14 bytes ``` $FDx>DŠ+)˜ê}sè ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fxc2lws7l6AJtzdNzDq@qLT684v9/QwMA "05AB1E – Try It Online") [Answer] # JavaScript (ES6), ~~53~~ 50 bytes 1-indexed. ``` n=>(g=k=>n?g(g[k]|!k++?g[n--,k*2]=g[k*3]=k:k):k)`` ``` [Try it online!](https://tio.run/##DYpBCsIwEEX3PcUIXUwaI1V31mkPUgIJtQ2aMpFW3MScPQY@vMfjv@zX7tP2fH8Uh8ecF8pMPTry1PPg0I1e/w5eysGNrNTRNxdNJTZXTf7mRZkxeQkbMhCcO2C4F7ZtMSkFxApgCryHdT6twaGxWEdOopzruCCLZERXpfwH "JavaScript (Node.js) – Try It Online") ### Commented **Note**: On the first iteration, we have `k = ['']`, which is zero-ish but truthy. By doing `!k++`, we force `k` to be coerced to \$0\$ *right away* (and not just before it's incremented), which makes the test work as expected. ``` n => ( // n = requested index g = k => // h is a recursive function taking k, starting at 0 n ? // if n is not equal to 0: g( // do a recursive call: g[k] | // if g[k] is defined !k++ ? // or k = 0 (increment k after the test): g[n--, k * 2] = // decrement n; set g[k * 2] g[k * 3] = k // and g[k * 3] and pass k : // else: k // just pass k ) // end of recursive call : // else: k // stop recursion and return k )`` // initial call to g with k = [''] (zero-ish) ``` --- # JavaScript (ES6), 65 bytes I thought the `'11'[k/x-2]` trick was neat, but overall this initial approach is far too long. 0-indexed. ``` n=>(g=k=>a[n]||g(-~k,a.some(x=>'11'[k/x-2])&&a.push(k+1)))(a=[1]) ``` [Try it online!](https://tio.run/##FcpBDoIwEADAO6/YA4HdIEi9YvkIIWGDgFrcEqqGBPDrVW9zmDu/2bXzbXqmYi@d77UXXeKgjS65knrbBkw/5sCZs48OF13GSsWVOS7pqaYo4mx6uSuaRBERsq5UTb63MwpoyAsQOIPK/0gSgjUAaK04O3bZaAdsGMNVdvrdcO1RaG@oCHb/BQ "JavaScript (Node.js) – Try It Online") ### Commented ``` n => ( // n = requested index g = k => // g is a recursive function taking k (starting at 1) a[n] || // if a[n] is defined, return it and stop g( // otherwise, do a recursive call: -~k, // with k + 1 a.some(x => // if there exists some x in a[] '11'[k / x - 2] // such that k / x is either 2 or 3 ... ) // && a.push(k + 1) // ... then push k + 1 in a[] ) // end of recursive call )(a = [1]) // initial call to g with k = a = [1] ``` [Answer] # [R](https://www.r-project.org/), 57 bytes ``` n=scan();for(i in 1:n)T=sort(unique(c(T,T%o%2:3+1)));T[n] ``` [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTOi2/SCNTITNPwdAqTzPEtji/qESjNC@zsDRVI1kjRCdENV/VyMpY21BTU9M6JDov9r@hwX8A "R – Try It Online") 1-based index. [Answer] # APL+WIN, 54 bytes Index origin 1 Prompts for the index of required value. Given the response that I received from Grimy and Shaggy that I can assume infinite memory and time then it is trivial to modify this function to work with a series up to the limit of your machine by increasing the value 20 in the function below. This version is limited to index position 1901981 ``` m←1⋄(⍎∊20⍴⊂'m←(0≠1,-2-/m)/m←m[⍋m←m,∊1+mר⊂2 3]⋄')⋄m[⎕] ``` For some reason this function will not run on Dyalog Classic in TIO which is what I usually use. On my machine 1 => 1, 11 => 22 and 61 => 237 (checked on <http://oeis.org>) [Answer] # JavaScript (ES6), 99 bytes ``` x=>eval("a=[i=1],a.b=a.includes;while(i++,c=i-1,x)a.b(i)||!a.b(c/2)&&!a.b(c/3)||(a.push(i),x--);c") ``` [Answer] # [Python 3](https://docs.python.org/3/), 73 bytes ``` f=lambda n,i=0,k=[1]:(i==n)*k[i]or f(n,i+1,sorted(k+[2*k[i]+1,3*k[i]+1])) ``` [Try it online!](https://tio.run/##LcoxDoAgEETRq1AuSiHamexJCAUG0Q26GKTx9EiM3eS/uZ6yJ55qDXi4c/FOsCIcVESj7QyEyLKLhmzKIkCzXqs75bJ6iL0ZP2pp@oeVsoZ2JUEssuNtBa3lfGXiAgGo8Qs "Python 3 – Try It Online") ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/180822/edit). Closed 4 years ago. [Improve this question](/posts/180822/edit) Your program should find the number of string pairs (pairs of 2) that contain all vowels (a e i o u), when given an integer `N` and `N` strings. There are easy ways to do this, but I'm looking for the quickest possible solution. **Example**: **INPUT:** ``` 4 password unique orbiting ointmental ``` **OUTPUT:** ``` 2 ``` **EXPLANATION:** `password` has `a,o` `unique` has `u,e,i` `orbiting` has `o,i` `ointmental` has `o,i,e,a` --- The pairs `password` and `unique` `ointmental` and `unique` are the `2` successful combinations. --- Here's a sample [DataSet](https://drive.google.com/open?id=1O2A7cE7xBhWHDzd4jzs4o-EBckQ27RHY) where `N` = 10000 [Answer] # Java openjdk8 Using bit arrays, Coding each word on an int where if `a` is present the lowest bit is 1, if `e` the second is 1, etc. For example `password` has a and o, so its code is `1|8` == `9` == `0b01001`. As we only need the number of pairs we can store the number of words for each code in an array of size 32. Then for each pair of different indexes except the last (31) where first is less than second and where bitwise or of indexes is 31, we multiply the number of words with code, and the last is particular because it's the only one that can make a pair with a word of the same code, and also with any word. ``` public static void main( String[] args ) { int[] a = new int[ 32 ]; int count = 0; try (Scanner scan = new Scanner( System.in )) { while ( scan.hasNext() ) { String s = scan.next(); a[ code( s ) ]++; } } int t = 0; for ( int i = 0 ; i < 31 ; ++i ) { count += a[ i ]; for ( int j = i + 1 ; j < 31 ; ++j ) { if ( ( i | j ) == 31 ) { t += a[ i ] * a[ j ]; } } } t += a[ 31 ] * count + a[ 31 ] * ( a[ 31 ] - 1 ) / 2; System.out.println( t ); } // a e i o u // 1 2 4 8 16 public static int code( String s ) { int r = 0; for ( char c : s.toCharArray() ) { r |= c == 'a' ? 1 : c == 'e' ? 2 : c == 'i' ? 4 : c == 'o' ? 8 : c == 'u' ? 16 : 0; } return r; } ``` [TIO](https://tio.run/##dVPLUsIwFN33K87OQscij3EcsOM4rnXDkmERSoTUkjB5qIzw7XhTAgWsWTQ5NyfnPluwT3ar1lwW84/9XqzWSlsUZEydFWU6zpmUXI@iaO1mpciRl8wYvDIh8RNFoBUujGWWtk8l5ljRdYyx1UIuJlMwvTBoER9hCWm9GRkk/6oQ@j1MR@cE5MrRN8NdbbZ6gziEBEN7UAgmcrkxlq9SCq517s@vr6UoOeLqWbpk5o1/27iFa5pfh8BhSL1iy4o6@sNjEwpyzkmTZKZJcsnYRfXpIrGrpN6VprD8hfAXGNH@iH6XDkki/gR4KEuSee/ivGaXWgVpCSTwMkWtVzQmLN7pFb3DFp6QZZ7eRKyaUDtH2x@K6ygus/@3Fkch8uWVQmJHSzsOh9tuq9OrHYQWK2fTNbXJljRpFqE7Qb3ToeHiFKGCOxq66GGAB3TvG6b2MG@@lafeX80rdFPX8iXTyDGESa16IfCsNds0jJXGNiMiVfaG3eCJohkGyD3snaDwcHCCysOHE3TV23vCZ6HUxdXcOi3hf9fDxW6/53OXU45KRsxZtVIz@g1@AQ) # C++ translating to C++ is straightforward [test with 100 first words](https://tio.run/##fVfbdqW4EX2vryAra830xDOJwT6@pNudD8nqB11BCF0RSGLS397RsdscbBjzcIy2SrXrqjLE2j9aQn78@LvQZJgo@yLMGDxD6ivANArdVhopNlpEWDUG@hkAhA4VMZR9KoA/S5Q/1W/Vn1CV57zpq6fq@vPzkhtffapIh/wvFan@/Ub0/Pjqf09l4@mp@hX9Wv2nqovMy5Kdl826FOfl7bo05@XDupyez96V9U/e78@/noXJ68p/hu8vZisk9Ketqei/1U1TfSsG/1ldV99fDsdODOxsttBvjP3prtB2Cp9X9Cz19et7VPCi4G/P4D@ZsiEX2q2u81PIX@L4LFa2v11dXTS8uPDTpLOt4RzW38uRSYdLhEN19XTWVBcv/vHsz3V5uzq/Na9Q8/gK3azQwx7aS511vaW5XaXvX6VPK3S3h/ZSF/vuVqnTe5q7vYK7vZ33K3S7h0576O49zf2e5n4fofsPmC/ePKxSN@9pHtet5lX6cSv9DrrorK9XsfoA2xFt9lZT67UymusDrD7AmgNsz1XvI7XBDvg3fq2lWT/usQOuZp@oeq3S@uEAe9xjG79uPuC62dfzBjvg3/i1tkd9f4A97rhuD/Jwuy@NDXY6wA64mj3X2oH1xa/Tgb2ng7ieDuJ62tbVX3Ft/Dod5OF04Otp39Ub7PQB14FfzYFfzYFfzYFf@9uvPuj7@uFAx@MB1@NHcnuu5nrvQ1Pvfd1gB3KbadD8dQybg/5qDsZHc7PPzQY7HWC7O7c56KXmYC41Nx/xb/z6IF/NwdBoDm745v4juQ3XQb5e5vEL36UotjP4dabu5W@303Gdcq8TZi//sJ0Vl2mw3rP7E/XbO@9yS6y1fnDm0kf3b6r86u0ttj1zmS2Xjr/0eXPo/aaGLpVzt43/wZmHN7m4Os77zUv9/zy4QT6V95v6W/VHXf32r2ZVH6ovX6rnH6bpcP538ccPougcbCd4D5bxeXCpDQjcghfTknHoQBjCvWEaC5gnKmLA1kpYePRmUb3rIcxt6Oc0Rgu5a8PEjJ8iiDmwZNvZEphIHlnHJuPApDDrWZBlBt1NRp@1TJDxSGaNElHgqY9SODYI4EHZgYlADNhIB9xl5xx0CMvEJ0uLDYnkLC1KAkj0SgUULQKElGLKy@QhuUyXlnAqAEVssYoeEejp0I1LdI5B@QKYYsQRd4Cj8Tz7BWMIxpVPArrEAZCTxjNsmAcj@IgyC2MHbTdZvTiyaEChn3Qfxn6AATstJE@IQXR9l@NkSQSdmJ1NCQGFLs7O0iwlBzoYGZzMgwFCyqcH5iJFsJIaO0/OkGI67slQspTBTtTS1PYtBW9S78dxUhKQzJkkLMQAIlIWjJeDhyGgFDvOBwXO@pCkdEmCGjj2nrMuA2nn1HV40AmMxDOOeRQOsJAo66U92@BGKkSQuYUxBjrMSVoF09JnJDquFiBhllPqrNTAxxI5Oo6ew0IWZmYfvIJMEEdUcDGCDH20WS2dBheM7DpDNQKRhEDd0peo83HqlUU4LCBxlnlGs1Mg6ahbY/HQgzEt5lhmM4OaxmFRNOUFek9xO4xpTjCSEbk2ET6DyW1JhaOOgG77VMJk/AxD6l3oCLXF43GMbZpml4BIo6XCaRwg0kDpNEwsAfPK8kSGFMCX6hy56Ke@lGci3ZhHhGGJmkUrltIBUcyGBzPQDG1UHk06BQUDmuTCRZc4dIPvMWGDYjDpHIOcWVuKaw5RjGbmErQUvS3bnAMecYiTC3OJjsUIWe0igkF0xQ2LugBqUdlQyjWFwS4oz9plDFgLY@aWTQ6W0sGYeKIExDYsKiw5ckgBK8KWTB1E3FLXISsXEJ6UirFmaUEbt6ABLZTAQmeqLC0RhmXhpUCVpyO0LUWUljcHvLREJnMoFIzZ7KSbcVvSXWpTj5Kl/wM) test on TIO with 10000 words of dataset ``` 1968503 Real time: 0.419 s User time: 0.315 s Sys. time: 0.099 s CPU share: 98.83 % Exit code: 0 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/) Two solutions designed by my esteemed colleague [Marshall](http://www.dyalog.com/meet-team-dyalog.htm#Marshall), master of speeding up APL. The formulas used are both in '70s APL, so they works in APL\360 on an IBM/360 mainframe. They are anonymous prefix functions taking a character matrix as argument. `N` is not needed but may be supplied as optional (and ignored) left argument. ### The first solution is *O*(*n*2) A naive approach: ``` {0.5×(+/,(⍉i)∧.∨i)-+/∧⌿i←∨/'aeiou'∘.=⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqAz3Tw9M1tPV1NB71dmZqPupYrveoY0Wmpq62PpD9qGd/JlAVUERfPTE1M79U/VHHDD3bR71ba4H6FR61TVRPTSlNTizJzM9TV1BPLC3Jz81PysxJVeeCyBYkFheX5xelACVL8zILS1OBjPyipMySzLx0EDMzryQ3Na8kMQekQcPC0PJRz7ZHfVMdNaPtDQ2AQMHQ4FHvFiOzWAA "APL (Dyalog Unicode) – Try It Online") Processes\* the large data set in about 4.5 ms. TIO takes about twice that. `{`…`}` "dfn"; the argument is `⍵`:  `'aeiou'∘.=⍵` equality 3D array with vowels along the first axis, words along the middle axis and characters along the last axis  `∨/` OR-reduction along the last axis; this gives us a 5-row table with one column per word  `i←` store that in `i` (for **i**n)  `∧⌿` AND-reduction along the first axis; this gives us a mask of words that contain all vowels  `+/` sum; count of words containing all vowels (we need to discount their "self-pairs")  `(`…`)-` subtract that from the following:   `(⍉i)∧.∨i` the Boolean matrix where the OR of corresponding masks is all-true.   `,` ravel (flatten)   `+/` sum; this gives us the count of ordered pairs  `0.5×` halve; this gives us the count of unordered pairs ### The second solution is *O*(*n*) Breaks even with the above *O*(*n*2) solution at about 150 words of 10 evenly distributed characters. It requires 0-based indexing, and a pre-computed 32-by-32 Boolean vowel signature pairing table: ``` { a←0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 a[2⊥∨/'aeiou'∘.=⍵]+←1 (0.5×lׯ1+l←a[31])++/,p×a∘.×a } ``` Processes\* the large dataset in 0.09 ms. TIO's timing is too inconsistent to make any conclusions, but it is likely that it takes about twice the time here too. --- \* 64-bit Dyalog APL 17.0 on 2.6 Ghz i7-4720HQ ]
[Question] [ **This is inspired by the excellent [Visualize Visual Eyes](https://codegolf.stackexchange.com/q/153366/56555) challenge. It is posted with permission from and credit to @Jordan** We are going to create an ASCII art approximation of the Xeyes challenge but without worrying about the actual mouse movements. Just the positions. **EDIT** I thought about whether this could be seen as a duplicate but I don't believe it is. * The previous question required detecting mouse movement. This does not and so is open to many more languages.This is simple interactive ASCII art which can be attempted in any language. * While the algorithm for the eye movement may be similar, this is in many ways simpler to achieve. * I'm not convinced that any answer given so far to the previous question could be trivially ported to this. * I don't think I am good enough at languages that could answer the previous question to attempt it. I would have a try at this one. If consensus is that I am wrong then I am happy to delete the question. I have removed the comment about "interesting answer" as this is intended to be code golf. **Overview** In all cases the mouse position will be represented by an X. Here are the eyes with no mouse position (cursor is off screen): ``` /---\ /---\ | | | | | O | | O | | | | | \---/ \---/ ``` Now let's say your mouse is to the right of the eyes: ``` /---\ /---\ | | | | | O| | O|X | | | | \---/ \---/ ``` and now at the bottom left: ``` /---\ /---\ | | | | | | | | |O | |O | \---/ \---/ X ``` and now at the top: ``` X /---\ /---\ | O | | O | | | | | | | | | \---/ \---/ ``` From this we can see that (in it's simplest case - we could make it a lot more complicated but let's not do that for now) there are 9 different positions for the eyes and nine different positions for the cursor as shown below: ``` 1 2 3 /---\ /---\ |123| |123| 4|456| |456|6 |789| |789| \---/ \---/ 7 8 9 ``` Position 5 represents no cursor (off screen). The eyes are both looking forward. **The Challenge** Take an integer (or any representation of an integer) between 1 and 9 inclusive and output the eyes if the cursor was in the position of that integer. You must include the X as the position of the cursor (except when it is off screen i.e. the eyes are looking forward - no X). **Rules** * Input format is your own choice. * Program or function. * Any amount of leading or trailing whitespace is allowed. * Output must consist only of the characters /\-| and either upper or lowercase x and o. * Assume that the input will always be valid, i.e. an integer between 1 and 9 inclusive. * Feel free to change the order of the integers if it helps i.e. 2 does not have to be top and 5 does not have to be no cursor. * Standard loopholes prohibited as usual. * This is code golf. Shortest answer wins. **Test Cases** Note: All test cases use the numbering sequence detailed in the explanation. As stated in the rules, you do not have to use the same number sequence. ``` Input = 5 /---\ /---\ | | | | | O | | O | | | | | \---/ \---/ Input = 6 /---\ /---\ | | | | | O| | O|X | | | | \---/ \---/ Input = 2 X /---\ /---\ | O | | O | | | | | | | | | \---/ \---/ Input = 7 /---\ /---\ | | | | | | | | |O | |O | \---/ \---/ X ``` This challenge has been in the [sandbox](https://codegolf.meta.stackexchange.com/a/14572/56555) for the last week. [Answer] # [Clean](https://clean.cs.ru.nl), 253 bytes ``` import StdEnv ?n=flatlines[[if([(0,0),(6,0),(12,0),(0,3),(0,9),(12,3),(0,6),(6,6),(12,6)]!!(n-1)==(v,u))'X'b\\b<-[' ':a++a]&v<-[0..]]\\a<-[spaces 6,['/---\\ ']]++[['|':[if(n==i)'0'' '\\i<-[j..j+2]]]++['| ']\\j<-[1,4,7]]++[['\\---/ '],spaces 6]&u<-[0..]] ``` [Try it online!](https://tio.run/##NU9Nb8IwDL3vV4QLbtSktLAVDS3ish0m7cZlUpxDWgpK1Qa0fkiT@O3LvHZcbL/n52e7bCrrQ3s5Dk3FWut8cO318tWzQ3988@PD3qtTY/vG@arT2p0iHaUi5SLKp5itp5SKzRSfZ2oG@aTKZyrnZrGIvMy4UtEoBs7hEwrE4kVqYLCzcWzNciSUJokxiJbK7mrLqmO50LCSUiIyMCaOtYYb7P6O8Uo5DimQA6KjiTpJ6nhtJhXcSI5YE52JR7H9H0UkqxW1xN3eLIf73nDoLT2v2J49hZ@SXj93Qb5/hNdvb1tXEih@AQ "Clean – Try It Online") This is mostly a port from [my answer to the other question](https://codegolf.stackexchange.com/a/153412/18730). [Answer] # [J](http://jsoftware.com/), 119 112 bytes ``` d=.y-1 a=.'O'(d{,{;~2+i.3)}7 6$42$' /---\ | | | | | | \---/' ' '(<3 6)}'X'(d{,{(;+:)3*i.3)}a,.a,.' ' ``` [Try it online!](https://tio.run/##y/qfbmtlrGClYPA/xVavUteQK9FWT91fXSOlWqfaus5IO1PPWLPWXMFMxcRIRV0BAvR1dXVjFGqArBoUMgYorq/Opa6grmFjrGCmWaseATFIw1rbStNYC2xWoo4eEAHV/NfkSk3OyFdIV0gtSy2qVLCzytSz5PoPAA "J – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), ~~150~~ 140 bytes ``` $x=shift;$_='9 8 7 /---\ /---\ 09870 09870 606540';$t=reverse;y/98764/12346/;$_.=" $t";s/(\d)$x(.)/\1O\2/g;s/$x/X/;y/0-9/| /;say ``` [Try it online!](https://tio.run/##LYzLCsIwFET3/YpQAm0Xyb19JG255BvcugiIYLSCC0mitOC/xyidxVnMYebp/EOlV3BMSWyREl9NWO7XSPxkqpn9Mv05FgyEEHZnwXCeRtxZaNRqwIp4NN69nQ@ONshKD9B2/aAh/0lTMh5LClDbS8PXWjZg24Pt4JY7vsIR8gjFDB8GFM5bSqn/Ag "Perl 5 – Try It Online") ## Explanation ``` $x = shift; # Shift the first value off the input argument array. # Assign template string to default pattern-search variable. # Only use first half of output. Use 0 instead of |. $_ = '9 8 7 /---\ /---\ 09870 09870 606540'; $t = reverse; # $t is the reverse of $_. y/98764/12346/; # Correct digits in first half of template string $_, # so 9 becomes 1, 8 becomes 2 etc. $_ .= " $t"; # Append the two halves of the template. s/(\d)$x(.)/\1O\2/g; # Regexp replace all occurrences of $x, preceded by # a digit and followed by any non-newline character, # by "O" and the original surrounding characters. s/$x/X/; # Replace last remaining occurrence of $x by "X". y/0-9/| /; # Replace 0 by |, and all other remaining digits by a space. say # Print $_ followed by a newline. ``` ]
[Question] [ # Task Write a program/function that, given three integers **n**,**a**,**b** prints a regular expression which matches all of the base-`n` integers from `a` to `b` (and no integers outside of that range). Your algorithm should, in theory, work for arbitrarily large integers. In practice, you may assume that the input can be stored in your data type. (don't abuse native data type, that's a standard loophole) # Input Three integers, `n, a, b` where `n` is in the range 1-32. `a` and `b` may be taken as base-`n` string/character list/digit list. # Output A single string, represent the regex. # Rules * Base-n integers use the first `n` digits of `0123456789ABCDEFGHIJKLMNOPQRSTUV`, you can choose to use upper-case or lower-case. * `a` and `b` may be negative, denoted by a `-` in front of the integer * You may assume `a ≤ b`. * Any regex flavor is allowed. * The behavior of the regex on strings not a base-n integer is undefined. # Winning criteria Answers will be scored by the length of the code in bytes. (so [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` ŸεD0‹'-×sÄIB«}'|ý ``` [Try it online!](https://tio.run/##AS0A0v8wNWFiMWX//8W4zrVEMOKAuSctw5dzw4RJQsKrfSd8w73//zEwMDAKLTUKMzI "05AB1E – Try It Online") For some reason I don't seem to be able to replace `I` with `³`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` ƓØBḣḊ;0 rµṠṾṖ$€ż⁸Aṃ¢¤j”| ``` [Try it online!](https://tio.run/##AUEAvv9qZWxsef//xpPDmELhuKPhuIo7MApywrXhuaDhub7huZYk4oKsxbzigbhB4bmDwqLCpGrigJ18//8xMv8tNf8yMA "Jelly – Try It Online") Take 2 input from command line argument as decimal number, and base from stdin. [Answer] # [Python 2](https://docs.python.org/2/), 157 bytes ``` n,a,b=input();s=o='' for i in range(a,b+1): if i<0:i=abs(i);s='-' if i==0:o='0'+o while i:i,r=i/n,i%n;o=[`r`,chr(55+r)][r>9]+o o='|'+s+o;s='' print o[1:] ``` [Try it online!](https://tio.run/##JczRCoIwFMbx@z3FuYlNNmkTLJqdXkQENTQPxJlMI4LefSndfvz@3/xZp8BFSmw60yPx/FpVVi0YUEoxhggExBA7fgxqE9plXgCNQFfrCbt@UbRzmcv/jGj91lqpg4D3RM8ByJOJSEc2dOAqYN3G1tynqMpSx6yp4@3S7HrLvlIvOux/UsyReIVQO9@k5E4md2dT2B8 "Python 2 – Try It Online") ]
[Question] [ ## Definition: > > A number **m** is called a primitive root of a prime **p** the condition that the smallest integer **k** for which **p** dividies **m****k****-1** is **p-1** > > > ## Your task Given a tuple **(a,b)** of positive integers, return the fraction: (number of primes **p** equal to or less than **a** which has **b** as a primitive root) divided by (number of primes equal to or less than **a**) ## Test Cases Assuming [Artin's Conjecture](https://en.wikipedia.org/wiki/Artin%27s_conjecture_on_primitive_roots) to be true, giving **(A very big number, 2)** should return a value around **.3739558136...** **The challenge is for the fastest code, not necessarily the shortest one.** ## Timing My crappy code takes 10 seconds for a million on my PC (intel i3 6th Gen, 8GB RAM, others I forgot), so your code should naturally beat that speed. This is my first challenge. Feeback is appreciated. :) [Answer] # [C (gcc)](https://gcc.gnu.org/) Around 0.6 sec for 1,000,000. ``` int modpow(long b,int e,long n){ long r=1; while(e){ if(e&1) r=r*b%n; b=b*b%n; e>>=1; } return r; } float f(int a,int b){ int ln=1; for(int p=2;p<=a;p*=ln,ln++); int* primes = malloc((a+1)*(sizeof(int))); int** factors = malloc((a+1)*sizeof(int*)); primes[0] = 0; primes[1] = 0; for(int i=2;i<=a;i++){ primes[i] = 1; factors[i] = malloc(ln*sizeof(int)); } factors[1] = malloc(sizeof(int)); factors[1][1] = 0; for(int p=2;p*p<=a;p++){ if(primes[p]){ for(int j=p*2;j<=a;j+=p){ primes[j] = 0; factors[j][0]++; factors[j][factors[j][0]] = p; } } } int count1 = 0; int count2 = 0; for(int p=2;p<=a;p++){ if(!primes[p]) continue; count2++; int n=p-1; int m=p-1; int prim=1; for(int j=1;j<=factors[n][0];j++){ int q=factors[n][j]; if(modpow(b,n/q,p)==1){ prim=0; break; } while(m%q==0){ m/=q; } } if(m>1){ if(modpow(b,n/m,p)==1){ prim=0; } } count1 += prim; } return (float)count1/count2; } ``` [Try it online!](https://tio.run/##dVPbjpswEH2Gr2C3SmUM28R5ZZ0fafMAxOyamrFDiFbaKt@eenwJZNNGQrJnzpw5c5xpX97a9vpNQqvOB5G9nqaDks2P9116F5Pahq4SpmzQB6M/iNLwljUlRkTpLpD/SRN3Gjmr0uTjXSpBBEYT2RHxneU2M9JmBTabNLyJR7HbuYpLmoxiOo@QjVV6STul6ynrCPaoXacGyfCgwBV0enRZw7eVeeV1ZShXUCooirxySJqZUQ7ilPFsqJXSLSF1wXJKTvJTaMed5xFLs65uJz0@oGcwdWDP@XOzt8DNfGfxHnVJq0uiLmkFoQ8BKBGIAyShoY@EngroUp03JgLZAvgFNUMelTiHqPcoaLFvEuSYvQvcwD03dFv1CO4Lbnwyau8jdTKr7/fWi6J4CN7lsc44iB0Hv4t/y1afYWKB9BbY/muAL/KfZv22CCYJZ4ENPIHXg7XAzQuLl2F5QQLuH@I2O8PJo3JA5dYF39PVHJfJfu8msmLCXjQlrI@lyTlnC994MKwZRf375kFYkWF15HwT0MOaH5cmOepd4LpvM/yvTSwNzhbczXm3YMQtV@4Ra2@Y3Tm/4bUEv3RIbUth6sjzqvsFz2VH2Mb9yi3@5y7Xvw "C (gcc) – Try It Online") [Answer] # Mathematica ``` (t=0; f=PrimePi[#]; d=#2; For[i=1,i<=f,i++,If[PrimitiveRoot[Prime[i],d]==d,t++]]; N[t/f])&[1000000,2]//AbsoluteTiming ``` [Try it online](https://sandbox.open.wolframcloud.com/) Paste the code and press shift-enter Takes 3.2 sec to find 1.000.000 [Answer] # C++11 + [libop](https://github.com/orlp/libop) 1.23 sec on my slow laptop for 10,000,000. ``` #include <cstdint> #include <vector> #include <algorithm> #include <iostream> #include <utility> #include "libop/op.h" // Returns 2^-32 mod m, -m^(-1) mod 2^32 inline std::pair<uint64_t, uint64_t> mont_modinv32(uint64_t m) { uint64_t a = 1ull << 31; uint64_t u = 1; uint64_t v = 0; while (a > 0) { a = a >> 1; if ((u & 1) == 0) { u = u >> 1; v = v >> 1; } else { u = ((u ^ m) >> 1) + (u & m); v = (v >> 1) + (1ull << 31); } } return std::make_pair(u, v); } // Returns (ab)R mod n given aR mod n, bR mod n, n and -n^(-1) mod R, with R = 2^32 inline uint64_t montmul32(uint64_t a, uint64_t b, uint64_t n, uint64_t nneginv) { uint64_t T = a*b; uint32_t m = T*nneginv; // m = T*-n^(-1) (mod 2^32) uint64_t t = (T + m*n) >> 32; return t >= n ? t - n : t; } double f(uint32_t a, uint32_t b) { std::vector<uint32_t> primes; op::primes_below(a + 1, std::back_inserter(primes)); int num_primitives = 0; for (auto p : primes) { if (p == 2) { num_primitives += b == 1; continue; } uint32_t s = p - 1; uint32_t pneginv = mont_modinv32(p).second; uint32_t montb = (uint64_t(b) << 32) % p; uint64_t mont1 = (1ull << 32) % p; uint32_t pows[32] = {montb}; for (int i = 1; s >> i; ++i) { montb = montmul32(montb, montb, p, pneginv); pows[i] = montb; } bool primitive_root = true; for (auto& kv : op::factorization(s)) { uint32_t e = s / kv.first; uint64_t r = mont1; for (int i = 0; e; ++i) { if (e & 1) r = montmul32(r, pows[i], p, pneginv); e >>= 1; } if (r == mont1) { primitive_root = false; break; } } num_primitives += primitive_root; } return num_primitives / double(primes.size()); } ``` ]
[Question] [ Inspired from a real problem; we were looking at this table and said "Hey, now that's a good codegolf problem." The [KOOS Jr. scores](https://www.hss.edu/files/KOOS-JR-Scoring-Instructions-2017.pdf) converts from a raw number to a percentile score given this table: ``` Raw summed score Interval score (0-28) (0 to 100 scale) 0 100.000 1 91.975 2 84.600 3 79.914 4 76.332 5 73.342 6 70.704 7 68.284 8 65.994 9 63.776 10 61.583 11 59.381 12 57.140 13 54.840 14 52.465 15 50.012 16 47.487 17 44.905 18 42.281 19 39.625 20 36.931 21 34.174 22 31.307 23 28.251 24 24.875 25 20.941 26 15.939 27 8.291 28 0.000 ``` Provide a program, function, expression, or source file generator\* that given the input raw number returns the interval score number. You may accept your input as a string or number and may produce your output as a string or number. Trailing zeros after the decimal point may be included or omitted. You may not however use scaled integers: 1 must really return 91.975 not 91975. \*source file generator must output a valid source file for some language you specify; just outputting the table is not allowed. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 59 bytes ``` •G‚Œιã¶&‡Vc–QΩ`ååI~(Ìö{3.ùSÿ{Ćι¯TærÆcï`₃āÀ}ªHÕ¶η•4ô.¥R3°/Iè ``` [Try it online!](https://tio.run/##AW0Akv8wNWFiMWX//@KAokfigJrFks65w6PCtibigKFWY@KAk1HOqWDDpcOlSX4ow4zDtnszLsO5U8O/e8SGzrnCr1TDpnLDhmPDr2DigoPEgcOAfcKqSMOVwrbOt@KAojTDtC7CpVIzwrAvScOo//8x "05AB1E – Try It Online") **Explanation** `•G‚Œιã¶&‡Vc–QΩ`ååI~(Ìö{3.ùSÿ{Ćι¯TærÆcï`₃āÀ}ªHÕ¶η•` is a compressed version of the input constructed by: * multiplying each element in the input by 1000 * reversing the resulting list * calculating deltas * joining to a single base-10 number * compressing to base-255 The rest of the code is then: ``` 4ô # split in pieces of 4 .¥ # undelta R # reverse 3°/ # divide each by 1000 Iè # index into list with input ``` [Answer] # [PHP](https://php.net/), 152 bytes ``` <?=intval(substr("255s1yyv1ta01pnu1mwc1kla1ik01gos1ex61d7k1bin19th183816bc14hd12l810n30ynd0wmh0ukp0shv0qda0o5n0lsr0j6z0g5p0car06eb0",$argn*4,4),36)/1e3; ``` [Try it online!](https://tio.run/##Hc5LDoIwFAXQOctoHIAh8V0KFYPIWsonFAulUj7i5tE4PaNjlT3uhVXWO8mpNTnjLPOKx8/yzsyr7H23lG6efBYlicO@r5glwZoFw1ZB9xKdJrSjQ/MWqK8aZWdwmxVSnkKUFWJVI@pTkOG0m5q2QdGiLTm10quWNCaGejfRU3yoTSxVciLRlMTCf@kch3EQchFc0PDsOL4 "PHP – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~166~~ ~~160~~ 139 bytes ``` lambda n:sum(int('6533222222211111111111222356EWU1LC74210ZYWTRQPOPRV1BRMO6BGYASWNLUSWQ55ZW96XMM8A2I6VX'[i::28],36)for i in range(28-n))/1e3 ``` [Try it online!](https://tio.run/##XY7BCoIwAEB/ZTc3MGpbLh100IgINE3TqdXBSGuQU8wOfb0JHYLe7fEur33390aRoVqehkdRX64FUPz5qqFUPdSYQSn5gn@MRg22FjF2V4s5wbM8E4dwH/hBmGAn9HzmbDI7Ejs3jsTeMHJhsdTzTJtsWZJqR8k5Mc86ZahqOiCBVKAr1K2ExJwohKa4pMN/sRAHbTdOAamDCko0fAA "Python 2 – Try It Online") Edit: golf 6 bytes from glaring redundancy of `2`'s...; also saved 21 bytes by switch to base 36 (thanks ovs!) and using `1e3` instead of `1000.` The string is an encoded list of the 28 4-digit deltas. [Answer] ## Python 3, 133 bytes ``` lambda k:sum(int('5ukygji75mxo64d3f5vstve68rdiq42l8nof8cs35qyb5bdtzihbhk086m8nel1nx3kqxvn',36)//8292**i%8292for i in range(28-k))/1e3 ``` It uses packed differences, and sums them. To pack efficiently, rather than using binary, it's packed in a number that's effectively base 8292, and that number is embedded in the code as a base 36 literal. [Answer] # [Stax](https://github.com/tomtheisen/stax), 59 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` â¬∟╧↓┘╟╤éJ{súÇaz░«╝╬°╢=♦Γ┘=▐▬[è2Ü←`‼frl¢£≤kpOy‼5¶^≡%#ßî↕V0Å ``` [Run and debug it](https://staxlang.xyz/#p=83aa1ccf19d9c7d1824a7b73a380617ab0aebccef8b63d04e2d93dde165b8a329a1b601366726c9b9cf36b704f791335145ef02523e18c1256308f&i=0%0A1%0A27%0A28&m=2) [Answer] # Mathematica, 196 bytes ``` (100-Accumulate[{0}~Join~IntegerDigits@9753332322223223323323344578])[[#+1]].{0,975,6,914,332,342,704,284,994,776,583,381,14,84,465,"012",487,905,281,625,931,174,307,251,875,941,939,291,0}[[#+1]]& ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~147~~ 146 bytes *-1 byte thanks to @JörgHülsermann* ``` lambda k:sum((int('9CU7OK2L6V5W6E8QYM3YL0TRGZIJ6Y14N43TRVCAXF6C58HP69ZC4536JNILBUC45C5S8G4DIT0J',36)&2**(14*-~i)-1)>>i*14for i in range(28-k))/1e3 ``` [Try it online!](https://tio.run/##Xc67DoIwAEDR3a/oJC2RSGmpQKKJ1heILwQU44IRtFHAoA4u/jri6naTu5z7@3kpclKl3UN1i7PjKQZX6/HKIBT5E0omDzrLmeayUN@ykbGO5iRyVd@b7G2HRZguKPG9kPd3Y8Z1Y7pi5p5TnTBnYbuDoE6ub4wJHdq@6kgtwlBTk2WIqax8BFIw6vWEjGlalEAAkYMyzs8J1AzlilAbJzXr75jIagBwL3@4FAqEqi8 "Python 3 – Try It Online") ]
[Question] [ It's really frustrating when I'm working and I have a ton of windows open that are completely or partially hidden behind other windows. To make things worse, I'm still using two 1024x768 monitors. Your task is to take a list of coordinates that designate the area, in pixels, on a screen, that a list of windows occupy and output a truthy value if, for a 2 monitor set-up with 1024x768 resolution, all the following conditions are met: * None of the windows would overlap, * None of the windows would be partly off screen * None of the windows would straddle a boundary between the two monitors (so the order in which you visualize monitors 1 and 2 is irrelevant) And a falsey value if any of these criteria are not met. You may assume that all windows are rectangular, and that no coordinates are negative in the input, which is in a file, in stdin, or in a list of tuples, is in the following format: ``` monitor-number left-x bottom-y right-x top-y monitor-number left-x bottom-y right-x top-y monitor-number left-x bottom-y right-x top-y ``` Where each line contains the ID of the monitor (which can either be in `[1, 2]` or `[0, 1]` depending on which is easier for your language), and the dimensions of a window. For example, the following input will result in a truthy output because none of the windows overlap: ``` 1 10 10 100 200 1 210 300 600 600 2 10 10 100 200 ``` The following input will result in a falsey value because lines 1 and 3 result in an overlap: ``` 1 10 10 50 50 2 5 5 600 200 1 20 20 80 80 ``` The following input will result in a falsey value because it would partially off-screen on one of the monitors: ``` 1 1000 400 1400 300 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest solution wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 33 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` <⁽¡ð,769FẠ Ḋs2Zr/€p/;€Ḣµ€ẎµQL⁼LȧÇ ``` A monadic link taking a list of lists of the window-data and returning `0` if any windows exceed their monitor's space or overlap, or `1` otherwise. Uses 1-indexed monitor IDs; `1,1` to `1024,768` inclusive are considered on-screen. **[Try it online!](https://tio.run/##y0rNyan8/9/mUePeQwsPb9AxN7N0e7hrAdfDHV3FRlFF@o@a1hToWwPJhzsWHdoKonf1Hdoa6POocY/PieWH2////x8dbahjaABBBjpGBgaxOkARIyDfGMQ3NNMxNjQDihnBVJkCFcXGAgA "Jelly – Try It Online")** (Too slow for the first two test cases! Typical golf :)) ### How? The reason this is so slow is because it creates all the pixels for all the windows, each with its monitor ID and checks for overlap using de-duplication (which is implemented using lists not sets). It also checks each pixel is on-screen rather than checking just the input corners. All in all very inefficient... Test-case 1 succeeded (`1`) locally in **only** eleven minutes! Test-case 2 succeeded (`0`) in less. ``` <⁽¡ð,769FẠ - Link 1 check pixels are on-screen: list of lists, each being [x,y,ID] ⁽¡ð - literal base-250 integer = 1025 ,769 - pair with literal 769 < - less than (vectorises) -> [[x<1025, y<769, ID],...] F - flatten into a single list Ạ - all truthy? Ḋs2Zr/€p/;€Ḣµ€ẎµQL⁼LȧÇ - Main link: list of lists, each being [ID,Lx,By,Rx,Ty] µ€ - for €ach window: Ḋ - dequeue -> [Lx,By,Rx,Ty] s2 - split into twos -> [[Lx,By],[Rx,Ty]] Z - transpose -> [[Lx,Rx],[By,Ty]] /€ - reduce €ach with: r - inclusive range -> [[Lx,...,Rx],[By,...,Ty]] / - reduce with: p - Cartesian product -> all pixels, [[Lx,By],[Lx,By+1],...[Lx,Ty],[Lx+1,By],... ...[Rx,Ty]] Ḣ - head -> ID ;€ - concatenate each pixel with the monitor ID Ẏ - tighten -> one list of all window's [x,y,ID] values µ - monadic chain separation, call that w Q - deduplicate (unique [x,y,ID] values) L - length L - length of w ⁼ - equal? Ç - call last link (1) as a monad (all on-screen?) ȧ - logical and ``` [Answer] ## Haskell, ~~103~~ 88 bytes ``` f l=[]==[a|z@(m,a,b,c,d)<-l,y@(n,e,f,g,h)<-l,y/=z&&m==n&&e<c&&(b<h||f<d)||1024<c||768<d] ``` Forgot the bounds checking initially. Takes input as a list of 5-tuples representing the windows. ### How does it work? We pair all windows with each other and then look at all pairs `(a, b)` with `a /= b`. Since the relation is symmetric, we only have to check whether the right end of the first and left end of the second window overlap. If they do, then for them to overlap one's lower has to be higher than the other one's top or vice versa. Lastly, we do bounds checking. If any of the conditions are true, the list will contain more than one element, so all there is left to do is to check whether the list is empty. [Answer] ## JavaScript (ES6), 100 bytes ``` a=>!a.some(([m,l,b,r,t],i)=>l<0|b<0|r>1024|t>768|a.some(([n,k,c,s,u],j)=>i!=j&m==n&l<s&b<u&r>k&t>c)) ``` Takes input as an array of arrays. Assumes window coordinates are monitor-relative. I could save 8 bytes by assuming windows never overlap to the left of the monitor but 100 is a nice round number ;-) ]
[Question] [ Given a string or list, calculate the effects of gravity on that string/list. The string will be made of 5 characters: * `N` has a weight of 2 * `L` has a weight of 1 * `S` has a weight of -2 * `D` has a weight of -1 (the 5th character is whatever you want, it means empty space. I use (space) in my examples) Items with negative weight fall upwards (towards the top of the string), and items with positive weight fall downwards (towards the bottom of the string). When an object collides with something, one of three things happens: * If the object collides with the top or bottom "walls" of the input, then it just stops. * If the object collides with another object, their weight/velocity is summed (i.e. `N` and `D` would give `1`). If the result is positive, both objects fall downwards. If it's negative, they fall upwards. * If an object (let's call it `A`) collides with an object `B`, and `B` is already pinned against the ceiling/floor, `A` will just come to rest against `B`. All non-occupied spaces of the string/list should be filled with the empty character. If it wasn't clear already: each character in the string/line is on top of the next one. i.e. `NL` is the same as: ``` N L ``` And `SD` is: ``` (blank) S D ``` **Test cases:** (uses (the space character) to show empty space) ``` " L D " -> " LD " or " LD " " SDLN " -> "SD LN" " NLLSSD " -> "NLLSSD " ``` [Answer] # [Haskell](https://www.haskell.org/), ~~169~~ 180 bytes ``` g s=sum[n|c<-s,(d,n)<-zip"SD LN"[-2..],c==d] w=elem ' ' h(x:y:r)|(w x&&g y<0)||(w y&&g x>0)=y:h(x:r)|w(x++y)||g x<0=x:h(y:r)|t<-x++y=h$t:r h r=r concat.until((==)=<<h)h.map(:[]) ``` [Try it online!](https://tio.run/nexus/haskell#JYu9joMwEAZ7nmJlnRJbAQtdibxXUfrcUCIKRH6MFHzIOMKOeHdiH93ON7P7AxZcXlNrYBtEseT0mhsmivc4k6YGqUhbfHPe5QPitctWvD1vE5zhnGnqq1BZttEV/On0gCBKtiUKifxPyTBUqYrNSv3lEqKOQpTo4/7/60SRBOovV9lMg0Wb3XH4M0Pv@Mu48UkpIkMhNNN86mdatR3bp340gBD5F@hsR@OAw51BS0BCDSQHAk0t1XEpKZvmWFX0MTh2ULGRibr9Aw "Haskell – TIO Nexus") Example usage: `concat.until((==)=<<h)h.map(:[]) $ " SDLN "`. *Edit:* +11 bytes, now also works for the `" NSDLLD "` test case proposed by [@zgrep](https://codegolf.stackexchange.com/users/42775/zgrep). (short) **Explanation:** `h` works on a list of tokens where initially each char of the input string is token. Until the token list no longer changes, `h` bubbles through the list comparing two tokens `x` and `y` at a time. Depending on the tokens their order is kept (`x:h(y:r)`), they are swapped (`y:h(x:r)`) or combined to a single token (`t<-x++y=h$t:r`). `g` computes the weight of a token and `w` checks whether a token contains a space. [Answer] # OCaml, 379 bytes ``` let rec n f a i=try n f(f a i)(i+1)with _->a let r s=String.(concat""(let rec w s=if ' '=s.[0]then`E else(function 0->`F|w when w<0->`L|_->`H)(n(fun a i->index"SD LN"s.[i]-2+a)0 0)and l=function a::b::t->(function`E,`L|`H,`E->l(b::a::t)|_,`L|`H,_|`F,`F|`E,`E->l((a^b)::t)|_->let c=a::l(b::t)in if b=List.nth c 1 then c else l c)(w a,w b)|x->x in l(n(fun a i->a@[sub s i 1])[]0))) ``` To test: ``` let () = List.iter (fun s -> Printf.printf "`%s`\n" (r s)) [ " S S S S "; " D D D D "; " "; " L L L L "; " N N N N "; "NL"; " SD"; " L D "; " SDLN "; " NLLSSD "; ] ``` [Answer] ## Python 2, 322 bytes [Try it online](https://tio.run/nexus/python2#ZY3BboMwEETP8VdspUprg4MgR1P3Eo4RFx9dVyqU0K1Sg4xRPj@FpGkPHVmr8ezqzYW@xiFECB0zmvw4Ry7YXk8xZO0w@8gqjcjOH3TqwDzoSjGotGFwHAIQkLecsj4M88iFpGwa3zwX4r5cqNmR/DvFLnB8OacojXCKbSZNNndlr/d8klijSHbp1R5QbK/GrNnNVijKk@6f8rLR/XNetpoXclsI2zi2oSP0ymhjFdnCLdBt4ZJTuhRPc8PxFXD5rWUpwiMmjUTMPgfy3K6hREBnlWqdkNbYX4Ry8k4sXFo4t3SJ9OdgTZRLGjYG8hHM5YKwysBNB/iv6m/W9foA8Bs) ``` import re S=input() C=str.count D='' while S!=D: D=S for i in[(i.group(),i.span())for i in re.finditer('\w+',S)]: s=i[0];g=C(s,'N')*2+C(s,'L')-C(s,'S')*2-C(s,'D');l=g<0;b=g>0;c=(1,-1)[b] if g:S=S[:i[1][0]-1]*l+re.sub('^ '*l+i[0]+' $'*b,''.join([i[0],' '][::c]),[S[i[1][0]-1:],S[:i[1][1]+1]][b])+S[i[1][1]+1:]*b print S ``` ]
[Question] [ We shall soon have a new logo & site design, let us use this last breath of the simple times and golf this ASCII version of the speech bubble beta logo: ``` +-------------------------------------------+ | .---------------------------------. | | .EPEpEpBPEpEGCXCgCgCGJgCgP&PWP&P&P&Y` | | .RSRsRWRSRsRsHoNoNONxNONONuJuSUSUSVSUS` | | :o@OTO@O@O@W@IDiDIWiDIDIDWZEZeZEWEZeZE- | | :GWGFGfGFKFGFMEMwMEMEMeXEMZLZLWLZLzLZH- | | :rLRLRLXLRLrLMBMGMGmGXGMGMLzTZLZLZLYLZ- | | :AOAoBOAOAOAYAOAoAoBOAOAoAWZEZEZEVEZEZ- | | :MGVGm!'""'!GRLr!'""'!LRKRS!'""'!uSuSU- | | :XEME' .''% !Gf' .;G% 'GFG' .;P% '&PVP- | | :IDID !DI! !V! .OPoYOPOP! -gCGCGHGCG- | | :NONw ``` .OR! .RWRRRRRR! !ONo* 'ONON- | | :GBGC !CXCGCP! !POP; !xOP `IJ; `!IDW- | | :P&P&._!&P&P&F~.____.;GFGF~.____.;eJEM- | | :USUSVSUSuSuTLRlRLRWRLRlRLWMGMGmGwGmGM- | | :ZeWEZEZeZWZeOAOaKAOAOaOwOOAoAOXoAoAOA- | | :wLZLZLzHZLZLGMxMgMGMgBGMGLRLXLRLrLRTr- | | :LZLZLYLZLZLzBMEMEMEyEmEMEfBFGFGfGWGFG- | | :EZEVEZEZeZVZDIdIDYdIdIDIx@O@o@oKO@O@o- | | `SkSuSuSUXUSuONOVONOnONWNOSRSRWRSRSRS- | | `.&P&PVP&P&PCXcGCGCGVGcGCEPYPEpEPE?.- | | ```````````````````:STACKE-````` | | :XCHA-` | | :NG-` | | ?=W...HWYWVWB :E` | +-------------------------------------------+ ``` This is [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so it's straight forward, output all the text that appears in the above code-block in as few bytes of code as possible, without any funny-business. ### input None ### Output The ASCII content of the code-block above as a return value or printed to STDOUT or equivalent; carriage returns `(13)` and/or new lines `(10)` are acceptable; a trailing empty line is also allowed. ### Update The original aim of this challenge was to have a puzzle aspect. It seems this has not been noticed, so I have decided to make the puzzle portion *significantly* easier, but still present, by performing a couple of steps to get you going: 1. There is a use of the string `"STACKEXCHANGE"` in the very bottom portion of the speech-bubble. 2. If one reads the rows of text in the main-portion of the speech-bubble, one might notice an almost repetitive nature of pairs of letters, for example the fourth row reads `"GWGFGfGFKFGFMEMwMEMEMeXEMZLZLWLZLzLZH"` which is almost `"GFGFGFGFGFGFMEMEMEMEMEMEMZLZLZLZLZLZH"`, except some letters have been changed either to another letter (e.g. the second letter from `F` to `W`), to lower-case (e.g. the sixth letter from `F` to `f`), or both (e.g. the sixteenth letter from `E` to `w`). The rows seem to all conform to such a pattern with a 12-13-12 character split (ignoring the mess of the `PPG` logo's white space and border). 3. The process described in (2), once noticed, should be quite easy to undo for the unmasked rows of the speech-bubble (the top six and bottom seven), by first converting the whole text to upper-case and then replacing the odd-ones-out and results in: ``` +-------------------------------------------+ | .---------------------------------. | | .EPEPEPEPEPEGCGCGCGCGCGCGP&P&P&P&P&P` | | .RSRSRSRSRSRSNONONONONONONUSUSUSUSUSUS` | | :O@OTO@O@O@O@IDIDIWIDIDIDIZEZEZEZEZEZE- | | :GFGFGFGFGFGFMEMEMEMEMEMEMZLZLZLZLZLZL- | | :RLRLRLRLRLRLMGMGMGMGMGMGMLZLZLZLZLZLZ- | | :AOAOAOAOAOAOAOAOAOBOAOAOAEZEZEZEZEZEZ- | | :MGVGm!'""'!GRLr!'""'!LRKRS!'""'!uSuSU- | | :XEME' .''% !Gf' .;G% 'GFG' .;P% '&PVP- | | :IDID !DI! !V! .OPoYOPOP! -gCGCGHGCG- | | :NONw ``` .OR! .RWRRRRRR! !ONo* 'ONON- | | :GBGC !CXCGCP! !POP; !xOP `IJ; `!IDW- | | :P&P&._!&P&P&F~.____.;GFGF~.____.;eJEM- | | :USUSUSUSUSURLRLRLRLRLRLRLGMGMGMGMGMGM- | | :ZEZEZEZEZEZEOAOAOAOAOAOAOOAOAOAOAOAOA- | | :ZLZLZLZLZLZLGMGMGMGMGMGMGLRLRLRLRLRLR- | | :LZLZLZLZLZLZEMEMEMEMEMEMEFGFGFGFGFGFG- | | :EZEZEZEZEZEZDIDIDIDIDIDID@O@O@O@O@O@O- | | `SUSUSUSUSUSUONONONONONONOSRSRSRSRSRS- | | `.&P&P&P&P&PCGCGCGCGCGCGCEPEPEPEPEP.- | | ```````````````````:STACKE-````` | | :XCHA-` | | :NG-` | | ?=W...HWYWVWB :E` | +-------------------------------------------+ ``` 4. While carrying out (3) one may notice a couple of things. First the least obvious: that the only `?`, in the very bottom-right became a `P`, whereas the extra text at the bottom says `?=W...`, and that a large proportion of replaced characters were also `W`. Second that the odd-ones out in upper-case were `B,H,J,K,T,V,W,X,Y`. Third that the odd-ones out occurred every seven letters. The second and third observation helps to fill in the middle rows - which, if we remove the `PCG` mask of spaces and non-letters, non `&` (used in the top and bottom row) and replace it with the letters yields: ``` +-------------------------------------------+ | .---------------------------------. | | .EPEPEPEPEPEGCGCGCGCGCGCGP&P&P&P&P&P` | | .RSRSRSRSRSRSNONONONONONONUSUSUSUSUSUS` | | :O@O@O@O@O@O@IDIDIWIDIDIDIZEZEZEZEZEZE- | | :GFGFGFGFGFGFMEMEMEMEMEMEMZLZLZLZLZLZL- | | :RLRLRLRLRLRLMGMGMGMGMGMGMLZLZLZLZLZLZ- | | :AOAOAOAOAOAOAOAOAOBOAOAOAEZEZEZEZEZEZ- | | :MGMGMGMGMGMGRLRLRLRLRLRLRSUSUSUSUSUSU- | | :MEMEMEMEMEMEGFGFGFGFGFGFG&P&P&P&P&P&P- | | :IDIDIDIDIDIDOPOPOPOPOPOPOCGCGCGCGCGCG- | | :NONONONONONORRRRRRRRRRRRRONONONONONON- | | :GCGCGCGCGCGCPOPOPOPOPOPOPDIDIDIDIDIDI- | | :P&P&P&P&P&P&FGFGFGFGFGFGFEMEMEMEMEMEM- | | :USUSUSUSUSURLRLRLRLRLRLRLGMGMGMGMGMGM- | | :ZEZEZEZEZEZEOAOAOAOAOAOAOOAOAOAOAOAOA- | | :ZLZLZLZLZLZLGMGMGMGMGMGMGLRLRLRLRLRLR- | | :LZLZLZLZLZLZEMEMEMEMEMEMEFGFGFGFGFGFG- | | :EZEZEZEZEZEZDIDIDIDIDIDID@O@O@O@O@O@O- | | `SUSUSUSUSUSUONONONONONONOSRSRSRSRSRS- | | `.&P&P&P&P&PCGCGCGCGCGCGCEPEPEPEPEP.- | | ```````````````````:STACKE-````` | | :XCHA-` | | :NG-` | | ?=W...HWYWVWB :E` | +-------------------------------------------+ ``` 1. Now reading the columns one can see that the "input" text to make this base grid was `PROGRAMMINGPUZZLES&CODEGOLFPROGRAMMINGPUZZLES&CODEGOLF@SE`. The lower-casing and replacement characters are to be determined by you, but also note that the ten remaining letters in the alphabet after removing those present in that string are `B,H,J,K,Q,T,V,W,X,Y` - the replacements plus `Q`. [Answer] # [Bubblegum](http://esolangs.org/wiki/Bubblegum), ~~542~~ 541 bytes Reversible hexdump: ``` 00000000: d2d6 251e 68f3 72d5 002a 2903 1637 6138 ..%.h.r..*)..7a8 00000010: 8a7f 9578 7027 0c9a 0fd0 32ae 6a63 b435 ...xp'....2.jc.5 00000020: 2668 6734 00e7 d8d9 32b6 cea3 4769 57c6 &hg4....2...GiW. 00000030: 3efb 5e94 1a60 07c7 e5f1 7f89 f033 35ff >.^..`.......35. 00000040: a725 18f4 5d92 5aec cf88 53a6 d80b 7b09 .%..].Z...S...{. 00000050: adf3 a88e f610 5fc3 d583 d228 a869 279c ......_....(.i'. 00000060: 1665 f15a e8c1 5f93 3eef 7399 5f72 099d .e.Z.._.>.s._r.. 00000070: d6a7 f20b 54a1 da1b 3eef 9772 2b97 567a ....T...>..r+.Vz 00000080: 99ae beaf 528d 82b4 61a6 334c 0f3e 9b70 ....R...a.3L.>.p 00000090: ae79 cc77 3cde c43c 164c 9c05 83ba 9a09 .y.w<..<.L...... 000000a0: 9399 4ca3 ae99 491c 7ecc 0aa8 461d 3311 ..L...I.~...F.3. 000000b0: 0a2e f881 d770 915d b7b8 036a 32e3 f040 .....p.]...j2..@ 000000c0: 067d 2803 ab06 d58f 5798 b561 5695 7587 .}(.....W..aV.u. 000000d0: 0b5e f183 e7df ddf9 1ec7 2f8c abac d814 .^......../..... 000000e0: e5b8 3c95 38b1 c3f1 94cc 27d4 f7ef 89c7 ..<.8.....'..... 000000f0: 7758 2df8 3df1 711e bb54 583e a84a 39dc wX-.=.q..TX>.J9. 00000100: 7681 106f 957a c4ab 3c42 a5ea 1ba9 a4f2 v..o.z..<B...... 00000110: 0899 2181 8827 2887 a3c3 6742 dab6 0559 ..!..'(...gB...Y 00000120: 0047 06c3 c0dd 32ef 3f11 5f82 7038 0f79 .G....2.?._.p8.y 00000130: 84dd a31a 3b29 30d8 7841 bc8b 54d8 235d ....;)0.xA..T.#] 00000140: 2f48 eb21 0387 db94 e993 37a4 1dff a54f /H.!......7....O 00000150: 1878 fc98 4feb 6ecd 84c3 6f39 a303 dbac .x..O.n...o9.... 00000160: f889 1034 0ab3 1e33 38a3 84c3 4da7 d990 ...4...38...M... 00000170: b736 1d1a fe75 1358 9767 697b 2feb de7a .6...u.X.gi{/..z 00000180: e0f0 f390 dc35 b1ce c545 ecb1 e93e c4c6 .....5...E...>.. 00000190: 53d6 c5f6 e8f0 5bce d035 14cc ea37 3bc0 S.....[..5...7;. 000001a0: 7761 3cbc 4d1a eef0 5bce 9da9 cc2a 7d4e wa<.M...[....*}N 000001b0: 57cd b3f5 f482 77b4 5ff6 1b69 e709 6fcb W.....w._..i..o. 000001c0: 1fe5 9073 8dd3 a2c5 15ea 97cc 752e 4b7c ...s........u.K| 000001d0: 031a 0581 1e71 f014 1d44 ced6 a3fa 1b8f .....q...D...... 000001e0: a08a 6366 aab1 5f98 628f d4e1 76b4 ff8f ..cf.._.b...v... 000001f0: 79b9 0da2 0d9b 0d17 401c fee6 98d7 5112 [[email protected]](/cdn-cgi/l/email-protection). 00000200: ccda e9fa 3d3c e70e 7e0b 7ffc ac29 a589 ....=<..~....).. 00000210: 6e74 a543 34cc c113 fea1 bfa5 7f nt.C4........ ``` [Try it online!](http://bubblegum.tryitonline.net#code=MDAwMDAwMDA6IGQyZDYgMjUxZSA2OGYzIDcyZDUgMDAyYSAyOTAzIDE2MzcgNjEzOCAgLi4lLmguci4uKikuLjdhOAowMDAwMDAxMDogOGE3ZiA5NTc4IDcwMjcgMGM5YSAwZmQwIDMyYWUgNmE2MyBiNDM1ICAuLi54cCcuLi4uMi5qYy41CjAwMDAwMDIwOiAyNjY4IDY3MzQgMDBlNyBkOGQ5IDMyYjYgY2VhMyA0NzY5IDU3YzYgICZoZzQuLi4uMi4uLkdpVy4KMDAwMDAwMzA6IDNlZmIgNWU5NCAxYTYwIDA3YzcgZTVmMSA3Zjg5IGYwMzMgMzVmZiAgPi5eLi5gLi4uLi4uLjM1LgowMDAwMDA0MDogYTcyNSAxOGY0IDVkOTIgNWFlYyBjZjg4IDUzYTYgZDgwYiA3YjA5ICAuJS4uXS5aLi4uUy4uLnsuCjAwMDAwMDUwOiBhZGYzIGE4OGUgZjYxMCA1ZmMzIGQ1ODMgZDIyOCBhODY5IDI3OWMgIC4uLi4uLl8uLi4uKC5pJy4KMDAwMDAwNjA6IDE2NjUgZjE1YSBlOGMxIDVmOTMgM2VlZiA3Mzk5IDVmNzIgMDk5ZCAgLmUuWi4uXy4-LnMuX3IuLgowMDAwMDA3MDogZDZhNyBmMjBiIDU0YTEgZGExYiAzZWVmIDk3NzIgMmI5NyA1NjdhICAuLi4uVC4uLj4uLnIrLlZ6CjAwMDAwMDgwOiA5OWFlIGJlYWYgNTI4ZCA4MmI0IDYxYTYgMzM0YyAwZjNlIDliNzAgIC4uLi5SLi4uYS4zTC4-LnAKMDAwMDAwOTA6IGFlNzkgY2M3NyAzY2RlIGM0M2MgMTY0YyA5YzA1IDgzYmEgOWEwOSAgLnkudzwuLjwuTC4uLi4uLgowMDAwMDBhMDogOTM5OSA0Y2EzIGFlOTkgNDkxYyA3ZWNjIDBhYTggNDYxZCAzMzExICAuLkwuLi5JLn4uLi5GLjMuCjAwMDAwMGIwOiAwYTJlIGY4ODEgZDc3MCA5MTVkIGI3YjggMDM2YSAzMmUzIGYwNDAgIC4uLi4ucC5dLi4uajIuLkAKMDAwMDAwYzA6IDA2N2QgMjgwMyBhYjA2IGQ1OGYgNTc5OCBiNTYxIDU2OTUgNzU4NyAgLn0oLi4uLi5XLi5hVi51LgowMDAwMDBkMDogMGI1ZSBmMTgzIGU3ZGYgZGRmOSAxZWM3IDJmOGMgYWJhYyBkODE0ICAuXi4uLi4uLi4uLy4uLi4uCjAwMDAwMGUwOiBlNWI4IDNjOTUgMzhiMSBjM2YxIDk0Y2MgMjdkNCBmN2VmIDg5YzcgIC4uPC44Li4uLi4nLi4uLi4KMDAwMDAwZjA6IDc3NTggMmRmOCAzZGYxIDcxMWUgYmI1NCA1ODNlIGE4NGEgMzlkYyAgd1gtLj0ucS4uVFg-Lko5LgowMDAwMDEwMDogNzY4MSAxMDZmIDk1N2EgYzRhYiAzYzQyIGE1ZWEgMWJhOSBhNGYyICB2Li5vLnouLjxCLi4uLi4uCjAwMDAwMTEwOiAwODk5IDIxODEgODgyNyAyODg3IGEzYzMgNjc0MiBkYWI2IDA1NTkgIC4uIS4uJyguLi5nQi4uLlkKMDAwMDAxMjA6IDAwNDcgMDZjMyBjMGRkIDMyZWYgM2YxMSA1ZjgyIDcwMzggMGY3OSAgLkcuLi4uMi4_Ll8ucDgueQowMDAwMDEzMDogODRkZCBhMzFhIDNiMjkgMzBkOCA3ODQxIGJjOGIgNTRkOCAyMzVkICAuLi4uOykwLnhBLi5ULiNdCjAwMDAwMTQwOiAyZjQ4IGViMjEgMDM4NyBkYjk0IGU5OTMgMzdhNCAxZGZmIGE1NGYgIC9ILiEuLi4uLi43Li4uLk8KMDAwMDAxNTA6IDE4NzggZmM5OCA0ZmViIDZlY2QgODRjMyA2ZjM5IGEzMDMgZGJhYyAgLnguLk8ubi4uLm85Li4uLgowMDAwMDE2MDogZjg4OSAxMDM0IDBhYjMgMWUzMyAzOGEzIDg0YzMgNGRhNyBkOTkwICAuLi40Li4uMzguLi5NLi4uCjAwMDAwMTcwOiBiNzM2IDFkMWEgZmU3NSAxMzU4IDk3NjcgNjk3YiAyZmViIGRlN2EgIC42Li4udS5YLmdpey8uLnoKMDAwMDAxODA6IGUwZjAgZjM5MCBkYzM1IGIxY2UgYzU0NSBlY2IxIGU5M2UgYzRjNiAgLi4uLi41Li4uRS4uLj4uLgowMDAwMDE5MDogNTNkNiBjNWY2IGU4ZjAgNWJjZSBkMDM1IDE0Y2MgZWEzNyAzYmMwICBTLi4uLi5bLi41Li4uNzsuCjAwMDAwMWEwOiA3NzYxIDNjYmMgNGQxYSBlZWYwIDViY2UgOWRhOSBjYzJhIDdkNGUgIHdhPC5NLi4uWy4uLi4qfU4KMDAwMDAxYjA6IDU3Y2QgYjNmNSBmNDgyIDc3YjQgNWZmNiAxYjY5IGU3MDkgNmZjYiAgVy4uLi4udy5fLi5pLi5vLgowMDAwMDFjMDogMWZlNSA5MDczIDhkZDMgYTJjNSAxNWVhIDk3Y2MgNzUyZSA0YjdjICAuLi5zLi4uLi4uLi51Lkt8CjAwMDAwMWQwOiAwMzFhIDA1ODEgMWU3MSBmMDE0IDFkNDQgY2VkNiBhM2ZhIDFiOGYgIC4uLi4ucS4uLkQuLi4uLi4KMDAwMDAxZTA6IGEwOGEgNjM2NiBhYWIxIDVmOTggNjI4ZiBkNGUxIDc2YjQgZmY4ZiAgLi5jZi4uXy5iLi4udi4uLgowMDAwMDFmMDogNzliOSAwZGEyIDBkOWIgMGQxNyA0MDFjIGZlZTYgOThkNyA1MTEyICB5Li4uLi4uLkAuLi4uLlEuCjAwMDAwMjAwOiBjY2RhIGU5ZmEgM2QzYyBlNzBlIDdlMGIgN2ZmYyBhYzI5IGE1ODkgIC4uLi49PC4ufi4uLi4pLi4KMDAwMDAyMTA6IDZlNzQgYTU0MyAzNGNjIGMxMTMgZmVhMSBiZmE1IDdmICAgICAgICAgbnQuQzQuLi4uLi4uLg) Just Zopfli'd the string for 1 million iterations. Running for 100 million iterations does not yield a shorter solution. [Answer] # PHP, 780 Bytes ``` <?=gzinflate(base64_decode("lZRvb9owEMbfT9p3cCq1kYbiDwCaShIcE0hiK2FxkjdNtQY0bSwVVQVDVT/7HpuBYZv2x6e7XKKfD/sem4H372Pw9s0LwaB/JanGXg44ZZI9ssdARx5W4QrGZ4jyRio4rG5POM2L/ClXJj5N+6zPRLaDi+x59lx8gJXw9ogP+7FYiLE2NY4nnyaxgsNUw5quYcpE74RzxSO+5NE84lHK0i2cpV3F0iZpEgXfJ83U4pskh1XwTZIGKU/5mleIabJf6BlNUieNxX3h94HwtdU6//HW+3o1sFJHi6e85GvHvbpyHY5fOGRJPs+LQ/pcYMcWxyqZS6jrXhOHL5GN+DVxsR+dSqQ3spQW110gxJnEDnFKh1Ah+1pIIR1CPCgQ8inc4ujwlpC2bUHmwKGBGZgtsv4dcbUGZ40MeIjq0JOHKOmg8Ig4OyFRI56NSOtAA4trlemdY9SOXukdBpYPEY55N2OpxY86owOLJP8CEVRunuqgwRZ+hjedYkZv1XRo+P1cS3AvtkL3XlS9jr7Ft0a5/VRHnu7SFYquAhQ+aZ0vNhY/6qznBObAsG9sjbgMInOa9Jmy+FHnrimbSfwQT+oHHeMdzmg/7uf6rPYnvC0+F0bnCrtFi0v4V5GpTBS4A/oewDx7m1qqe1iaexNWH7kWsuR4MlnrGybZLT3DiZH05zEsFn44Z555IeQC/80YVuHU99qzL3/GM34B/4LfvleU0qmqVakCNOwSNvjgf/6WvgM=")); ``` Maybe helpful maybe not I do not know I give up to find an other way. beginning the first line at 1 you could concat lines they have the sum 24 with one letter starts with the W in the middle go up go left and go reverse the 2 line down then concat the first letter of line 13 with the end of line 11 and go to the middle now I assume that you must go down to line 14 It seems for me that "?=W...HWYWVWB" is a hint to solve this [Answer] ## Ruby, 788 bytes Basically the same method as the PHP solution. ``` puts Zlib.inflate Base64.decode64 "eJyVlG9vmzAQxt/vU5hKLdIi/AESTQ0QxyEBjCDDwJtSrUk0bRlVqihZVfWz7zmnOG017Y9PdxzRzyf83DkD79/X4MMTw+J/BTlhT4bmIhP34j6gKMMq3MDkHDG7yjQcVrc9zfMif8i1iQ+zLu1SlR7hKt3P98VnWAlvX+hhN1ZLNSbT42jydRJpOEw3olk1Qpvo9bTUcirXcrqYymkikgNcJKtKJE3cxBr+GDczS+/iHFbBd3ESJDKRW1khJvHjkjY0cR03lvaV3wXKJ6spf3nrfPoUWEnR0oks5dZxLy5cR6L+KYvzRV6c0n2Bw1oaXyhcxl33kjlyjWwkL5mLs1CaIb3KyszSdH7GnEnkMKd0GFdZV6tMZQ5jHpQP5QxuaSh7YKxtW4A5aGhvFjartPvIXNL+rGAgQ9RGF2WIgg7KjphzVBlKRPMRax1ob2lqLb9xTIunz/wGC58O8ft8NReJpfvm4uzLOP8O8XVunvqk/QF+ppuVFqbJullB6NsFSX+rDoo0V1VH0bf0wfTrcUZRJsdkg5KbAGVth/PlztJ9c2lLYIZE/BRbxHUwNRNEc2Tpvrmrpmwm0V00qe8oRkdMZTfuFjSdXU+3xbfCNLfCQSFtCf+hUp2qAjNPcw/z7N1pOYlXmlsSVl8kta+UeIqspvuUiWt+pplp5Ps1LJZ+uBCeeWHsNf2bNazCme+1r375I53KN+x7+vqT5pzPdK1LHUCqtyzRg//69/kFnIsxTA==" ``` ]
[Question] [ **See Also: [Recognition](https://codegolf.stackexchange.com/questions/90123/number-plate-golf-recognition)** ## Introduction You've now been taken off the speed camera development team (let's face it, your code is nowhere near production code standards) and are now working on a program to extract information about the car from the number plates. Of course, you've caught the code golf bug and want to write the program in as few bytes as possible. ## Challenge Given a valid, British number plate, display information about the car's registration. You only have to support number plates registered between 2001 and 2051 (inclusive). Internet access is disallowed. *The input will be given as a string.* ## Number Plates British number plates are ordered like so: ![](https://upload.wikimedia.org/wikipedia/commons/thumb/6/6c/British_car_registration_plate_labels.svg/1280px-British_car_registration_plate_labels.svg.png) ### Area code A table with all of the area code mnemonics which you need to support can be found [here](https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_the_United_Kingdom#Local_memory_tags). For the letter X, you only need to output *Personal Export* due to multiple areas being covered by the same mnemonic. You must output the DVLA office name. ### Age Identifier Similarly, a table with all of the age identifiers which you need to support can be found [here](https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_the_United_Kingdom#Age_identifiers). If the identifier is in the range `Y to 50` inclusive, you must output: ``` 1/3/[Year] to 31/8/[Year] ``` Likewise, if the identifier is in the range `51 to 00` inclusive, you must output: ``` 1/9/[Year] to [28/29]/2/[Year + 1] ``` You should support leap years. ## Examples ### WK94 FRS ``` Truro, 1/9/2044 to 28/2/2045 ``` ### CB16 BTD ``` Bangor, 1/3/2016 to 31/8/2016 ``` ### BD51 SMR ``` Birmingham, 1/9/2011 to 29/2/2012 ``` ### XAY EEA ``` Personal Export, 1/3/2001 to 31/8/2001 ``` ## Scoring The shortest code in bytes wins [Answer] # Ruby, 629 bytes ``` s=gets p=c=0 'PETeRborOuGh NORWich IPSwicH BIRMiNGHam CARdiff SWANsea BAngOr CHEsTer SHREWsbURY CHELmSFOrd NOTTInGHAm LInCOlN MAIDStone BRIgHtON BOURNEMoUth PORTSMoUth ISLE OF WIGHt PORtSmOUtH BOREHAMwoOD NORTHAmPton WIMBLeDoN BOREHAMwOoD SIdcup MANChESTer NEWCAstle STOcKtON oXFOrd PReStON CArlISlE ReADIng GLAsGoW EDINBUrGh DUNdEe ABERDEen INvErNEsS WORcESTer EXeTeR TRUro BRiStoL PERSONAL eXPOrt LeEds SHEFFiElD BEVERLEY'.split($/).map{|w|c<s[0,2].to_i(35)&&p=w;d=0;w.bytes{|b|d+=d+b/95};c+=d} y=(?1+s[2,9]).to_i-1 puts p.capitalize+", 1/%d/20%02d to %d/%d/20%02d"%[z=3+y%100/50*6,1+y%=50,z<4?31:y%4==2?29:28,(z+5)%12,1+y+z/9] ``` The first two letters are interpreted as a base 35 number and then looked up to find the correct town. The quantity of addresses assigned to each town is encoded (run-length encoding) in the captialization of each town in binary, where uppercase=0 and lowercase=1. In order to handle the Y age indicator for the first half of 2001, a 1 is prepended to the age. Thus `1` `Y` is interpreted by `.to_i` as 1, and `1` `02` is interpreted as 102. 1 is subtracted (to handle the wraparound for 2050) and taken modulo 100 to decide which half of the year we are in. It is then taken modulo 50 (and the 1 added on again) to find the year. [Answer] # PHP, ~~1044~~ ~~800~~ 757 bytes The script is added to a [PHAR (PHP archive)](http://php.net/phar) and compressed with gzip to shrink it from 1044 to 800 bytes. Further optimization took the original code down to 994 bytes, which then as a Phar is 757 bytes. Takes the license plate string as the first argument like `php u.phar BD51 SMR` (actually the latter part is read as "second argument", but useless garbage anyway for this challenge). [Download the uklic.phar file for this answer](http://mehr.it/golf/uklic.phar) This is the script before compression: ``` <?$o=[X=>'Personal export',B=>Birmingham,E=>Chelmsford,M=>Manchester,O=>Oxford,R=>Reading,V=>Worcester,A=>['A-N'=>Peterborough,'O-U'=>Norwich,'V-Y'=>Ipswich],C=>['A-O'=>Cardiff,'P-V'=>Swansea,WXY=>Bangor],D=>['A-K'=>Chester,'L-Y'=>Shrewsbury],F=>['A-P'=>Nottingham,'R-Y'=>Lincoln],G=>['A-O'=>Maidstone,'P-Y'=>Brighton],H=>['A-J'=>Bournemouth,'K-Y'=>Portsmouth,W=>'Isle of Wight'],K=>['A-L'=>Borehamwood,'M-Y'=>Northampton],L=>['A-J'=>Wimbledon,'K-T'=>Borehamwood,'U-Y'=>Sidcup],N=>['A-O'=>Newcastle,'P-Y'=>Stockton],P=>['A-T'=>Preston,'U-Y'=>Carlisle],S=>['A-J'=>Glasgow,'K-O'=>Edinburgh,'P-T'=>Dundee,UVW=>Aberdeen,XY=>Inverness],W=>['A-J'=>Exeter,KL=>Truro,'M-Y'=>Bristol],Y=>['A-K'=>Leeds,'L-U'=>Sheffield,'V-Y'=>Beverley]];$p=$argv[1];$a=$o[$p{0}];$z=$a;if(count($a)>1){foreach($a as$r=>$d){if(preg_match("/[$r]/",$p{1})){$z=$d;}}}$n=$p{2}.$p{3};$y=$n+($n==Y);if($y==0)$y=50;$h=$y&&$n<51;$y%=50;$x=$y+1;printf('%s, 1/%s/20%02d to %s/20%02d',$z,$h?3:9,$y,$h?'31/8':28+!($x%4).'/2',$h?$y:$x); ``` The DVLA Office lookup is a simple map with a string if the first character of the license plate is enough to identify the office and an array if we need the second character. The character range is then matched with a simple regexp. The code for the date range is quite easy except for the two edge cases "Y" and "00"~~, which can't be calculated~~. Y is cast to integer and added a 1, in case the input is an integer. That's how we get 2001 for Y. 00 is accounted for by modulo arithmetic. This is the slightly better readable version: ``` <? $o = [ X => 'Personal export', B => Birmingham, E => Chelmsford, M => Manchester, O => Oxford, R => Reading, V => Worcester, A => ['A-N' => Peterborough, 'O-U' => Norwich, 'V-Y' => Ipswich], C => ['A-O' => Cardiff, 'P-V' => Swansea, WXY => Bangor], D => ['A-K' => Chester, 'L-Y' => Shrewsbury], F => ['A-P' => Nottingham, 'R-Y' => Lincoln], G => ['A-O' => Maidstone, 'P-Y' => Brighton], H => ['A-J' => Bournemouth, 'K-Y' => Portsmouth, W => 'Isle of Wight'], K => ['A-L' => Borehamwood, 'M-Y' => Northampton], L => ['A-J' => Wimbledon, 'K-T' => Borehamwood, 'U-Y' => Sidcup], N => ['A-O' => Newcastle, 'P-Y' => Stockton], P => ['A-T' => Preston, 'U-Y' => Carlisle], S => ['A-J' => Glasgow, 'K-O' => Edinburgh, 'P-T' => Dundee, UVW => Aberdeen, XY => Inverness], W => ['A-J' => Exeter, 'KL' => Truro, 'M-Y' => Bristol], Y => ['A-K' => Leeds, 'L-U' => Sheffield, 'V-Y' => Beverley] ]; $p=$argv[1]; $a=$o[$p{0}]; $z=$a; if (count($a)-1) { foreach($a as $r => $d) { if (preg_match('/['.$r.']/', $p{1})) {$z=$d; } } } $n=$p{2}.$p{3}; $y=$n+($n==Y); if ($y==0) { $y=50; } $h=$y&&$n<51; $y%=50; $x=$y+1; printf('%s, 1/%s/20%02d to %s/20%02d',$z,$h?3:9,$y,$h?'31/8':28+!($x%4).'/2',$h?$y:$x); ``` Updates: 1. Seriously trimmed down the date calculation section and made use of printf, replaced `is_array($a)` with `count($a)>1 2. Optimized the Phar bootstrapping ]
[Question] [ # Introduction [BitShift](https://esolangs.org/wiki/BitShift) is an esolang, created by me, to output strings. Sounds boring, is boring. However, the only instructions available to BitShift are `0` and `1`. Therefore it can be challenging to golf in it. To make matters even more interesting, the language only supports 4 bitshifting instructions, a clear, a print and an input instruction. # How it works BitShift is written by alternating `0` and `1` characters. Once the interpreter finds 2 of the same characters in a row, it will perform an instruction based on the amount of non-alternating characters preceding it. `010010110001010` will perform the operations `3 4 2 1 5` `010 0101 10 0 01010` here, the non-alternating characters are seperated by a spacebar for readability. The interpreter can be found [here](https://dl.dropboxusercontent.com/u/10914578/Bitshift.html) # Operations All operations are performed on one single value. BitShift does not know of a stack. BitShift programs initially start with a value of 0. This value can range from 0-255 and overflows at -1 and 256 ``` 1 Shift the value 1 bit to the left (0000 0001 > 0000 0010) 2 Shift the value 1 bit to the right (0000 0010 > 0000 0001) 3 XOR the value with 1 (0000 0000 > 0000 0001) 4 XOR the value with 128 (0000 0000 > 1000 0000) 5 Set the value to 0 6 Convert the value to a character and print it 7 Read a character from user input and set the value to it ``` # Challenge Your task is to create a program which can convert an input string to the shortest possible BitShift program which will output that string when run. # Rules * You are not allowed to use the `7` operation * Your program takes only one input argument, which is the string to convert * Your program will output the translated BitShift program to STDOUT * You can use any kind of built-in function in your preffered language * You can use any kind of language, as long as it's created before this date # Scoring This is a [metagolf](/questions/tagged/metagolf "show questions tagged 'metagolf'"). The person who can create the shortest BitShift program will win this challenge. In case of a tie, the lowest byte count will win. The input string ([ISO 8859-1](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)) you should base your answer on is: `This is a string, meant to test the effectiveness of your program. Here are some special characters to make matters interesting: Æ Ø ß. How meta! :D` The special characters used are `&#198; &#216; &#223;` Please post the output of your program in your answer, so that it can be tested for validation. The following is an example solution. Obviously, this is a terrible solution. # Javascript, 594 bytes, 4275 characters ``` var flag = true; var input = prompt(); var output = "" for (n in input) { var c = input.charCodeAt(n).toString(2); while (c.length < 8) { c = "0" + c; } for (var i = 0; i < 8; i++) { if (c[i] == "1") { output += flag ? "010" : "101"; } if (i < 7) output += flag ? "0" : "1"; } for (var z = 0; z < 6; z++) { output += flag ? "0" : "1"; flag = !flag; } flag = !flag; for (var z = 0; z < 5; z++) { output += flag ? "0": "1"; flag = !flag; } flag = !flag; } console.log(output); ``` [Answer] # Mathematica, 343 bytes, 2573 characters ``` B=BitXor;t[a_]:={Mod[2a,256],⌊a/2⌋,a~B~1,a~B~128,0};w[a_,b_]:=Position[t@a,b][[1,1]];f=FindShortestPath[Graph[0~Range~255,e=Join@@Table[a#&/@({}⋃t@a),{a,m=c=0,255}],EdgeWeight(w@@#&/@e)],All,All];o="";u[a_,b_]:=(Do[o=o<>ToString[m=1-m],{If[a==b,6,a~w~f[a,b][[2]]]}];m=1-m);While[c~u~y;c!=y,c=f[c,y][[2]]]~Do~{y,ToCharacterCode@i};o ``` This is my first code competition. This program should generate the shortest possible program for any string. It effectively calculates a lookup table given the current state of the accumulator and the goal byte to find the shortest sequence of the five operations to get from any one to another, carrying the accumulator over characters and taking advantage of the size difference between instructions. Uses Mathematica 8's `Graph` infrastructure for calculating shortest paths (alternatives being to roll one's own or just embed the `256 x 256` table of instructions). Ungolfed version (the first `i = "..."` line is also present, but not counted in the golfed version since it is the input): ``` i = "This is a string, meant to test the effectiveness of your program. Here are some special characters to make matters interesting: Æ Ø ß. How meta! :D"; B = BitXor; t[a_] := {Mod[2 a, 256], Quotient[a, 2], B[a, 1], B[a, 128], 0} w[a_, b_] := Position[t[a], b][[1, 1]] g = Graph[Range[0, 255], e = Join @@ Table[DirectedEdge[a, #] & /@ Union@t@a, {a, 0, 255}], EdgeWeight -> (w @@ # & /@ e)]; f = FindShortestPath[g, All, All]; c = m = 0; o = ""; u[a_, b_] := (Do[ o = o <> ToString[m = 1 - m], {If[a == b, 6, w[a, f[a, b][[2]]]]}]; m = 1 - m); Do[While[u[c, y]; c != y, c = f[c, y][[2]]], {y, ToCharacterCode[i]}]; o ``` Output: ``` 10111101111011110101000010110010101101101010000010110010110010010101101111110101001011001011001001010111110100110100110110101001000000101011101001101101010000000101011011101110111110111011010100110010000101011001101110111010100100001000001001010110011011101110101000010001000011011010100110100110010101111111001101010010001000010001000010010101101110111101101010011001000010010101100110010001000100010101110111101010000001101010010110010110010110010101100100010000110110101000000000110010101101001101001101001101010001000001011001001010110100110110101001100100001010111111001010110100110100110100110101000011010100100000101100100101011011111010100110100110100110110101001101110101001010110010001001010111011111101110110101000100001000010101111001001010110100110010001010111101111011010100010001000010110010101111011111001001010110100110110101001010110111111010100100010000100010001000100101011111011101111001010110010000001010110111011101110111110110101001101001101001101010010001000010010101100110111011101010000001010111010011010011010100110111010100110100110100110110101000001000100001101101010000010001010110111111101101010011010011010011011010100110111110011010100000000110010101100101100101011010011011010100101100101011110010010101101111101010001011001001010110100110010001010111100100101011011111010100100010001000001000100101011001011001011001001010110010001001010110111011110110101001000001010110111011101111101110110101001101110101001101111100100101011101111110111011010100001000001001010111011111110110101001101001101001101010000000110010101100100001011001001010111101111101010000010110010010101101001100100010101101111111011010100110111011010100010000100001010111011111010011011010100101100101011011010100100000010101101001101001101001101010011011101111001001010111111111001101010010001000010001000010010101101111101101010011001101111011101101010000010000100101011011111010100100010000100010000100101011011111011010100101100110010000101011010100010000010110010010101101001101010010010101101111110101001011001011001001010110011011101110101000100001010111011111010011011010100101100101011110010010101101001101101010011001000010101111001001010110011011101110101000010001000011011010100001000101011111110010101100100010001011010100110111111010100010110011010011010010101111110011010100100001000100010001000100101101010001100100101011111111001101010011010011010100110111011101111010011011010100101100101011111111100110101001000100001000100001001010110111011110110101001011001100100001010111111010011011010100001100101011011010100100010001000010001010111110111101010 ``` [Answer] # D, 472 bytes, 4275 characters ``` import std.stdio;import std.conv;import std.file;import std.format;import core.stdc.stdio;void main(char[][]a){bool f=true;char[] o;int i;char[64000]b;size_t j;FILE* g=core.stdc.stdio.fopen("i", "r");j=fread(cast(void*)b, 1, 64000, g);foreach(dchar n;b[0..j]){string c=format("%b",n);while(c.length<8)c='0'~c;for(i=0;i<8;i++){if(c[i]=='1')o~=f?"010":"101";if(i<7)o~=f?'0':'1';}for(i=0;i<6;i++){o~=f?'0':'1';f=!f;}f=!f;for(i=0;i<5;i++){o~=f?'0':'1';f=!f;}f=!f;}writeln(o);} ``` Loads input from a file called `i` in the same directory as the program. Tons of bytes waisted on the UTF input. Output: ``` 001000010000100001010110101110111011110111110101001010001000100001000001001010110101110111011101111101110110101001010000100000001010110101110111011110111110110101001010001000100010000010001001010110101111011111110101001010001000100000001001010110101111011111110101001010001000100010000010001001010110101110111011101111011110101001010001000100010000010001010110101110111011110111110110101001010001000100001000100010001010110101110111011111011101110110101001010000100001000100001010110101111011111110101001010001000100001000100001001010110101110111011111011110110101001010001000100000001001010110101110111011110111011101110101001010001000100010000100001010110101111011111110101001010001000100010000100001010110101110111011110111011101110110101001010000100000001010110101110111011101111011110101001010001000100000100001001010110101110111011101111101110110101001010001000100010000100001010110101111011111110101001010001000100010000100001010110101110111011110111110101001010001000100000100001001010110101111011111110101001010001000100000100001001010110101110111011111011101110101001010001000100000100010001010110101110111011111011110110101001010001000100000010001001010110101110111011101111011110101001010001000100001000001001010110101110111011101111011101110101001010001000100000100001001010110101110111011110111011101110101001010001000100000100001001010110101110111011101111101110110101001010001000100010000010001001010110101111011111110101001010001000100001000100010001001010110101110111011111011101110101001010000100000001010110101110111011101110111110110101001010001000100001000100010001001010110101110111011101111011110110101001010001000100010000010001010110101111011111110101001010001000100010000001010110101110111011101111101110101001010001000100001000100010001001010110101110111011111011101110110101001010001000100010000010001010110101110111011111110110101001010001000100001000100001001010110101111011110111011101110101001010000100000001010110101110111110111110101001010001000100000100001001010110101110111011101111101110101001010001000100000100001001010110101111011111110101001010001000100000001001010110101110111011101111101110101001010001000100000100001001010110101111011111110101001010001000100010000010001001010110101110111011110111011101110110101001010001000100001000100001001010110101110111011111011110110101001010000100000001010110101110111011101111101110110101001010001000100010000001010110101110111011111011110110101001010001000100000010001001010110101110111011110111110110101001010001000100000001001010110101110111011110111011110101001010000100000001010110101110111011111101110110101001010001000100001000001010110101110111011111110110101001010001000100010000010001010110101110111011111110110101001010001000100000010001001010110101110111011101111011110101001010001000100000100001001010110101110111011101111101110101001010001000100010000010001001010110101111011111110101001010001000100010000100001010110101110111011110111011101110110101001010000100000001010110101110111011110111011110110101001010001000100000001001010110101110111011110111101110110101001010001000100000100001001010110101111011111110101001010001000100001000100001001010110101110111011111110110101001010001000100010000100001010110101110111011101111011110101001010001000100000100001001010110101110111011101111101110101001010001000100010000010001001010110101111011111110101001010001000100001000001001010110101110111011110111011101110101001010001000100010000100001010110101110111011111011110110101001010001000100010000010001010110101110111011111011110110101001010001000100010000010001001010110101110111011101111011110101001010001000100001000001001010110101110111011110111011101110101001010001000100000100010001001010110101111011101110111101110101001010000100000001010110101101110111111011101110101001010000100000001010110101101110111101110111110101001010000100000001010110101101110111101110111011101110110101001010000100001000100010001010110101111011111110101001010001000001000001010110101110111011110111011101110110101001010001000100010000100010001001010110101111011111110101001010001000100001000100001001010110101110111011111011110110101001010001000100010000100001010110101110111011111110110101001010000100000001001010110101111011111110101001010000100010001000010001010110101110111111011110101001010 ``` ]
[Question] [ After the last Ludum Dare (LD) game programming contest [a friend of mine](http://williamedwardscoder.tumblr.com/post/95981602928/all-the-ld30-games-in-one-mosaic) made a nice mosaic of all the LD game thumbnails: [![mosaic of Ludum Dare games](https://i.stack.imgur.com/KvH50.jpg)](http://www.royvanrijn.com/blog/wp-content/uploads/2014/08/mosaic.jpg) After searching for my own game I quickly gave up and decided to solve it like a real programmer... by writing code that finds my game thumbnail. This is the thumbnail of my game: [![screenshot of game](https://i.stack.imgur.com/5JvqS.jpg)](http://www.royvanrijn.com/blog/wp-content/uploads/2014/08/target.png) More examples can be found by going to the Ludum Dare [list of games](http://www.ludumdare.com/compo/ludum-dare-30/?action=preview). So what is the challenge? Write a program that has the following input: ``` <filename_mosaic> <amount_of_tiles_x> <amount_of_tiles_y> <filename_target> ``` For example using the images above: ``` mosaic.jpg 59 43 target.png ``` The output should be the index of the target image. For the mosaic and screenshot above the correct index is: ``` 48,18 ``` The following (non-golfed) code provides a working example: ``` public class MosaicFinder { //Start with java MosaicFinder mosaic.jpg 59 43 target.png public static void main(String[] args) throws Exception { String mosaicFilename = args[0]; int tilesX = Integer.parseInt(args[1]); int tilesY = Integer.parseInt(args[2]); String targetFilename = args[3]; BufferedImage mosaic = ImageIO.read(new File(mosaicFilename)); int tileHeight = mosaic.getHeight()/tilesY; int tileWidth = mosaic.getWidth()/tilesX; BufferedImage tofind = ImageIO.read(new File(targetFilename)); //Translate target.png to correct size: BufferedImage matchCanvas = new BufferedImage(tileWidth, tileHeight, BufferedImage.TYPE_INT_RGB); AffineTransform at = AffineTransform.getScaleInstance((tileWidth*1.0)/tofind.getWidth(), (tileHeight*1.0)/tofind.getHeight()); ((Graphics2D)matchCanvas.getGraphics()).drawRenderedImage(tofind, at); int bestIndexX = 0, bestIndexY = 0; BigInteger lowest = null; for(int x = 0; x<tilesX;x++) { for(int y = 0; y<tilesY;y++) { //For all tiles: BigInteger error = BigInteger.ZERO; for(int x1 = 0; x1<tileWidth;x1++) { for(int y1 = 0; y1<tileHeight;y1++) { int rgb1 = matchCanvas.getRGB(x1, y1); int rgb2 = mosaic.getRGB((x*tileWidth)+x1, (y*tileHeight)+y1); int r1 = (rgb1 >> 16) & 0xFF; int r2 = (rgb2 >> 16) & 0xFF; error = error.add(BigInteger.valueOf(Math.abs(r1-r2))); int g1 = (rgb1) & 0xFF; int g2 = (rgb2) & 0xFF; error = error.add(BigInteger.valueOf(Math.abs(g1-g2))); int b1 = rgb1 & 0xFF; int b2 = rgb2 & 0xFF; error = error.add(BigInteger.valueOf(Math.abs(b1-b2))); } } if(lowest == null || lowest.compareTo(error) > 0) { lowest = error; bestIndexX = (x+1); bestIndexY = (y+1); } } } System.out.println(bestIndexX+","+bestIndexY); } } ``` This is a visual example of the code running: ![enter image description here](https://i.stack.imgur.com/znO5K.gif) This contest is a code-golf contest, the shortest code wins the challenge. **Update:** It seems stackexchange messes up the images a bit, on [my blog](http://www.royvanrijn.com/blog/2014/08/finding-an-image-in-a-mosaic/) you can find the source images for the examples in correct resolution. Also: I've fixed the amount of images from 42 to 43 **Current best: [David Carraher](https://codegolf.stackexchange.com/users/3967/david-carraher), [Mathematica (280)](https://codegolf.stackexchange.com/questions/36962/find-a-thumbnail-in-a-mosaic/36969#36969)** [Answer] # Mathematica - ~~280~~ 247 No need to scale the target to the tile size. The key is to match the average color for the target and for each tile. Closest match wins. In principle, it would be possible for the routine to choose the wrong match, but the test case suggests that this approach is surprisingly robust. The mean colors of target and selected tile were almost a perfect match: a distance of 0.00296966 away from the target mean color in RGB colorspace "cube" with edges of length 1. ## Ungolfed 364 chars ``` f[{m_, tilesx_, tilesy_, targ_}] := Module[{mosaic = Import[m],target = Import[targ], mDim = ImageDimensions[mosaic], (* find the average RGB colors for the target *) meanTargetPixelColor = Mean[Flatten[ImageData[target], 1]], m, t}, m = ImagePartition[mosaic, {mDim[[1]]/tilesx, mDim[[2]]/tilesy}]; (*Find the color distances between target mean rob and each mosaic tile Select the tile that best matches the average pixel color.*) t = SortBy[{#, EuclideanDistance[Mean[Flatten[ImageData[#], 1]], meanTargetPixelColor]} & /@ Flatten[m], Last][[1, 1]]; Reverse[Position[m, t][[1]]]] ``` **Example** Assuming that `mosaic` and `target`hold the respective filenames. ``` f[{mosaic, 59, 43, target}] ``` > > {48,18} > > > --- ## Golfed 247 ``` f@{p_,x_,y_,s_}:=Module[{k=Flatten,i=Import,z=i@p,w,m,t,r},r=ImageDimensions@z; w=Mean[k[ImageData[i@s],1]];m=ImagePartition[z,{r[[1]]/x,r[[2]]/y}]; Reverse[Position[m,SortBy[{#,EuclideanDistance[Mean[k[ImageData@#,1]],w]}&/@k@m,Last][[1,1]]][[1]]]] ``` [Answer] # Python (360) I seem to have broken PIL somehow, so load PPMs instead. For this reason, I insist that the thumbnail is already scaled correctly to the size of the tile in the mosaic. Its my first ever codegolf submission and I'm unsure the leeway I can expect in this regard. ``` import sys I=int R=range O=open M=map N='\n' A=ord S=sum # parse arguments _,m,c,r,t=sys.argv c=I(c) r=I(r) # load mosaic ppm _,w,_,m=O(m).read().split(N,3) w,h=M(I,w.split()) u=w/c v=h/r m=M(A,m) # load thumbnail ppm t=M(A,O(t).read().split(N,3)[3]) # make a list of the MSE of each tile in the mosaic, sort it, print the best print sorted((S(S((p-q)**2 for p,q in zip(t[(y*u+x)*3:][:3], m[((i*v+y)*w+j*u+x)*3:][:3])) for x in R(u) for y in R(v)), j+1,i+1) for j in R(c) for i in R(r))[0][1:] ``` Its **really** slow because of the `m[ofs*3:][:3]` to get the channels for each pixel; that's creating a list of the remainder of the pixels, and then slicing just the first three... horrid performance :) [Answer] # Java ~~(551)~~ (523) ``` public class F{ public static void main(String[]j)throws Exception{ BufferedImage m=read(new File(j[0])),c; int x=parseInt(j[1]),a=parseInt(j[2]), w=m.getWidth()/x,h=m.getHeight()/a, b=0; c=new BufferedImage(w,h,1); c.getGraphics().drawImage(read(new File(j[3])).getScaledInstance(w,h,Image.SCALE_SMOOTH),0,0,null); for(int d=1<<30,y=x*a,e;--y>0;) { e=0; for(int z=w*h;z-->0;) for(int i=0,l=c.getRGB(z/h,z%h),k=m.getRGB(y/a*w+z/h,y%a*h+z%h);++i<3;l>>=8,k>>=8) e+=pow((l&255)-(k&255),2); if(d>e){d=e;b=y;} } out.print(b/a+1+","+(b%a+1)); } } ``` Whitespace added to make it a bit clearer. Based on Roy's, but using a MSE, which is I believe a much superior metric. And less characters. Java is *really* verbose :/ Imports etc are: ``` import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import static javax.imageio.ImageIO.*; import static java.lang.System.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; ``` [Answer] # Java (707) My example code in golfed mode, removing spaces and using small variable names, without the needed imports: ``` public class F{public static void main(String[]j)throws Exception{BufferedImage m=read(new File(j[0]));int M=0xFF,x=parseInt(j[1]),a=parseInt(j[2]),w=m.getWidth()/x,h=m.getHeight()/a,b=0,n=0;BufferedImage u=read(new File(j[3])),c=new BufferedImage(w,h,1);((Graphics2D)c.getGraphics()).drawRenderedImage(u,getScaleInstance((w*1.0)/u.getWidth(),(h*1.0)/u.getHeight()));BigInteger d=null;for(;x-->0;)for(int y=a;y-->0;){BigInteger e=ZERO;for(int z=w;z-->0;)for(int v=h;v-->0;){int l=c.getRGB(z,v),k=m.getRGB(x*w+z,y*h+v);e=e.add(valueOf(abs(((l>>16)&M)-((k>>16)&M)))).add(valueOf(abs(((l>>8)&M)-((k>>8)&M)))).add(valueOf(abs((l&M)-(k&M))));}if(d==null||d.compareTo(e)>0){d=e;b=x+1;n=y+1;}}out.print(b+","+n);}} ``` The imports are: ``` import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.math.BigInteger; import static javax.imageio.ImageIO.*; import static java.awt.geom.AffineTransform.*; import static java.lang.System.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.math.BigInteger.*; ``` Java is horrible for code golf, but at least it is below 1000. ]
[Question] [ # The challenge Make a JavaScript program that can use a HTML table as a canvas, having each cell a pixel. You can either input the position and color values in a form or by using the console. # Score calculation * +10 points for not using JQuery * +15 points for the cells scaling equally to keep the same table aspect ratio when the browser is scaled * +15 points for accomplishing the last thing without using any kind of CSS * +[number of upvotes] * +20 points if you do not label the cells' tags with coordinates (it counts if you make an JavaScript array like `{"cell1-1": ..., "cell1-2": ..., "cell1-3": ...}` but it doesn't count when you label the `<td>` tag itself, like `<td id="cell-7-9">` or `<td class="cell-8-1">`) So if you have 67 upvotes, no JQuery (+10), the cells scaling (+15) but by using CSS (no +15) and you do not label the cells (+20), then your score will be 67 + 10 + 15 + 0 + 20 = 112. The challenge ends on **20 Feb 2014, 4:00 PM GMT+0**. **WINNERS:** Doorknob -> 61 + 3 = 64 points Victor, with 60 + 1 = 61 points they have very close scores so I couldn't exclude Victor. [Answer] # Score: 61 *10 (no jQuery) + 15 (scaling cells) + 15 (the scaling part uses no CSS) + 20 (no labels) + 1 (upvotes)* When you click on a cell, it turns the current color. ## JavaScript ``` var w = h = 20, color = 'red' function createTable() { var tbl = document.createElement('table') tbl.id = 'tbl' for (var i = 0; i < h; i++) { var tr = document.createElement('tr') for (var i2 = 0; i2 < w; i2++) { var td = document.createElement('td') td.addEventListener('mousedown', draw) tr.appendChild(td) } tbl.appendChild(tr) } document.body.appendChild(tbl) return tbl } function killTable(tbl) { tbl.parentNode.removeChild(tbl) } var tbl = createTable() function draw(e) { e.preventDefault() this.style.backgroundColor = color } document.getElementById('finalize').addEventListener('click', finalize) function finalize() { var tds = document.getElementsByTagName('td') for (var i = 0; i < tds.length; i++) { tds[i].style.border = 'none' tds[i].removeEventListener('mousedown', draw) } document.getElementById('optionsWrapper').style.display = 'none' } document.getElementById('changeColor').addEventListener('click', changeColor) function changeColor() { color = document.getElementById('color').value } document.getElementById('changeDims').addEventListener('click', changeDims) function changeDims() { var dims = document.getElementById('dims').value.split('x') w = +dims[0], h = +dims[1] killTable(tbl) tbl = createTable() } ``` ## HTML ``` <div id='optionsWrapper'> <button id='finalize'>Finalize</button><br/> <label for='color'>Color: </label><input id='color' type='text' value='red' /><button id='changeColor'>Go</button><br/> <label for='dims'>Change dimensions (WARNING: will erase drawing): </label><input id='dims' type='text' value='20x20' /><button id='changeDims'>Go</button> </div> ``` # CSS ``` td { width: 5px; height: 5px; padding: 0; border: 1px solid black; } table { border-collapse: collapse; } ``` ## JSFiddle <http://jsfiddle.net/D9u2N/1/> ## Screenshots Zoomed in view (while editing, click to enlarge to full size): > > [![screenshot](https://i.stack.imgur.com/RHaY3.png)](https://i.stack.imgur.com/RHaY3.png) > > > Finalized view (zoomed out): > > ![screenshot 2](https://i.stack.imgur.com/nnUgn.png) > > > [Answer] # Score: 60 + upvotes * No jQuery used. * No CSS. * The rule says *[cells scaling equally to keep the same table aspect ratio when the browser is scaled]*, it does that by not scaling at all when the window is resized and if you do use scaling/zoom in the browser, it will keep the aspect ratio. * No cell or row labeling used. The code basically creates a `TableCanvas` object. This object creates a table-based canvas and using javascript's DOM API, inserts it in a DOM node. Colors are specified as strings like `"rgb(0,255,0)"` for green. It features: * Resizing without deleting the canvas contents (except for the pixels clipped out of the canvas in the operation). * Zooming (not to be confused with scaling). * Clearing area to a color. * Pixel manipulation. * Line, rectangle and ellipse drawing. * Extensible API to add your own methods. * Allows the creation of multiple independent instances at the same time in different parts of your DOM. [Fiddle](http://jsfiddle.net/YF7M8/1) # The actual code ``` function TableCanvas(target, pp) { var w = -1, h = -1, zoomH = 1, zoomV = 1, defaultColor = "rgb(255,255,255)"; var rows = {}; var tbl = document.createElement("table"); var tblBody = document.createElement("tbody"); this.remake = function(p) { var newW = p.w ? p.w : w, newH = p.h ? p.h : h; if (newW < 0 || newH < 0) newW = newH = 0; if (p.zoomH) zoomH = p.zoomH >= 1 ? p.zoomH : 1; if (p.zoomV) zoomV = p.zoomV >= 1 ? p.zoomV : 1; if (p.defaultColor) defaultColor = p.defaultColor; for (var j = 0; j < newH; j++) { var isNewRow = j >= h; if (isNewRow) { var tr = document.createElement("tr"); rows[j] = {tr: tr, cells: {}}; tblBody.appendChild(tr); } for (var i = 0; i < newW; i++) { var isNewCell = isNewRow || i >= w; if (isNewCell) { var td = document.createElement("td"); td.style.background = defaultColor ? defaultColor : "rgb(255,255,255)"; rows[j].cells[i] = {td: td}; rows[j].tr.appendChild(td); } rows[j].cells[i].td.style.paddingLeft = (zoomH - 1) + "px"; rows[j].cells[i].td.style.paddingTop = (zoomV - 1) + "px"; } } for (var j = h - 1; j >= 0; j--) { for (var i = w - 1; i >= newW; i--) { rows[j].tr.removeChild(rows[j].cells[i].td); delete rows[j].cells[i]; } if (j >= newH) { tblBody.removeChild(rows[j].tr); delete rows[j]; } } w = newW; h = newH; return this; }; tbl.appendChild(tblBody); target.appendChild(tbl); tbl.setAttribute("border", "0"); tbl.style.borderSpacing = "0"; this.getTd = function(p) { return (p.x >= 0 && p.y >= 0 && p.x < w && p.y < h) ? rows[p.y].cells[p.x].td : null; }; this.getPixelColor = function(p) { return (p.x >= 0 && p.y >= 0 && p.x < w && p.y < h) ? rows[p.y].cells[p.x].td.style.background : null; }; this.setPixelColor = function(p) { if (p.x >= 0 && p.y >= 0 && p.x < w && p.y < h) { rows[p.y].cells[p.x].td.style.background = p.color ? p.color : defaultColor ? defaultColor : "rgb(255,255,255)"; } return this; }; this.drawRectangle = function(p) { for (var a = Math.min(p.x1, p.x2); a <= Math.max(p.x1, p.x2); a++) { for (var b = Math.min(p.y1, p.y2); b <= Math.max(p.y1, p.y2); b++) { this.setPixelColor({x: a, y: b, color: p.color}); } } return this; }; this.drawLine = function(p) { var t, x1 = p.x1, x2 = p.x2, y1 = p.y1, y2 = p.y2; if (Math.abs(x2 - x1) > Math.abs(y2 - y1)) { if (x1 > x2) { t = x1; x1 = x2; x2 = t; t = y1; y1 = y2; y2 = t; } for (var a = x1; a <= x2; a++) { this.setPixelColor({y: y1 + (y1 === y2 ? 0 : Math.floor((a - x1) * (y2 - y1) / (x2 - x1))), x: a, color: p.color}); } } else { if (y1 > y2) { t = x1; x1 = x2; x2 = t; t = y1; y1 = y2; y2 = t; } for (var a = y1; a <= y2; a++) { this.setPixelColor({x: x1 + (x1 === x2 ? 0 : Math.floor((a - y1) * (x2 - x1) / (y2 - y1))), y: a, color: p.color}); } } return this; }; this.drawEllipse = function(p) { var t, x1 = p.x1, x2 = p.x2, y1 = p.y1, y2 = p.y2; if (x1 > x2) { t = x1; x1 = x2; x2 = t; } if (y1 > y2) { t = y1; y1 = y2; y2 = t; } var rx = (x2 - x1 + 1) / 2, ry = (y2 - y1 + 1) / 2, cx = (x2 + x1) / 2, cy = (y2 + y1) / 2; for (var a = x1; a <= x2; a++) { for (var b = y1; b <= y2; b++) { if ((a - cx) * (a - cx) / (rx * rx) + (b - cy) * (b - cy) / (ry * ry) <= 1) this.setPixelColor({x: a, y: b, color: p.color}); } } return this; }; this.clear = function(c) { this.drawRectangle({x1: 0, y1: 0, x2: w - 1, y2: h - 1, color: c}); return this; }; this.getWidth = function() { return w; }; this.getHeight = function() { return h; }; this.remake(pp); } ``` # The test code ``` var body = document.getElementsByTagName("body")[0]; var divA = document.createElement("div"), divB = document.createElement("div"); body.appendChild(divA); body.appendChild(divB); divA.style.cssFloat = "left"; divA.style.marginRight = "10px"; divB.style.cssFloat = "left"; var canvas, canvas2, i = 0, f, commands = [ function() { console.log("Create a magenta canvas"); canvas = new TableCanvas({target: divA, w: 50, h: 50, defaultColor: "rgb(255,0,255)"}); }, function() { console.log("Draw black pixel"); canvas.setPixelColor({x: 2, y: 2, color: "rgb(0,0,0)"}); }, function() { console.log("Zoom 10x horizontal, 5x vertical"); canvas.remake({zoomH: 10, zoomV: 5}); }, function() { console.log("Draw green pixel"); canvas.setPixelColor({x: 9, y: 16, color: "rgb(0,255,0)"}); }, function() { console.log("Zoom to 3x"); canvas.remake({zoomH: 3, zoomV: 3}); }, function() { console.log("Paint as yellow"); canvas.clear("rgb(255,255,0)"); }, function() { console.log("Draw second green pixel"); canvas.setPixelColor({x: 29, y: 36, color: "rgb(0,192,0)"}); }, function() { console.log("Resize 1"); canvas.remake({w: 50, h: 60, defaultColor: "rgb(0,0,255)"}); }, function() { console.log("Resize 2"); canvas.remake({w: 60, h: 45}); }, function() { console.log("Resize 3"); canvas.remake({w: 45, h: 50, defaultColor: "rgb(255,0,0)"}); }, function() { console.log("Resize 4"); canvas.remake({w: 60, h: 60}); }, function() { console.log("Create a green second canvas"); canvas2 = new TableCanvas({target: divB, w: 50, h: 50, defaultColor: "rgb(0,255,0)"}); }, function() { console.log("Draw smiley"); canvas2.drawEllipse({x1: 1, y1: 1, x2: 48, y2: 48, color: "rgb(255,255,0)"}) .drawEllipse({x1: 10, y1: 10, x2: 20, y2: 20, color: "rgb(0,0,0)"}) .drawEllipse({x1: 30, y1: 10, x2: 40, y2: 20, color: "rgb(0,0,0)"}) .drawLine({x1: 10, y1: 30, x2: 15, y2: 35, color: "rgb(0,0,0)"}) .drawLine({x1: 15, y1: 35, x2: 35, y2: 35, color: "rgb(0,0,0)"}) .drawLine({x1: 35, y1: 35, x2: 40, y2: 30, color: "rgb(0,0,0)"}); }, function() { console.log("Draw cyan rectangle"); canvas.drawRectangle({x1: 10, y1: 10, x2: 45, y2: 45, color: "rgb(0,255,255)"}); }, function() { console.log("Draw orange ellipse"); canvas.drawEllipse({x1: 28, y1: 14, x2: 38, y2: 49, color: "rgb(255,128,0)"}); }, function() { console.log("Draw blue line"); canvas.drawLine({x1: 12, x2: 20, y1: 40, y2: 5, color: "rgb(0,128,255)"}); }, function() { console.log("Zoom to 4x"); canvas2.remake({zoomH: 4, zoomV: 4, h: 80}); }, function() { console.log("Draw black line"); canvas.drawLine({x1: 4, y1: -9, x2: 32, y2: 60, color: "rgb(0,0,0)"}); }, function() { console.log("Zoom to 2x3"); canvas2.remake({zoomV: 3}); }, function() { console.log("Zoom to 1x"); canvas2.remake({zoomH: 1, zoomV: 1}); }, function() {} ]; f = function() { (commands[i])(); i++; if (i < commands.length) setTimeout(f, 400); }; f(); ``` ]
[Question] [ It's asked to write a script to generate a source data to feed a JavaScript renderer. ## JS Renderer documentation The JS renderer is this script: ``` function o(x){ r=x.split(' '); (d=document).write('<style>i{position:absolute;width:10;height:10;background:#000}</style>'); for(i=0;i<r.length;++i){c=r[i].split(',');d.write('<i style=top:'+(e=eval)(c[0])+';left:'+e(c[1])+'></i>') } } ``` It takes as input a list of X/Y coordinates separated by spaces and commas and prints on DOM the points as **10×10** pixel squares. For example, if you call the script with: ``` o('0,0 10,0 20,0 30,0 40,0 20,10 20,20 0,30 10,30 20,30 30,30 40,30 0,50 10,50 20,50 30,50 40,50'); ``` It will print: ![HI example](https://i.stack.imgur.com/vMcIi.png) Notice that the values can be expressed as calculations, so it will accept: ``` o('10*2,50/5'); ``` ## Your task Write a script that, given as input a string of characters (`[A-Z0-9 ]`; uppercase letters, numbers, spaces) prints on **`stdout`** the coordinates to feed the JS renderer. ### Rules * The "line-height" of the characters should be of at least 50px * Your script doesn't need to run the JS parser * The expected output format is: `x,y x,y x,y x,y` * The shortest code wins **Bonus**: if you could reduce the length of the JS renderer without changing the behavior would be great **:)** [Answer] ## Mathematica - 164 bytes I'm happy to agree if you call this cheating, but it wasn't ruled out in the question. I let Mathematica rasterise the string and then throw away all white pixels and generate instructions from the rest: ``` g=""<>MapIndexed[If[#<1,"",{h,w}=ToString/@(10#2);h<>","<>w<>""]&,ImageData@Rasterize[#,RasterSize->(n=5StringLength@#),ImageSize->n]/.{(1.)..}->0/.{_,_,_}->1,{2}]& ``` It could probably be golfed down even further. Especially the `/.{(1.)..}->0/.{_,_,_}->1` looks suspiciously like it could be simplified. Slightly ungolfed: ``` g[str_] := ( n = 5*StringLength[str]; pixels = ImageData[Rasterize[str, RasterSize->n, ImageSize->n]] /. {1., 1., 1.} -> 0 /. {_, _, _} -> 1; StringJoin[ MapIndexed[ If[#1 < 1, "", {h, w} = Map[ToString, 10*#2]; h <> "," <> w <> "" ] &, pixels, {2} ] ] ); ``` This will handle really any characters in the string, and you can tweak the size by adjusting the `5` (which means letters are 5 pixels wide, which meets your requirement of them being 50 actual pixels tall). Here is some example output using a resolution of `7`: ![enter image description here](https://i.stack.imgur.com/jwKFg.png) And here using a resolutiong of `9`: ![enter image description here](https://i.stack.imgur.com/qFFyK.png) And `12`: ![enter image description here](https://i.stack.imgur.com/bnhaL.png) (The screenshots are somewhat minified to fit SE's column width, of course.) [Answer] # APL, 196 chars ``` f←37 5 3⍴(555/2)⊤95x⊥32-⍨⎕UCS'ne,[9fkO!|UUmYb~qu"*5n2wJgBe1P~P+E)$?ZGHb4{W(:edC2JdpirhX4I@m/K/q,ww <=:N%(euf9AJ"' ⎕←1↓∊{⍕¨' '⍺','⍵}/¨↑,/{10×(2↑4×⍵-1)∘+¨1-⍨a/⍥,⍳⍴a←⍉f[(' ',⎕A,∊⍕¨0,⍳9)⍳⍵⌷s;;]}¨⍳⍴s←⍞ ``` Dialect is [Nars2000](http://www.nars2000.org/). The first line produces the font, which I took from [this page](http://robey.lag.net/2010/01/23/tiny-monospace-font.html). I've encoded it in base 95 as printable ASCII characters, so the first line decodes it and turns it into a 37×5×3 bitmap. The second line reads a line of input. For each character it extracts the right bitmap from the font, produces a list of coordinates of the 'on' bits, adds an offset to the first coordinate (x) depending on the position in the string, multiplies by 10, formats the result as required, and outputs it. Here is the output for `HELLO WORLD 9` ``` 0,0 0,10 0,20 0,30 0,40 10,20 20,0 20,10 20,20 20,30 20,40 40,0 40,10 40,20 40,30 40,40 50,0 50,20 50,40 60,0 60,20 60,40 80,0 80,10 80,20 80,30 80,40 90,40 100,40 120,0 120,10 120,20 120,30 120,40 130,40 140,40 160,10 160,20 160,30 170,0 170,40 180,10 180,20 180,30 240,0 240,10 240,20 240,30 240,40 250,30 260,0 260,10 260,20 260,30 260,40 280,10 280,20 280,30 290,0 290,40 300,10 300,20 300,30 320,0 320,10 320,20 320,30 320,40 330,0 330,20 330,30 340,10 340,20 340,40 360,0 360,10 360,20 360,30 360,40 370,40 380,40 400,0 400,10 400,20 400,30 400,40 410,0 410,40 420,10 420,20 420,30 480,0 480,10 480,20 480,40 490,0 490,20 490,40 500,0 500,10 500,20 500,30 500,40 ``` And here it is turned into an image: ![enter image description here](https://i.stack.imgur.com/DCHVJ.png) It could probably be golfed a bit more here and there, but the main gain would come from a smarter font encoding. I can explain the code in more detail if anyone asks. [Answer] # Javascript (E6) 274 (261 function + 13 console output) Not so short, *but* any font, any size, any character ``` F=(m,f="50",F="Georgia")=>{d=1024;e=document.createElement("canvas");c=e.getContext("2d");e.height=e.width=d;c.font=f+"px "+F;c.fillText(m,0,f); i=c.getImageData(0,0,d,d).data;q='';for(p=d*d*4;p;p-=4)i[p-1]&&(q+=(p>>12)+'0,'+((p>>2)&(d-1))+'0 ');return q.trim()} ``` **Ungolfed** ``` function F(m, f="50", F="Georgia") { d = 1024 e = document.createElement("canvas") c = e.getContext("2d") e.height = e.width=d c.font = f + "px " + F c.fillText(m,0,f); i = c.getImageData(0,0,d,d).data; q='' for (p = d*d*4; p; p-=4) i[p-1] && (q += (p >> 12)+'0,'+((p>>2) & (d-1))+'0 '); return q.trim() } ``` **Usage** `console.log(F('HELLO WORLD'))` `console.log(F('Bonjour, monde',30,'Garamond'))` ]
[Question] [ # Challenge Write a program that generates the song "There Was A Stream", detailed below. ## Description The song "There Was a Stream" is a camping song. It takes N parameters and generates a song of length O(N2) lines. A sample song (first 3 verses) is given [here](http://pastebin.com/QpzkKCwi). ## Rules * Your entry must take a list of strings and output a valid song. It may be a function (that takes an array of strings) or a program (that takes strings from ARGV or STDIN). Output may be a return value or output to STDOUT or STDERR. * It must run within 1/2 second on my machine (1.66GHz Intel Atom, 1GB RAM, Ubuntu 12.04) for all invocations with less than 15 parameters. * Verses must be separated by a blank line. * No inbuilt compression function (e.g. gzip), whether from the core or from libraries. Things like `rot13`, `md5`, `base64` etc. are okay though. * You may include a data file (that is placed in the same directory and named whatever you wish), but its score will be added to the total for the program. ### Scoring Count the number of characters (if you use ASCII) or raw bytes (if you use something else). Command-line flags (without the hyphens) are included, but not the interpreter name, for example `#!/usr/bin/perl -n` adds 1 to the character count. All whitespace is included. As with all code-golf, the entry with the lowest character count wins. **Deadline:** 14 December 2012 ## Example ``` INPUT: bank house OUTPUT: (given above) ``` Reference implementation (ungolfed, very ugly code): <http://pastebin.com/VeR4Qttn> [Answer] ## Perl 239 + 2 = 241 bytes This is a mostly binary solution, so as usual, this is a program to generate it: generator.pl ``` use MIME::Base64; $data = <<EOD; JF89bGMgcGFjayB1NjAsJ8MqbtCBITBInQmKJcpWt4c2oWhLBPwjAkyBIiUwjBI3Ql9c9GoWtJZbuTd5 ZbuWhPwjAkyBIyQjDBFXQlLpGtKJWhP2t4c2r7mhFQjAqdM2t4eTjjk2aJcpWtKJWrb77ms6Kbpc2qKZ 6E1rmtKJWo7JYcmorNZWhM6+U1LpGobLGt4c2osqZ6NGobpGp4eTk0wiTBIXQlLpGr7mtKIdGhPwjBIT nQkyBISUwjBFXQtKJWhPxAjBLHR7KdNLJWh5r8ms9MpYbTIFQyc7eS8zLTovCkFGSUpUVyAvO2V2YWw= EOD print decode_base64($data); ``` Accepts input from STDIN, space separated, two extra bytes for the `-na` option. Sample usage: ``` $ perl generator.pl > out.pl $ stat -c %s out.pl 239 $ echo bank house | perl -na out.pl There was a stream (There was a stream) Just a teeny-weeny stream (Just a teeny-weeny stream) And the stream was on its way... Where the moon shines high In the clear blue sky And all was bright and gay. And on that stream (And on that stream) There was a little bank (There was a little bank) Just a teeny-weeny bank (Just a teeny-weeny bank) And the bank was on the stream And the stream was on its way... Where the moon shines high In the clear blue sky And all was bright and gay. And on that bank (And on that bank) There was a little house (There was a little house) Just a teeny-weeny house (Just a teeny-weeny house) And the house was on the bank And the bank was on the stream And the stream was on its way... Where the moon shines high In the clear blue sky And all was bright and gay. ``` ### Method Consider the following UU-Encoded string: ``` \PRINT($A,$B="8HERE:WAS:A:$L$_","3($B)3",$C="7UST:A:TEENY-WEENY:$_","3($C)",,$5=" \4ND:THE:$_:WAS:ON:$5","ITS:WAY...39HERE:THE:MOON:SHINES:HIGH36N:THE:CLEAR:BLUE:$ \SKY34ND:ALL:WAS:BRIGHT:AND:GAY.33"),$A="4ND:ON:THAT:$_",$A.="3($A)3",$5="THE:$_$ 5",$L='LITTLE:'FOR:STREAM,@5# ``` After applying a `lc,y/3-:/\nAFIJTW /` it becomes this: ``` \print($a,$b="There was a $l$_"," ($b) ",$c="Just a teeny-weeny $_"," ($c)",,$F=" \And the $_ was on $F","its way... Where the moon shines high In the clear blue $ \sky And all was bright and gay. "),$a="And on that $_",$a.=" ($a) ",$F="the $_$ F",$l='little 'for stream,@F# ``` Which is basically the 269 byte solution below. There's a few problems with this method, though. UU-Encoded strings are limited to characters 33-96, which excludes space, newline, and `{ | } ~`, as well as all lower-case letters. The solution I chose, is to apply `lc` after the `pack u`, and then translate 8 characters: space, newline, and the 6 upper-cased I needed. This leaves an 18 byte footprint, which is fairly excessive, but it produces the desired result. The other problem is that each line needs to begin with the same character (here I chose `\` corresponding to a *decoded* length of 60 (92 - 32), which is an *encoded* length of 80), except for the last line, which needs to begin with the character reflecting its length. Here I ended up with 21 (padding with a `#` to be evenly divisible by 3), corresponding to `5`. No problem, I'm replacing 5 anyway, so I chose it as one of my variables. Perl seems to be incredibly lenient about where you can place backslashes. This program even begins with one. It is possible to instruct perl to use a other characters to begin each line, such as `M` (the default value), but none seem quite as flexible as a backslash. As an aside, this method should be equally as effective in Ruby. If I had any skill in the language, I might be tempted to try it. For reference, my previous solutions remain below. --- ## Perl 267 + 2 = 269 bytes ``` (print$a,$b="There was a $l$_"," ($b) ",$c="Just a teeny-weeny $_"," ($c)",$d=" And the $_ was on $d",'its way... Where the moon shines high In the clear blue sky And all was bright and gay. '),$a="And on that $_",$a.=" ($a) ",$d="the $_$d",$l='little 'for stream,@F ``` Accepts input from STDIN, space separated, two extra bytes for the `-na` option. Sample usage: ``` $ echo bank house | perl -na stream-song.pl ``` --- ## PHP 286 bytes No real attempt at compression, just output reusage. ``` <?for($w=stream;$w;$a="And on that $w",$a.=" ($a) ",$l='little ',$d="the $w$d",$w=next($argv))echo$a,$b="There was a $l$w"," ($b) ",$c="Just a teeny-weeny $w"," ($c)",$d=" And the $w was on $d",'its way... Where the moon shines high In the clear blue sky And all was bright and gay. '; ``` Accepts input as command line arguments. Sample usage: ``` $ php stream-song.php bank house ``` [Answer] ## Haskell, 366 characters ``` t="stream" b o="And the "++o++" was on " p s=[s,'(':s++")"] a(o:q@(p:_))=(b o++"a "++p):a q a[o]=[b o++"its way..."] v l@(o:q)=w q++p("There was a "++if o==t then o else"little "++o)++p("Just a teeny-weeny "++o)++a l++["Where the moon shines high","In the clear blue sky","And all was bright and gay.",""] w m@(y:_)=v m++p("And on that "++y) w[]=[] s=v.reverse.(t:) ``` As permitted by the problem statement, this is a function `s :: [String] -> String`, where the input is the objects and the return value is a list of lines of the song. This is nowhere near the current leader in this challenge, but it's as far as I got and I thought someone might like to see if it can be improved. I think its main failing is trying too hard to capture all of the structure of the song in the structure of the program. It also might be interesting to rewrite it to use lists of words (replace `++` with `,` and fewer spaces), or `\n`s rather than a list of lines. Fluffy source: ``` stream="stream" andthe o="And the "++o++" was on " p s=[s,'(':s++")"] ander :: [String] -> [String] ander(o:os@(p:_))=(andthe o++"a "++p):ander os ander[o]=[andthe o++"its way..."] outerVerse :: [String] -> [String] outerVerse l@(o:os)=recurse os++p("There was a "++if o==stream then o else"little "++o)++p("Just a teeny-weeny "++o)++ander l++["Where the moon shines high","In the clear blue sky","And all was bright and gay.",""] recurse :: [String] -> [String] recurse m@(y:_)=outerVerse m++p("And on that "++y) recurse[]=[] song=outerVerse.reverse.(stream:) go xs = putStr $ unlines $ song xs ``` Defluffifier (in Perl): ``` #!/usr/bin/perl -wp s/ ?\+\+ ?/++/g; s/ander/a/g; s/andthe/b/g; s/iverse/i/g; s/song/s/g; s/stream(?!")/t/g; s/\bos\b/q/g; s/outerVerse/v/g; s/recurse/w/g; s/ends/z/g; s/^go .*//s; s/--.*//s; s/^\s\Z//s; s/^.*::.*\Z//s; ``` [Answer] **Python 2.7 352 Bytes** ``` import urllib as u;import re,sys;v=sys.argv;f=lambda l,o,n:[re.sub(o,n,i) for i in l];n='\n';d=-1;m=re.findall('i\d.+>(.+)</d',u.urlopen('http://goo.gl/48fMV').read());a=m[:8]+[n];z=range;s='stream' for t in z(len(v)+d):a+=f(m,s,v[t])[9:11]+f(m,s,'little '+v[t+1])[:4]+['And the '+v[i+1]+' was on a '+v[i] for i in z(t,d,d)]+m[4:8]+[n] print n.join(a) ``` Example usage: ``` python stream bank house ``` Output: ``` There was a stream (There was a stream) Just a teeny-weeny stream (Just a teeny-weeny stream) And the stream was on its way... Where the moon shines high In the clear blue sky And all was bright and gay. And on that stream (And on that stream) There was a little bank (There was a little bank) Just a teeny-weeny little bank (Just a teeny-weeny little bank) And the bank was on a stream And the stream was on its way... Where the moon shines high In the clear blue sky And all was bright and gay. And on that bank (And on that bank) There was a little house (There was a little house) Just a teeny-weeny little house (Just a teeny-weeny little house) And the house was on a bank And the bank was on a stream And the stream was on its way... Where the moon shines high In the clear blue sky And all was bright and gay. ``` Un-golfed (also added a few `a+=`s): ``` #!/usr/bin/env python import urllib as u import re import sys v=sys.argv f=lambda l,o,n: [re.sub(o,n,i) for i in l] n='\n'; d=-1; m=re.findall('i\d.+>(.+)</d',u.urlopen('http://goo.gl/48fMV').read()) a=m[:8]+[n] z=range s='stream' for t in z(len(v)+d): a+=f(m,s,v[t])[9:11] a+=f(m,s,'little '+v[t+1])[:4] a+=['And the '+v[i+1]+' was on a '+v[i] for i in z(t,d,d)] a+=m[4:8]+[n] print n.join(a) ``` ]
[Question] [ [Whispers](https://github.com/cairdcoinheringaahing/Whispers) is February 2021's Language of the Month, so what tips do you have for golfing in it? Tips do not have to be specific to [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so long as they apply to other types of challenges on the site. Tips should be at least somewhat specific to Whispers (e.g. "remove ignored code" is not an answer). Please post one tip per answer. [Answer] # Order is important Swap lines that are referenced more frequently than other lines with less referenced lines that are referenced by a small digit number. **Example:** ``` > 1 > 2 > 3 > 4 > 5 > 6 > 7 > 8 > 9 > Input >> #10 >> [10] >> Output 11 12 ``` The input is referenced twice and the line number is `10`. If this line is moved up to *line 1*. Both `10`s are replaced by `1`s. In this example 2 bytes were saved. ``` > Input > 1 > 2 > 3 > 4 > 5 > 6 > 7 > 8 > 9 >> #1 >> [1] >> Output 11 12 ``` Moving *line 11* and *12* up saves another 2 bytes. ``` > Input >> #1 >> [1] > 1 > 2 > 3 > 4 > 5 > 6 > 7 > 8 > 9 >> Output 2 3 ``` I wrote a script that takes a Whispers program as input and prints the optimized re-ordered program. [TIO](https://tio.run/##lVfrT@NGEP@c/BWjVD2tm2Al9N2AVY7jqkgcQZCqH7g0WuxN2MOxrfWGC6342@nsy4/YAYrYWN55z/5mZv2FPtCDNGPJl@j@ma@zVEj4gns@T/33m@WSCRZdMRoxMe7ukCfTs23IMsnTpElLso28loLRdZv0RvLYPxGCPp7zXO6j5S2E0zSOWahstlH3aBNsxbb@JyrDu1ZPDP2SSslE0kLPdSDOdiry8XO2uY15CGFM8xw@UZ7Av91OJvgDlQxySSUSlzyhMWAWeLKC69nJ1Wwx/bj4@OfF6WwyvVicTy7O4Bh6QdAb75G1LsGHyR@T2fXi8mQ2O7u6QCFL8MN0nfGYkR75@/PnyPuO4G/f63lNhSo1R8aXABZcnc@4i1wmDsv0kPII1hgNMZw3c6BilXsquI4Uj0DqmIBb/YoOJewr1GlEbTVwQK4fc8nWPk88z6jtGGdQh1HmxzxhOfEwNp1uUqbdl6kKg3gqvk6nEtLNPADBlPUkZGof1YVoVbKr6i4xgjyRGFkahhtNyQvmabFFatqM2CSRCBSBojyJ2HaSXCNMWDQVGNclRebS6qTBQEpzRtuKJUwg60kSXWIIcrqRmAayT7UWeoJQgRhIpfaA2TwyP1N6riUN72eChsxE@9TF/wYc9EnvceH1OI3FAiMZE@sNckzsQdr3l2JB8WUqAFkkcBQZjvFxVNfkxyxZyTuk9Ps2RltMCiKlHcN9w@fmcJdAFB2rlgqZ/8XlHWkvPgdAhQfAQpb61LQzetsYe7/hsYJ6qpNjoV4jWVR1bIPBAjLP45269S1Bu2dlvt5h@QKxFB/LPiKFX9oxbp1aMeNfwbsS6SYjh94AXsQM/hnXfZphn4@09UEZ78D5axKG1h2jVut0VPPjBBSTpT@VidSHhlz6EMyb49JnUyg6srxFuK/4abmrBi0QrKBMzblYc5rF9hvkMOURJ2X620ujhP/eWt5pICaAWvAFzYG4a/vVBL0JAH8y26YUnIpReBSQSpRtFeJqot/nNm@3aRozmkCYJhJbd@6q0PRVH3FDuOqmhkp6mt4zKXJ@@DSKTMPGnbJVYU0hugZ11Z7LXacyjP0c00OcugFUSYI9MJEzkzrPFP9LPcYmxbGYiOdvT0hTI8aBAkWwNiVFRRUBCSY3OG6bCsatSDEwaIyOfXMpL3BSBY@NVu2WnH7O/8H@XQZd9NqCB35raK6yQrJZ32IuK1xFu8MqNNSiPCGAYVmGxfG7UeA/0HjDpksr5sEBjDz4toHyeb9fqc6nelYL5vZk7mStdXprD606C29zN8PrwppmZAsHQW1QbB/VDatXDIbt/5gKWnaL6M1iHKYncUx6N@qWNe8NoAe2gJ6AxTmrSiCp7D7W1@2jj/4oL/dq8/Ms5pI4xU@v3n/a8ViOCZsBmd6zZABvnemWz6HnGHYRoPV5ZTsz5EDZVvcoc3H3aa4dfXEwFcUmc18zonYLMIcvTTOl4EEfRu1h795D3nyBqXXsfayVBt648Ohoa1eCt3ar8kpT02UaVbVz7/EKGXe7Vk2RzhTmynygqK4O@FkTszVT53SKnw1U0NuY2XlU@XgxXx7K7YU@83ErSfvVILlRtOBmVJzjpFXtXk8VJac1DqC41wwKESthkmIsYyacB52FuwY5w52qDbVv3ixCfp/iyBE8YsUXjjIZ6rDZLCU6Iam8U71MIwF7Q03hu3eG7Fd33XxB5nJ2YOs0nOWW6yD2YA5G1VaxI330mvSo0U2G7uC11yZVTo15tSpq9ivmrUzwgsxoB1xDV3plNitB1NuyOSAFv@fnAEbdAA5xfY/rB1w/4voJ18@4fsH1Ky6d4W4QwDejoXrcjIZz9TQfJDAawejwPw) | [Github](https://github.com/MichaelChat/ReorderYourWhispers) [Answer] # Use `Then` to group values into an array `Then` is a command which takes an indefinite number of arguments and puts them in an array: ``` > "hello" > "world" >> Then 1 2 ``` The last line here returns `['hello', 'world']`. This can then be used with `Each` or `Select` to output things or modify them for something else. ]
[Question] [ As the trip through the solar system on your way to [rescue Santa](https://adventofcode.com/2019) gets a little droll, so perhaps some optimizations to your Intcode Computer are in order. Namely, making it as small as possible because you've got nothing better to do with your time. *Check out Advent of Code if you haven't already, [the guy](https://adventofcode.com/2019/about) that makes the puzzles is amazing; Day 11 blew my mind. I might be cribbing the specs for the Intcode Computer, but why not challenge people to minify it?* ## Here are the specifications for an Intcode Computer: Links to the day where the specifications are introduced will be included. These pages will contain example programs to use as test cases as well as supplemental explanation, as I presume I don't have to explain what it means to "read from" or "write to" a memory address. * An Intcode program is a list of integers (for example, `1,0,0,3,99`). To run one, start by looking at the first integer (called position `0)` this will be the opcode (enumerated below). Following an opcode will be its arguments (if any, each opcode will detail how many). *Entries may take programs in any reasonable format, including how to handle any input to an Intcode program.* * Intcode Computers have an instruction pointer that, after executing an instruction moves forward a number of positions based on the opcode (1 plus the number of arguments). ([Day 2](https://adventofcode.com/2019/day/2)) * Each parameter of an instruction is handled based on its parameter mode. The rightmost two digits of an opcode indicate the opcode itself, while the remaining digits (read from right to left) indicate the argument mode (how the literal value of the argument is handled). ([Day 5](https://adventofcode.com/2019/day/5)) + `0` is position mode. Read from the position indicated; eg. `mem[a]` + `1` is immediate mode. Read as a literal value; eg. `a` - Parameters that an instruction writes to will never be in immediate mode. + `2` is relative mode. Read from the position indicated by adding the RelativeCounter to the value; eg. `mem[a+r]` * Intcode Computers have a `RelativeCounter` which is a value that is used as an offset for relative mode arguments. This value starts at `0` (during which, relative mode acts identically to position mode). ([Day 9](https://adventofcode.com/2019/day/9)) + The `RelativeCounter` may hold a negative value. * The computer's available memory should be much larger than the initial program. Memory beyond the initial program starts with the value 0 and can be read or written like any other memory. (It is invalid to try to access memory at a negative address, though.) * The computer should have support for large numbers and negative numbers; `long`s are sufficient. ## Opcodes: Arguments will be noted as `A`, `B`, etc. where `A` is the first argument, `B` is the second, and so on. * `1`: Adds `A` and `B` and stores the result in `C` * `2`: Multiplies `A` and `B` and stores the result in `C` * `3`: Reads an integer from input and stores the result in `A` * `4`: Outputs the value read from `A` * `5`: Jump-if-true. If `A` is non-zero, it sets the instruction pointer to the value of `B` * `6`: Jump-if-equal. If `A` is zero, it sets the instruction pointer to the value `B` * `7`: Less than. If `A` is less than `B`, it stores `1` in the position given by `C`. Otherwise, it stores `0` * `8`: Equals. If `A` is equal to `B`, it stores `1` in the position given by `C`. Otherwise, it stores `0` * `9` Adjusts the RelativeCounter by the value of `A`. The relative base increases (or decreases, if the value is negative) by the value of the parameter. * `99`: Terminates the program * Other opcodes are invalid. ### Opcode & paramater mode detail Taken from [Day 5](https://adventofcode.com/2019/day/5): ``` ABCDE 1002 DE - two-digit opcode, 02 == opcode 2 C - mode of 1st parameter, 0 == position mode B - mode of 2nd parameter, 1 == immediate mode A - mode of 3rd parameter, 0 == position mode, omitted due to being a leading zero ``` ## Test cases `[3,9,8,9,10,9,4,9,99,-1,8]` Using position mode, consider whether the input is equal to 8; output 1 (if it is) or 0 (if it is not). `[3, 3, 1107, -1, 8, 3, 4, 3, 99 ]` Using immediate mode, consider whether the input is less than 8; output 1 (if it is) or 0 (if it is not). (From [Day 5](https://adventofcode.com/2019/day/5)) `[109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99]` takes no input and produces a copy of itself as output. `[1102, 34915192, 34915192, 7, 4, 7, 99, 0]` should output a 16-digit number. `[104, 1125899906842624, 99]` should output the large number in the middle. (From [Day 9](https://adventofcode.com/2019/day/9)) `[109, -1, 4, 1, 99]` outputs -1 `[109, -1, 104, 1, 99]` outputs 1 `[109, -1, 204, 1, 99]` outputs 109 `[109, 1, 9, 2, 204, -6, 99]` outputs 204 `[109, 1, 109, 9, 204, -6, 99]` outputs 204 `[109, 1, 209, -1, 204, -106, 99]` outputs 204 `[109, 1, 3, 3, 204, 2, 99]` outputs the input `[109, 1, 203, 2, 204, 2, 99]` outputs the input (From [Reddit](https://www.reddit.com/r/adventofcode/comments/e8aw9j/2019_day_9_part_1_how_to_fix_203_error/fac3294/) regarding [Day 9](https://adventofcode.com/2019/day/9)) `[3, 11, 3, 12, 1, 11, 12, 9, 104, 0, 99]` takes two inputs and outputs their sum *Day 9 features a [self-test program](https://adventofcode.com/2019/day/9/input) that will output opcodes that do not appear to be operating correctly, provided that your Intcomputer is fully functional to Day 5 specifications. It is very long and contains per-user unique code relevant to part 2's puzzle, as such it is not included here.* [Day 7](https://adventofcode.com/2019/day/7), [Day 11](https://adventofcode.com/2019/day/11), [Day 13](https://adventofcode.com/2019/day/13), [Day 15](https://adventofcode.com/2019/day/15), [Day 17](https://adventofcode.com/2019/day/17), [Day 19](https://adventofcode.com/2019/day/19), [Day 21](https://adventofcode.com/2019/day/21), and [Day 23](https://adventofcode.com/2019/day/23) all contain Intcode programs as well (as does, presumably, [Day 25](https://adventofcode.com/2019/day/25) if the pattern holds). And remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")! But that only applies to the Intcode Computer itself, any auxillary code to handle executing it is not counted towards your score. ### A Helpful Hint When testing your intcode computer, it is very helpful to run the diagnostic program. [Here's a copy for those without an AOC account](https://gist.github.com/JonoCode9374/60df1703155957ef2a288ff3bd5d135a). Sometimes, your program will constantly output `203` when running this program. That means that opcode `03` doesn't work when placed in "relative mode". Quite a few of us on the CGCC Discord were experiencing this issue. For information on how to fix this, read [here](https://www.reddit.com/r/adventofcode/comments/e8aw9j/2019_day_9_part_1_how_to_fix_203_error/) [Answer] # [Python 3](https://docs.python.org/3/), ~~480 476 474 418~~ 416 bytes -56 bytes thanks to Value Ink ``` def a(c,i,o): p=g=r=0;c+=[0]*9999 def v(b):r;x=c[p+b];return eval(["c[x]","x","c[x+r]"][m[b]]) def s(b,e):c[c[p+b]+r*(m[b]>1)]=e while g!=99: g=c[p];m=[0]*4;k,g=g//100,g%100;n=1 while k:k,m[n]=k//10,k%10;n+=1 if g<3or 6<g<9:x,y=v(1),v(2);s(3,[x==y,x+y,x*y,x<y][g&3]);p+=4 if g==3:s(1,i());p+=2 if g==4:o(v(1));p+=2 if g==5:p=v(2)if v(1)else p+3 if g==6:p=p+3 if v(1)else v(2) if g==9:r+=v(1);p+=2 ``` Takes as input the code, an input function (called with no arguments whenever the code requests input), and an output function (called with one argument, the value just output, whenever the program outputs something). I included all of the test cases given in the TIO link. [Try it online!](https://tio.run/##jVPbcpswEH3nK1R32hFhk0iAHQusfkKn74ymgx2FMLaBgu3ir0@lFb4lbsYMEsvu2bNHl232m9e6it7envULyekCSqj9xCONLGQrWboIZMbUnTCPRyxmR@d@0qa9XGRNMFdpqzfbtiJ6l69oNlpkvRrBqDfDmEGrRipbZ3OlfJfd0TloP1lkLjto76gN/@C@ktojf1/LlSbFFymE0UAKW0Sla5QQp0soZPH4yBmD4puZ00pyg3JJy2QJ66xScmkRsDSAtAoQUL6QYhbVLZnMiplIetjLHeU@7Gjopx2NIOul3EMfmHFnxmyvsuJ7pPy0CWQ8EEgZJR3lUFIf/eHRHyc1tXzv3OOkkbZCafeM@3rVadIE0TE@MXHzT87jFn8EiKQNUCjy4gF1m7rVv81WbzXt7TGZp1jV83xF0IkOtIgkvZfTLAIBUzPMlgiIzRAC7jlMFazy9fw5T57gjNT38q7T7cZxSMluoph@RsG9P9uysnoyzgQQDiRkMRDDQMwZuhnd7svY9GBOrOECB9O4hVAecneWUxmFWCBLFJCfdaXBVe4e8qbR1fOlnk5KRNt1cc5CIFEs@JiLC@sJSIyzWSlhR95rq1zpinabljqvT6Q0upHdLpLzcDw1rcMm0zichDGq/4xuODv5IdNRCrdvMe6XpbqB6Z5f5DpdN2dfJodnyTetggnvxTTeRncbUlanK2Dm8HARJo7vGMOv@F80vNByz5kDuF7Iqa10dhUu1CHinULDcl1hhC8WCYcFn2mITvrDs/pfya@8zau6zPHXEpdVs0Vm4y805Wxo2wuxQyMh9oroj7IR6R3581OBseM/huYfQvbBEDaQA4GjUYc4tr25hLgJPHTnwp0phkvketFldg9N3cAV4deV5yQY1Hlv/wA "Python 3 – Try It Online") [Answer] # [JavaScript (V8)](https://v8.dev/), ~~234~~ 230 bytes Expects `([program], [input])`, where *input* is ordered from last to first. Prints to stdout. ``` f=(P,i,p=r=0)=>(n=P[p++])-99&&([A,B]=(g=n=>o--?[(v=P[p++],k=n%10|0)-1?P[v+=k>1&&r]||0:v,...g(n/10)]:[])(n/100,o=~-(n%=10)%6>>1||3),n<4?P[v]=n<2?A+B:n<3?A*B:i.pop():n<5?print(A):n<7?!A^n>5?0:p=B:n<9?P[v]=n<8?A<B:A==B:r+=A,f(P,i,p)) ``` [Try it online!](https://tio.run/##rVVRb9owEH7vr7g9FMXDSe0QIKaYCKS97GGrNO0pyqSMBPAKdpYEqmpsf53ZIdAwrStFi@SzfXG@@76zffkWb@JimoustDf@bjfj1h0WOOM5J4iPLMnvwqzdjpDNWKtlhWM8ibg155KPlG0HobWpF@B7Lq8p2RJk0@Au3LT5/Yi2Wnm03ZLBBjuOM7fkDSUoGoQRqoYEK/7LtuQ11@7r3mhEt9sOwnLoGYCIy6EbjNuTgRx2gvHbyUA4mcospOfdIMuFLK2xmfSDN@MvctQNyCDjZjU7fO4H4@FkMObam7f5GM/22hDa3YZXAGHYwQz7ulGijacbY9im2I8whH6k7YvPzQ18LoScQ6YKUQolYaWSFMNUyUIkaQ4Pi7Rc6F4bEDJblyAKSL@v4yWUCvxbUOvSeClYYgbCvEagciBPc5CqRM6LhPuacL2ogykl/eqNHnu6MWaWsLM0NVSJ1SpNRFymZ8lapkWhPbG8QNdzlI@qKNGysUs8s0Yfnsrg2hLi7wc93VW@/YDUKJVuraqM71MTt@YcywSyXCXrqfbGWl32CMqwK9LlDOKiFrHnqPm5uOMx2qWsMehrsn2zD@QY6B9pLRZqvUwOyYmB9uxEzHU65Hr1Nc3rSFokpW7XZ4yRnu@5PddrCjlrA08jmX1axvk8rQPpBFS@lUiSZeocM6xzq2O/LthJ2H28AmzaxKwUXYbawDyBdP8PJGGN08Wwuz9hvdcDN0A1RAPUWHYh7LOg7lMSbEpeh/ssqLmFBtGt4ajbuYTpsSac8O3UuT2Ae93e@Yf579CmZpjC4ZosU9Oz6qQdbn0fa/4vQe9LQvlQ14SiKgqNeCKHYr26iq6cmcrfxdOFZYUxBhEh4CP4UZVEpa/QUs2t958@fnCKUv@b5mL2aMUIwx8ugdAtzCwDgOAn2v0G "JavaScript (V8) – Try It Online") ## How? The implementation is rather straightforward, except the computation of the number of parameters for a command \$n \le 9\$, for which we use the following formula: ``` (n - 1) % 6 >> 1 || 3 ``` Which gives: ``` n | -1 | %6 | >>1 | ||3 | action ---+----+----+-----+-----+-------------- 1 | 0 | 0 | 0 | 3 | A+B -> P[C] 2 | 1 | 1 | 0 | 3 | A*B -> P[C] 3 | 2 | 2 | 1 | 1 | input -> A 4 | 3 | 3 | 1 | 1 | output A 5 | 4 | 4 | 2 | 2 | p=B if A!=0 6 | 5 | 5 | 2 | 2 | p=B if A==0 7 | 6 | 0 | 0 | 3 | A<B -> P[C] 8 | 7 | 1 | 0 | 3 | A==B -> P[C] 9 | 8 | 2 | 1 | 1 | r+=A ``` ## Commented ### Helper function \$g\$ is a helper function that retrieves \$o\$ parameters according to the upper digits of the current command, which are passed in \$n\$. ``` g = n => // n = command / 100 o-- ? // decrement o; if it was not equal to 0: [ // update the list of parameters ( // v = P[p++], // v = next value read from the program k = n % 10 | 0 // k = floor(n mod 10) ) - 1 ? // if k is not equal to 1: P[v += k > 1 && r] // read P[v] if k = 0 or P[v + r] if k = 2 || 0 // if undefined, use 0 instead : // else: v, // immediate mode: use v ...g(n / 10) // recursive call with n / 10 ] // end of update : // else: [] // stop recursion ``` ### Main function ``` f = ( // f is a recursive function taking: P, // P[] = program i, // i[] = input p = r = 0 // p = program pointer, r = relative counter ) => // (n = P[p++]) - 99 && ( // read the next command n and stop if it's 99; otherwise: [A, B] = g( // retrieve the first 2 parameters A and B (the latter // may be undefined) by invoking g: n / 100, // pass n / 100 o = ~-(n %= 10) % 6 >> 1 // set o = number of parameters for this command, || 3 // using the formula described above ), // end of call to g n < 4 ? // if n is less than 4: P[v] = // update P[v]: n < 2 ? A + B // if n = 1, store A + B : n < 3 ? A * B // if n = 2, store A * B : i.pop() // if n = 3, store the next input : // else: n < 5 ? // if n = 4: print(A) // output A : // else: n < 7 ? // if n = 5 or n = 6: !A ^ n > 5 ? 0 // jump if (A == 0) XOR (n == 6) is false : p = B // : // else: n < 9 ? // if n = 7 or n = 8: P[v] = // update P[v]: n < 8 ? A < B // test A < B if n = 7 : A == B // or A == B if n = 8 : // else: r += A, // update r f(P, i, p) // recursive call for the next command ) // end ``` [Answer] # AWK, 285 283 bytes ``` {for(split(i,v);o<99;r+=o>8?x:0){o=$++p;a=int(o/100)%10;b=int(o/1000)%10;w=$++p+1+!!a*r;x=--a?$w:$p;y=$++p+1+!!b*r;y=--b?$y:$p;z=$++p+1+!(o<10^4)*r;o%=100;if(o~3)$w=v[++j];if(o~4)printf"%.f\n",x;if(o~/1|2|7|8/)$z=o<2?x+y:o<3?x*y:o<8?x<y:x==y;else{--p;p=o~5?x?y:p:o~6?!x?y:p:p-1}}} ``` [Try it online!](https://tio.run/##RY/ZboMwEEW/hchIOLaLTWgKGNdv/YkuEkhBoo1ii0TBDsuvUwdXzcvMnXtGs1T9z7IMjeqisz62l6jFV8hVmee8Q0K9ZtIUFA5KAIQ0r0R7ukQqZpTCkFFeP2pv9GsfYigIqm3HjSCkkqAvgOb2gWqHrEO1BPaObv8oUiWjXyl0DSoUbixvm0jNOwh6cX1H6PvTGynUnVvdbMKn5uO0wcbbMRuT8WXMYghuQpWJNMgWqtxJs71n90xpCyOE5Yfj@TAQorkWan6WRtpCF2rey8BLTdg0TcvCaI4ZTmiKCcPunjXgv0hp5sXepdXzguI8X8gb/gU "AWK – Try It Online") This essentially works by treating the input fields as the locations in memory, instead of initializing an array to store the program. An extra 3 bytes (included in score) are required for the `-F,` switch, which sets the comma as the field separator. ## Usage examples `<code>` stands for the program posted above. Interpret an Intcode program stored in a file named `intcode.txt`: ``` awk -F, '<code>' intcode.txt ``` Interpret an Intcode program using a [Here-string](https://en.wikipedia.org/wiki/Here_document): ``` awk -F, '<code>' <<< 9,1,204,-1,2205,-1,8,99,0 ``` Pass a value as input: ``` awk -F, -v i=1 '<code>' intcode.txt ``` Pass multiple input values: ``` awk -F, -v i=1,2,3 '<code>' intcode.txt ``` ]
[Question] [ [Make a Number Expression](https://codegolf.stackexchange.com/questions/34500/make-a-number-expression) is related : actually, it is also about Aheui. But it just made number expression, but this made real Aheui code. --- [Aheui](https://aheui.readthedocs.io/en/latest/specs.en.html) is esolang written in only Korean character. Because of its nature, Aheui can't use Arabic numbers. But, of course, there is way to generate number. ## Brief introduction to Aheui Reading the link above is best, but put it shortly : Aheui is befunge-like esolang : have cursor, every character is instructor, and using stack. One instructor, looks like `박`, have three part : Initial consonant`ㅂ`, vowel`ㅏ`, final consonant`ㄱ`. First part, initial consonant, determine what to do. Here is table of initial consonant that can be useful here: * `ㅇ` : no operation. * `ㅎ` : terminate. * `ㄷ` : pop two number from current stack, than add them, and push to current stack. * `ㄸ` : same as `ㄷ`, but multiply instead of add. * `ㄴ` : pop two number from current stack, push `second // first` to current stack. * `ㅌ` : same as `ㄴ`, but subtract instead of divide. * `ㄹ` : same as `ㄴ`, but modulo instead of divide. * `ㅂ` : push number to current stack. Number is given by final consonant. * `ㅃ` : duplicate top of current stack. * `ㅍ` : swap top two value of current stack. Second part, vowel, determine momentum. Maybe you just need `ㅏ`, go to next. Last part, final consonant, determine number to used in `ㅂ` commend. Here is list of final consonant and number. 1. Nothing 2. `ㄱ`, `ㄴ`, `ㅅ` 3. `ㄷ`, `ㅈ`, `ㅋ` 4. `ㅁ`, `ㅂ`, `ㅊ`, `ㅌ`, `ㅋ`, `ㄲ`, `ㄳ`, `ㅆ` 5. `ㄹ`, `ㄵ`, `ㄶ` 6. `ㅄ` 7. `ㄺ`, `ㄽ` 8. `ㅀ` 9. `ㄻ`, `ㄼ` Finally, `망` is printing operator. Your code have to print `망희` or `망하` or whatever after calculation, to print and terminate the program. ## Korean Character Every Aheui instructor is Korean character. As I mentioned above, Korean character has three part : Initial consonant(`choseong` or `초성`), Vowel(`jungseong` or `중성`), Final consonant(`jongseong` or `종성`). Every character has initial consonant and vowel, but final consonant is option. Korean character in Unicode is from `AC00`(`가`) to `D7A3`(`힣`). For composing Korean character, look at [this webpage](http://gernot-katzers-spice-pages.com/var/korean_hangul_unicode.html) for help. ## Question Input is an positive integer. Generate aheui code that prints given integer, without hardcode every possibility. You can test your Aheui code at [try it online](https://tio.run/#aheui). ## Examples ``` Input | Output | Discription 1 | 반밧나망희 | Put two 2s in stack, divide, print, and halt. 1 | 반반나망희 | Same as above. 1 | 밪반타망희 | Put 3 then 2 in stack, subtract, print, and halt. 3 | 받망희 | Put 3 in stack, print, halt. 3 | 반밧나빠빠다다망희 | Put two 2s in stack, divide, duplicate two times, add two times, print, halt. This is OK, but won't get good point. 72 | 밢밣따망희 | Put 8 and 9 in stack, multiply, print, and halt. 10 | 박밙따망희 | Put 2 and 5 in stack, multiply, print, and halt. ``` ## Scoring Average length of 101 Aheui codes that prints 100 to 200. If score is same, shorter code wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), Score 849/101 = 8.406; 126 bytes of Jelly code ``` 9,`€µŒċZ€ṪḢ,0Ɗ¹E?ṭƊ€ż,ƭ€Ɱ€⁾+×ẎF€€ḢV;Ɗ€;@1ị<ɗƇ201FL$Þµ1ịⱮŒQTịµ$3¡Ṣṫ100Ṫ€F€⁵;‘,@⁾+פyⱮị⁽ıaD×588+“Ḥþ’Ḣ;+¥“ƲG~ọ’b21¤;ƲƲ¤;€“ẒP“ṃƓ’Ọ ``` [Try it online!](https://tio.run/##PY4xS8RAEIX/yhXpEmETEU5WMIWejYWCCFqpYCNnY3eNJAoqd2oRiyioYIiN3gkXCGST84rZy4I/Y/aPxNkTbPbNPt73Zk6Ou91e0yw7B/piCHkdzQb7NKH4wCJxmOqDWF9FMVJ9cuuJo0akevxl3nBqyxjL@475EFMku3ye476L1WDlJ1bXHnM7m5Z8hdxYBNbR9g5NkFuL8IYiQfHpMkb7iJsXhTnXwaPj/9VD2iPIoOH3bHy4JuOldtvWwTMWqZzq4Im2chveyVHZxjlWd@QdeS6kXGUqIzGdFC@jLSPiUj0YqrptIKGjGDvzGPuPtRZaOniBtJ5wn@7mPpY38urU2mt@AQ) A niladic link that returns a list of Jelly strings, one for each Aheui number from 100 to 200. The footer on TIO prepends the total length and the mean length. Note this is equal in score to [attinat’s Mathematica answer](https://codegolf.stackexchange.com/a/186697/42248), but shorter in code length to generate the Aheui numbers. Full explanation to follow. Uses ㅂ (push), ㄷ (add), ㄸ (multiply) and ㅃ (duplicate) for initial consonants. Output: ``` 8.405940594059405 849 100 - 밖밙빠따따망희 101 - 밖밙따밟빠따다망희 102 - 밨밤밟다따망희 103 - 밙밤따밞밟따다망희 104 - 밤밖밟다따망희 105 - 받밙밞따따망희 106 - 밙빠따밟빠따다망희 107 - 밙밞따밤밟따다망희 108 - 박밨밟따따망희 109 - 밖밞따밟빠따다망희 110 - 바밟다박밟다따망희 111 - 밙밨따밟빠따다망희 112 - 박밞밤따따망희 113 - 밖밤따밟빠따다망희 114 - 밨밞따밤밟따다망희 115 - 받박밞밤따따다망희 116 - 밙밞따밟빠따다망희 117 - 밟밖밟다따망희 118 - 밨밟따밤빠따다망희 119 - 밞밤밟다따망희 120 - 받밙밤따따망희 121 - 박밟다빠따망희 122 - 바박밟다빠따다망희 123 - 밨밞따밟빠따다망희 124 - 박밨밞밤따다따망희 125 - 밙밙빠따따망희 126 - 박밞밟따따망희 127 - 밞밟따밤빠따다망희 128 - 박밤빠따따망희 129 - 밨밤따밟빠따다망희 130 - 바밟다밖밟다따망희 131 - 받박밤빠따따다망희 132 - 박밨따박밟다따망희 133 - 밙박밤빠따따다망희 134 - 박받밤빠따다따망희 135 - 받밙밟따따망희 136 - 밤밤밟다따망희 137 - 밞밤따밟빠따다망희 138 - 박밙밤빠따다따망희 139 - 받밤밤밟다따다망희 140 - 밖밙밞따따망희 141 - 바밖밙밞따따다망희 142 - 박밖밙밞따따다망희 143 - 박밟다밖밟다따망희 144 - 박밤밟따따망희 145 - 밤빠따밟빠따다망희 146 - 박바밤밟따다따망희 147 - 받밞빠따따망희 148 - 바받밞빠따따다망희 149 - 박받밞빠따따다망희 150 - 밙밙밨따따망희 151 - 바밙밙밨따따다망희 152 - 박밖밤밟따다따망희 153 - 밟밤밟다따망희 154 - 박밞따박밟다따망희 155 - 박밟밤밟다따다망희 156 - 박밨따밖밟다따망희 157 - 밖밟밤밟다따다망희 158 - 박밞밤밟따다따망희 159 - 받밖밞빠따다따망희 160 - 밖밙밤따따망희 161 - 바밖밙밤따따다망희 162 - 박밟빠따따망희 163 - 바박밟빠따따다망희 164 - 박바밟빠따다따망희 165 - 박밟다받밙따따망희 166 - 박박밟빠따다따망희 167 - 밙박밟빠따따다망희 168 - 받밞밤따따망희 169 - 밖밟다빠따망희 170 - 바밟다밤밟다따망희 171 - 박밖밟다빠따다망희 172 - 박밙밟빠따다따망희 173 - 밖밖밟다빠따다망희 174 - 박밨밟빠따다따망희 175 - 밙밙밞따따망희 176 - 박밤따박밟다따망희 177 - 박밙밙밞따따다망희 178 - 박밤밟빠따다따망희 179 - 밖밙밙밞따따다망희 180 - 밖밙밟따따망희 181 - 바밖밙밟따따다망희 182 - 박밞따밖밟다따망희 183 - 받밖밙밟따따다망희 184 - 밖바밙밟따다따망희 185 - 밙바밖밟따다따망희 186 - 받밨밞밤따다따망희 187 - 박밟다밤밟다따망희 188 - 밖박밙밟따다따망희 189 - 받밞밟따따망희 190 - 바받밞밟따따다망희 191 - 박받밞밟따따다망희 192 - 받밤빠따따망희 193 - 바받밤빠따따다망희 194 - 박받밤빠따따다망희 195 - 받밙따밖밟다따망희 196 - 밖밞빠따따망희 197 - 바밖밞빠따따다망희 198 - 박밟다박밟따따망희 199 - 받밖밞빠따따다망희 200 - 밙밙밤따따망희 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), score 849/101 = 8.406 ``` g@n_:=f@n<>"망히" f@n_:=f@n=Switch[n,-1,"밯",1,"반반나",9,"밞",8,"밣",7,"밝",6,"밦",5,"발",4,"밗",3,"받",2,"박", _,mn@{m@n,a@n,s@n}] m@n_:=m@n=f@#<>If[# #==n,"빠",f[n/#]]<>"따"&/@Select[Divisors@n,1<# #<=n&]//mn a@n_:=a@n=f@#<>f[n-#]<>"다"&/@Range[⌈n/2⌉-1]//mn s@n_:=s@n=m[n+#]<>f@#<>"타"&/@Range[n-1]//mn mn=First@*MinimalBy[StringLength[""<>#]&] ``` [Try it online!](https://tio.run/##hY7PSgMxEIfv@xRlForWKdvW/7pbgoogWFF7DEFC3W4DZgptVEQE0UtFj4qCtgiKHvXq63gVn6EmK4voRUjmI8l8v4yWphVraVRDDocJo625qMkorMLHc/9z0AOvmd1F9X1lGi1OWCwjfLy@AKa8cevkBnDWnQaAM44PgNOOfcApxyfAScc7wAnHa8Bxx1vAiuMVoLeFmtihZoTS7i6jI@Hp9Htb7Qh@WF1pcj/nRxFZ5@0esMkp8IVw816@Qj5g9Xgnbhi@pPZUt92xGVgOrRFGlBdBoMmTaaDMAm1A0U/980fnb0pKYv5@0aOg8n5xVix/W93UsjXSnMackNrweXr8Y1HWrSlaVp2uYYWaIqXlzsIBr5uOomQ1psS0OEBY9UVeDEcKVt1u68VWWzXif/sLo97GrooN99btq@E@Qi7KAa4x@8pqsaRfXsCSbLZyqYSVUkmI@UwtVhNn/W3wxPAL "Wolfram Language (Mathematica) – Try It Online") Builds numbers with `다` (+) `따` (\*) `타` (-), and `빠` (duplicate), in addition to literals for 2..9. Doesn't actually make use of `밯`=-1. Paste the tio output ([Unicode character codes](https://reference.wolfram.com/language/tutorial/CharacterCodes.html)) into Mathematica to see the result: ``` 100 -> 밗발빠따따망히 101 -> 박밞박밞다따다망히 102 -> 밦밣밞다따망히 103 -> 받밗발빠따따다망히 104 -> 밣밗밞다따망히 105 -> 받발밝따따망히 106 -> 박밗밝빠따다따망히 107 -> 박받발밝따따다망히 108 -> 박밦밞따따망히 109 -> 밗받발밝따따다망히 110 -> 박발박밞다따따망히 111 -> 받박발밝따다따망히 112 -> 박밝밣따따망히 113 -> 발박밦밞따따다망히 114 -> 박받밦밞따다따망히 115 -> 발박받밝따다따망히 116 -> 박박밝밣따다따망히 117 -> 밞밗밞다따망히 118 -> 박받밝밣따다따망히 119 -> 밝밣밞다따망히 120 -> 받발밣따따망히 121 -> 박밞다빠따망히 122 -> 박발밝밣따다따망히 123 -> 받발밗밞따다따망히 124 -> 박밦밝밣따다따망히 125 -> 발발빠따따망히 126 -> 박밝밞따따망히 127 -> 박발발빠따따다망히 128 -> 박밣빠따따망히 129 -> 받받발밣따다따망히 130 -> 박발밗밞다따따망히 131 -> 받박밣빠따따다망히 132 -> 박밦박밞다따따망히 133 -> 밝박밣밞다다따망히 134 -> 박받밣빠따다따망히 135 -> 받발밞따따망히 136 -> 밣밣밞다따망히 137 -> 박받발밞따따다망히 138 -> 박발밣빠따다따망히 139 -> 받밣밣밞다따다망히 140 -> 밗발밝따따망히 141 -> 받박발밞따다따망히 142 -> 박밝밣빠따다따망히 143 -> 박밞다밗밞다따망히 144 -> 박밣밞따따망히 145 -> 발박받밞따다따망히 146 -> 박밞밣빠따다따망히 147 -> 받밝빠따따망히 148 -> 박박밣밞따다따망히 149 -> 박받밝빠따따다망히 150 -> 발발밦따따망히 151 -> 밗받밝빠따따다망히 152 -> 박밗밣밞따다따망히 153 -> 밞밣밞다따망히 154 -> 박밝박밞다따따망히 155 -> 발받밗밝따다따망히 156 -> 박밦밗밞다따따망히 157 -> 밗밞밣밞다따다망히 158 -> 박밝밣밞따다따망히 159 -> 받밗밝빠따다따망히 160 -> 밗발밣따따망히 161 -> 밝박받밝따다따망히 162 -> 박밞빠따따망히 163 -> 받밗발밣따따다망히 164 -> 밗발밗밞따다따망히 165 -> 받발박밞다따따망히 166 -> 박박밞빠따다따망히 167 -> 발박밞빠따따다망히 168 -> 받밝밣따따망히 169 -> 밗밞다빠따망히 170 -> 박발밣밞다따따망히 171 -> 받받밦밞따다따망히 172 -> 박발밞빠따다따망히 173 -> 밗밗밞다빠따다망히 174 -> 박밦밞빠따다따망히 175 -> 발발밝따따망히 176 -> 박밣박밞다따따망히 177 -> 받받밝밣따다따망히 178 -> 박밣밞빠따다따망히 179 -> 밗발발밝따따다망히 180 -> 밗발밞따따망히 181 -> 밦발발밝따따다망히 182 -> 박밝밗밞다따따망히 183 -> 받발밝밣따다따망히 184 -> 밗밗밦밝따다따망히 185 -> 발박발밝따다따망히 186 -> 받밦밝밣따다따망히 187 -> 박밞다밣밞다따망히 188 -> 밗박발밞따다따망히 189 -> 받밝밞따따망히 190 -> 발박밗밞따다따망히 191 -> 박받밝밞따따다망히 192 -> 받밣빠따따망히 193 -> 밗받밝밞따따다망히 194 -> 박받밣빠따따다망히 195 -> 받발밗밞다따따망히 196 -> 밗밝빠따따망히 197 -> 발받밣빠따따다망히 198 -> 박밞박밞다따따망히 199 -> 받밗밝빠따따다망히 200 -> 발발밣따따망히 ``` The lowest number that improves with `타` is 211, with `받밣밞따따발타` (3\*8\*9-5) beating out `발밠밝따따반반나다` (5\*6\*7+2/2). The next lowest, 239 (`받밞빠따따밗타`=3\*9\*9-4), didn't require `반반나` in its `다`/`따`-only construction (`받밣밞따밝다따박다`=3\*(8\*9+7)+2). [An earlier version of this program](https://tio.run/##NY9NS8NAEIbv/RUyC0VhQmj9qMomLCKCopfmuCxlCflYaKaQLIpXT4JXxYK2CIpee/U3lf6GmCkIAw/zMs8wU1lfZpX1LrVtWyianEa5IhnD@mexWT5CL//PouTO@bTUhAOE9WrO9TAHPOFuCXjM/AQcMReAR8xvwEPmO@AB8xVwn/kGOGS@APYmeOHqxqsbR66y07N7fTVzpHMlZJxrCoThc56@oB@qXQrGlopMUzgMBmYPt1OXuRY7IoqoW/n7AdhZoTBb7XnFWpJNs9Trc3frmlndqO4H2Rkyor4xmPjaUXGdUeFLDSBjYbq4bf8A) generated `다`/`따`-only constructions. --- ## With `밯=-1` (score unchanged) ``` g@n_:=f@n<>"망히" f@n_:=f@n=Switch[n,1,"밯",9,"밞",8,"밣",7,"밝",6,"밦",5,"발",4,"밗",3,"받",2,"박", _,mn@{m@n,a@n,s@n}] m@n_:=m@n=f@#<>If[# #==n,"빠",f[n/#]]<>"따"&/@Select[Divisors@n,1<# #<=n&]//mn a@n_:=a@n=f@#<>f[n-#]<>If[#==1,"타","다"]&/@Range[⌈n/2⌉-1]//mn s@n_:=s@n=m[n+#]<>f@#<>If[#==1,"다","타"]&/@Range[n-1]//mn mn=First@*MinimalBy[StringLength[""<>#]&] ``` [Try it online!](https://tio.run/##hY/NSgMxFEb38xTlDhStt0xb/3VSgoogqKhdhiChTqcBcwvTqIgIgpuKLhUX2iIoutStr@NWfIaatFRx5SI5EL7v3BujbDMxyuq66vdTTrsLrMEprsLnS/er14GgMXpjtSNt601BWEb4fHsFnPfsAc55PgLOenYBZzyfAac97wGnPG8BJz3vACueN4DBLhriJ4YTKnfanE5lYAbz3O1mhnF1rSHCXMgYuc77A2BDUBRK6Re8foN8xGvJflK3YkUf6nYrcw4sx64RM8rLKDIUqIFQjYROUAzlUMyY@8rX@Rk4@eUTSKfbUZQm4uOqQ1Hl4@qiWB5K2gOJu5kRNOH7P9sNJL4@VP1KaFQ2xFZ11ra8sKFJG7W/dCxqNtOUrieU2qYAiKuhzMv@WMFV91pmudnS9eTffGE8yNhwWLlUwkqpJIPtA51YEWy5uBUhQo7lADe5i/ONRNEfUcTTiGdycZQuVlMfdG@B7H8D "Wolfram Language (Mathematica) – Try It Online") If the program is given no input, `밯` (read a character from input) returns -1, which allows for a one-character `1` literal. The lowest number that benefits from this is 269, which improves to `발밦밞따따밯다` (5\*6\*9+(-1)) from `박받밣밞빠따다따다` (2+3\*(8+9\*9)). ]
[Question] [ The set of [necklaces](https://en.wikipedia.org/wiki/Necklace_(combinatorics)) is the set of strings, where two strings are considered to be the same necklace if you can rotate one into the other. Your program will take nonnegative integers `k` and `n`, and generate a list of the `k`-ary (fixed) necklaces of length `n`. Necklaces will be represented by any representative string. So the necklace corresponding to the strings {ABC, BCA, CAB} can represented as `ABC`, `BCA`, *or* `CAB`. The program will output a list of strings, such that each necklace is represented by *exactly one* string in the list. So for instance, outputting `ABC` and `BCA` would not be valid, since the same necklace was represented twice. Some other details: * Your program may choose which `k` characters to use for the alphabet. If you prefer, you can instead choose `k` distinct values of any type, and have your program output lists (or some other sequence type) of those `k` values. (This might in fact be necessary if `k` is greater than the number of characters avaible in your language.) For example, if `k=3`, you could use {A,B,C}, {&, H, (}, or even {10, 11, 12} as your alphabet. The only restriction is that elements of your alphabet may not contain whitespace. * You may output any representative for each necklace. So for the necklace {ABC, BCA, CAB}, you may output `ABC`, `BCA`, or `CAB`. There is no "preferred" representative. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program wins! --- Also, here is a useful test to see if your program is working. Given `k` and `n`, the list your program outputs have the length listed [here](https://en.wikipedia.org/wiki/Necklace_(combinatorics)#Number_of_necklaces). Here is an [OEIS sequence](http://oeis.org/A000031) corresponding to `k`=2. Also, here are some examples and counterexamples. Note that these are not test cases, because any input has both an infinite number of correct and incorrect outputs. I will give inputs in the form `(k,n)`. Examples: * `(2,2)`: `[AA, BB, AB]` * `(2,2)`: `[AA, BA, BB]` * `(2,2)`: `[[1,0], [0,0], [1,1]]` * `(3,2)`: `[AA, BB, CC, AB, BC, AC]` * `(2,3)`: `[AAA, BBB, AAB, ABB]` * `(3,3)`: `[AAA, BBB, CCC, AAB, AAC, ABB, ABC, ACB, ACC, BBC, BCC]` * `(0,n)`: `[]` (for positive integers n) * `(k,0)`: `[[]]` (for nonnegative integers k) * `(k,n)`: Search ["necklaces with k colors and n beads"](https://www.wolframalpha.com/input/?i=necklaces%20with%203%20colors%20and%205%20beads) on wolfram alpha (for positive integers k and n) Counterexamples: * `(2,2)`: `[AA, BB, AB, BA]` * `(2,2)`: `[AA, BB]` * `(3,3)`: `[AAA, BBB, CCC, AAB, AAC, ABB, ABC, ACC, BBC, BCC]` * `(3,3)`: `[AAA, BBB, CCC, AAB, BAA, AAC, ABB, ABC, ACB, ACC, BBC, BCC]` * `(k,n)`: Any list whose length is different from [this](https://en.wikipedia.org/wiki/Necklace_(combinatorics)#Number_of_necklaces) (for positive integers n) * `(3,3)`: `[AAA, BBB, CCC, AAB, BAA, AAC, ABB, ABC, ACC, BBC, BCC]` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṗṙJṂȯƲ€Q ``` A dyadic Link accepting the alphabet size, `k`, on the left and the necklace length, `n`, on the right which yields a list of the necklaces using the positive integers up to `k` as the alphabet. **[Try it online!](https://tio.run/##ASYA2f9qZWxsef//4bmX4bmZSuG5gsivxrLigqxR/8OnxZLhuZj//zP/NA "Jelly – Try It Online")** ### How? ``` ṗṙJṂȯƲ€Q - Link: integer k, integer n ṗ - Cartesian power of [1,2,...,k] with n - i.e. all n-length lists using alphabet [1,2,...,k] Ʋ€ - last four links as a monad for €ach list, L: J - range of length - i.e. [1,2,...,n] ṙ - rotate left by each of those values - i.e. get all rotations Ṃ - minimum ȯ - logical OR with L (since the minimum of an empty list is 0 not []) Q - unique values the resulting list ``` [Answer] # [Python 2](https://docs.python.org/2/), 105 bytes ``` lambda k,n:{min(i[j:]+i[:j]for j in range(n or 1))for i in product(*[range(k)]*n)} from itertools import* ``` [Try it online!](https://tio.run/##LYoxDsIwDAD3vsJjUrpAt0i8JGQotAGnjR257oAQbw9UMJ3udOWpD6ZTjedLXYZ8HQeYO3KvjGTQJxcO6F0KkQUSIIEMdJ8MwdeP1u4Z91yEx@2mpvW/YbahJftuonAG1EmUeVkBc2HRthZBUogGqWxqbPenrX3TfwA "Python 2 – Try It Online") Returns a set of tuples. [Answer] # JavaScript (ES7), ~~123 116 115~~ 113 bytes Takes input as `(k)(n)`. Each necklace is represented as an array of integers. ``` k=>g=(n,x=k**n,o=[])=>x--?g(n,x,o.some(a=>~(a+[,a]).search(b),b=[...Array(n)].map(_=>x/k**--n%k|0))?o:[b,...o]):o ``` [Try it online!](https://tio.run/##dY5BCsIwFET33kP4vyax2J2QFs8RgqQ1rdo2vyQiFcSrx7gUK8zq8WaYq7mb0PjLdOOOTja2Mvay7CQ4Nss@yxwjqTTKcua86j6UkQg0WjCyfIHZKGY0imCNb85QI6ulEkIcvDcPcKjFaCY4pvo2jXHu1v0zR6xor2qWPNK4p9iQCzRYMVAHLewwBVffsFiCySyWzF@Y/zHTl/gG "JavaScript (Node.js) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 27 bytes ``` ?UÆVoÃrï ®c £ZéYÃn gÃâ:[[]] ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=xlZvw3LvW1tdXSCuYyCjWulZw24gZ8Pi&input=MwozCi1R) Outputs with numbers starting from 0 for the values. Inputs in reversed order (`n` then `k`). The `r` throws a fit for `n = 0` so I had to add an significant [special-case](https://ethproductions.github.io/japt/?v=1.4.6&code=P1XGVm/Dcu8grmMgo1rpWcNuIGfD4jpbW11d&input=MAoyCi1R). Explanation: ``` ? :[[]] #Special case: return [[]] if n is 0 UÆ Ã #Get n rows of: Vo # The numbers [0..k-1] rï #Get all possible lists containing one number from each row... ® Ã #For each of those lists: c # Fix the formatting £ZéYÃ # Get every possible rotation n g # Choose the "minimum" one â #Remove duplicate lists ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes ``` Nθ≔Xθ…⁰⊕Nη≔⊟ηζ¿ηIEΦζ⁼κ⌊﹪÷×ι⊕ζηζ﹪÷ιηθ¶ ``` [Try it online!](https://tio.run/##ZY7LCsIwEEX3/YrgagoRxG1X4gO6qIi4dBPb0Q7m0TZJhf58TK2LirMa7uVwblmLrjRChpDrxrujVzfsoE2zZGMtPTSczGsMODsL/UBYcZbrskOF2mEFcyiNx1k9RxuoYzTEiO4s/uzUkXawFdZBIRo4kHSRHDjbt15IC0/OCtKkvILCVF6aaHA76qlCuJBCC/Q7YJico@Sj/6NoqtuxzhKUFr8jFle9SLMQ1mwdlr18Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ≔Xθ…⁰⊕Nη≔⊟ηζ ``` Input `k` and `n` and calculate the powers of `k` from `1` to `n`, but then keep `kⁿ` separately. ``` ¿η...¶ ``` If `n` is zero then just print a newline. (I could special-case `0` in the algorithm which would only cost two bytes but the resulting array only contains an empty array and Charcoal optimises that away on output, so you can't tell that the empty array is there.) ``` Φζ⁼κ⌊﹪÷×ι⊕ζηζ ``` For all the numbers from `0` to `kⁿ`, multiply them all by `kⁿ+1`, then divide by the above powers of `k`, then take the modulus of all of them by `kⁿ`. Keep only those numbers which equal the minimum of the resulting set. ``` IE...﹪÷ιηθ ``` Convert the numbers to reversed base `k` padded to length `n` for output using Charcoal's default output which is each element on its own line and each necklace double-spaced from the next necklace. ]
[Question] [ > > **Build a function in python that can win a [Sevens](https://en.wikipedia.org/wiki/Sevens_(card_game)) game provided that there are only 2 players** > > > --- Here are the instructions from [Wikipedia](https://en.wikipedia.org/wiki/Sevens_(card_game)#Rules_and_Laws): > > All cards are dealt to the players, even if as a result some players > have one card more than others. The owner of the seven of hearts > begins by playing it. Similarly, the other three sevens may later be > played as the first cards of their respective suits. After that, cards > may be added in sequence down to the ace and up to the king. A player > who cannot place a card passes. > > > **You cannot pass if you have a card to play.** > > > The one who gets the seven of hearts is the first to play. > > > The cards will be randomly distributed to the user and the computer. The function will have two parameter: 1. List of cards remaining to play for computer 2. List cards that have been played The syntax of a card is like this: > > `[value, suit]` > > > For example [king, "clubs"] --- > > The list of suits are: > > > * clubs > * spades > * diamonds > * hearts > > > The list of values are: > > > * 1 > * 2 > * 3 .... > * 11(jack) > * 12(queen) > * 13(king) > > > The remaining cards for player 1 will be stored in list named `card_1_rem` and the remaining cards for player 2 will be stored in list named `card_2_rem` The cards that have been played will be stored in a list called `played_cards` --- The function will have to append the played card to the list called `played_cards` and subtract the item for the list called `card_1_rem` or `card_2_rem` The return of one function will be the input of the competitor The one who finishes his cards first, wins. **Winning Condition** --- Step 1: Users will submit their programs. Step 2: I will test the programs against each other. Step 3: The first program **to remain in first place (as measured by lowest total running score) for 50 consecutive games will be the winner**. This will help smooth out the effects of luck. However, a maximum of 10000 games will be played, and if no player meets the first criterion, then the player with the lowest total score after 10000 games wins. Step 4: All the results will be uploaded to a github repo(which I will soon make). --- > > The loser has to count his points as follows > > > > ``` > Ace : 1 > 2 : 2 > 3 : 3 > 4 : 4 > 5 : 5 > 6 : 6 > 7 : 7 > 8 : 8 > 9 : 9 > 10 : 10 > jack : 10 > queen : 10 > king : 10 > > ``` > > For example if a king and an ace remain in the loser's hand, he gets > 11 point. > > > The objective is to minimize the points you have got. > > > Winner gets 0 points > > > IMP : Submissions are allowed only in the [Python 3](https://www.python.org/) language. The controller code of this challenge is here(major update has been done): <https://gist.github.com/Salil03/19a093554205b52d05dc7dc55992375a> [Answer] ## Tactical This ended up different enough that I felt it deserved a separate entry. This one calculates slightly smarter scores, looking not just at the next step but future choices for each player as well, based on the cards they hold. Seems to do a lot better than the "synergistic" version, better enough to beat the mysterious `player2` advantage. ``` def tactical(cards_in_hand, played_cards): def list2dict(lst): d = {} for val, suit in lst: if suit in d: d[suit].append(val) else: d[suit] = [val] return d def play_card(card): cards_in_hand.remove(card) played_cards.append(card) hand = list2dict(cards_in_hand) if not played_cards: if 7 in hand['hearts']: play_card([7, 'hearts']) return (cards_in_hand, played_cards) table = list2dict(played_cards) playable_cards = {} for suit in hand: if suit not in table: if 7 in hand[suit]: # Do I hold the majority of the cards of this suit? suit_advantage = (len(hand[suit]) - 6.5) playable_cards[(7, suit)] = suit_advantage * 20 if 6 in hand[suit] and 8 in hand[suit]: # opponent can't immediately make use of this playable_cards[(7, suit)] += 20 continue visible = set(table[suit] + hand[suit]) opp_hand = set(range(1,14)) - visible highcard = max(table[suit]) + 1 if highcard in hand[suit]: advantage = sum(c > highcard for c in hand[suit]) - sum(c > highcard for c in opp_hand) playable_cards[(highcard, suit)] = advantage * 10 if highcard + 1 in opp_hand: playable_cards[(highcard, suit)] -= 20 lowcard = min(table[suit]) - 1 if lowcard in hand[suit]: advantage = sum(c < lowcard for c in hand[suit]) - sum(c < lowcard for c in opp_hand) playable_cards[(lowcard, suit)] = advantage * 10 if lowcard - 1 in opp_hand: playable_cards[(lowcard, suit)] -= 20 if not playable_cards: return (cards_in_hand, played_cards) best_card = max(playable_cards, key=playable_cards.get) #print(hand, "\n", table, "\n", best_card, ":", playable_cards[best_card]) play_card(list(best_card)) return (cards_in_hand, played_cards) ``` [Answer] ## Synergistic I'm not really a Python guy, but wanted to give this a go. This builds the set of playable cards at each turn, and assigns each of them a simple static score. The card with the highest score is played (assuming any playable card exists). ``` def synergistic(cards_in_hand, played_cards): def list2dict(lst): d = {} for val, suit in lst: if suit in d: d[suit].append(val) else: d[suit] = [val] return d def play_card(card): cards_in_hand.remove(card) played_cards.append(card) hand = list2dict(cards_in_hand) if not played_cards: if 7 in hand['hearts']: play_card([7, 'hearts']) return (cards_in_hand, played_cards) table = list2dict(played_cards) playable_cards = {} for suit in hand: if 7 in hand[suit]: playable_cards[(7, suit)] = -1 if suit not in table: continue visible = set(table[suit] + hand[suit]) opp_hand = set(range(1,14)) - visible highcard = max(table[suit]) + 1 if highcard in hand[suit]: if highcard+1 in opp_hand: playable_cards[(highcard, suit)] = 1 else: playable_cards[(highcard, suit)] = 2 lowcard = min(table[suit]) - 1 if lowcard in hand[suit]: if lowcard - 1 in opp_hand: playable_cards[(lowcard, suit)] = 0 else: playable_cards[(lowcard, suit)] = 1 if not playable_cards: return (cards_in_hand, played_cards) best_card = list(max(playable_cards, key=playable_cards.get)) #print(hand, "\n", table, "\n", best_card) play_card(best_card) return (cards_in_hand, played_cards) ``` By the way, the controller seemed to have several issues, including in score calculation and comparison. I made some changes to [the controller here, please take a look](https://gist.github.com/digital-carver/3c0e4e15d5137c5a8b6928396ca3fc0c/revisions) and update your version if this seems right. Two things I *haven't* fixed in the controller: * why is the loop condition `(win2 <= 50) and (win1 <= 100)` ? This should probably be symmetrical, it should exit the loop whenever *either* of the players has 100 consecutive wins. * trying some runs of the controller locally, with the same function for both players, Player 2 seems to win most of the time - it can't be inherent to the game since the initial 7H requirement would smooth that out (as @Veskah mentioned in the comments), so, yet undetected controller bugs? Or my player code somehow maintaining state and having a bias this way? Per-game, it's not like Player 2 dominates heavily (from the results output txt), but somehow the overall score per controller run ends up favouring player 2 much more than random (Player 1's total scores are often more than 2x that of Player 2). [Answer] **SearchBot** ``` import random suits = ["clubs", "diamonds", "hearts", "spades"] suit_mul = 14 hearts = suit_mul * suits.index("hearts") def evaluate(hand): return sum(min(c % suit_mul, 10) for c in hand) def rollout(hand0, hand1, runs): sign = -1 counts = [[0.] * 8 for _ in range(2)] def counts_index(card): return 2 * (card // suit_mul) + ((card % suit_mul) > 7) for card in hand0: counts[0][counts_index(card)] += 1 for card in hand1: counts[1][counts_index(card)] += 1 while True: if not hand1: return sign * evaluate(hand0) can_play = [] for i, run in enumerate(runs): if run[0] == 8 or run[1] == 6: if run[1] != 6: run[0] = 7 if run[0] != 8: run[1] = 7 suit = suit_mul * i rank = run[0] - 1 next_low = suit + rank if next_low in hand0: if next_low - 1 in hand0: runs[i][0] -= 1 hand0.remove(next_low) counts[0][counts_index(next_low)] -= 1 can_play = [] break can_play.append((next_low, 0, -1)) rank = run[1] + 1 next_high = suit + rank if next_high in hand0: if next_high + 1 in hand0: runs[i][1] += 1 hand0.remove(next_high) counts[0][counts_index(next_high)] -= 1 can_play = [] break can_play.append((next_high, 1, 1)) if can_play: weights = [(a - 1) / (a + b - 1) if a + b - 1 > 0 else 0 for a, b in zip(*counts)] weighted = [(0 if t[0] % suit_mul == 7 else weights[counts_index(t[0])], t) for t in can_play] weight = sum(t[0] for t in weighted) total = random.uniform(0, weight) for (w, (card, index, direction)) in weighted: total -= w if total <= 0: break hand0.remove(card) counts[0][counts_index(card)] -= 1 runs[card // suit_mul][index] += direction hand0, hand1 = hand1, hand0 counts[0], counts[1] = counts[1], counts[0] sign *= -1 def select_move(hand0, hand1, runs, n=40): if hearts + 7 in hand0: return hearts + 7 if hearts + 7 in hand1: return can_play = [] for i, run in enumerate(runs): suit = suit_mul * i rank = run[0] - 1 next_low = suit + rank if next_low in hand0: if next_low - 1 in hand0: return next_low can_play.append((next_low, 0, -1)) rank = run[1] + 1 next_high = suit + rank if next_high in hand0: if next_high + 1 in hand0: return next_high can_play.append((next_high, 1, 1)) if not can_play: return if len(can_play) == 1: return can_play[0][0] scores = [0 for _ in can_play] for i, (card, index, sign) in enumerate(can_play): hand0_copy = set(hand0) runs_copy = [list(r) for r in runs] hand0_copy.remove(card) runs_copy[card // suit_mul][index] += sign for j in range(n): scores[i] -= rollout(set(hand1), set(hand0_copy), [list(r) for r in runs_copy]) return can_play[scores.index(max(scores))][0] def search(cards_in_hand, played_cards): def play_card(c): if c is None: return suit = suits[c // suit_mul] rank = c % suit_mul for i, card in enumerate(cards_in_hand): if card[0] == rank and card[1] == suit: del cards_in_hand[i] played_cards.append([rank, suit]) return assert(False) hand = set(suit_mul * suits.index(s) + v for v, s in cards_in_hand) played = set(suit_mul * suits.index(s) + v for v, s in played_cards) opponent_hand = (suit_mul * s + v for v in range(1, 14) for s in range(4)) opponent_hand = set(c for c in opponent_hand if c not in hand and c not in played) runs = [[8, 6] for _ in range(4)] for i, run in enumerate(runs): suit = suit_mul * i while suit + run[0] - 1 in played: run[0] -= 1 while suit + run[1] + 1 in played: run[1] += 1 card = select_move(hand, opponent_hand, runs) play_card(card) return cards_in_hand, played_cards ``` [Answer] This is in python 3, but I'm pretty sure it'd work in python 2 as well. It effectively works linearly through the best (as per my limited understanding of the game) possible options at each step - highest scoring card that can match those already played, a new seven, and finally lower scoring cards, finishing by returning `None` if none of the previous options were possible. ``` def computer_play(computer_cards, dealt_cards): #look at dealt_cards and sort computer_cards by suit dealt_hearts = [] dealt_spades = [] dealt_clubs = [] dealt_diamonds = [] for i in dealt_cards: if i[1] == 'hearts': dealt_hearts.append(i[0]) elif i[1] == 'spades': dealt_spades.append(i[0]) elif i[1] == 'clubs': dealt_clubs.append(i[0]) else: dealt_diamonds.append(i[0]) #look at each suit and the highest card that can be played in each max_card_hearts = max(dealt_hearts, default=0) + 1 max_card_spades = max(dealt_spades, default=0) + 1 max_card_clubs = max(dealt_clubs, default=0) + 1 max_card_diamonds = max(dealt_diamonds, default=0) + 1 #play highest overall card if ['hearts', max_card_hearts] in computer_cards: return [max_card_hearts, 'hearts'] elif ['spades', max_card_spades] in computer_cards: return [max_card_spades, 'spades'] elif ['clubs', max_card_clubs] in computer_cards: return [max_card_clubs, 'clubs'] elif ['diamonds', max_card_diamonds] in computer_cards: return [max_card_diamonds, 'diamonds'] else: #if no cards that match suits out, check for sevens suits = {'hearts':max_card_hearts, 'clubs':max_card_clubs, 'spades':max_card_spades, 'diamonds':max_card_diamonds} for i in suits.keys(): if [7, i] in computer_cards: return [7, i] #if no sevens, check for lowest card that can be played for i in suits: if [i, suits[i]-2] in computer_cards: return [i, suits[i]-2] #if nothing can be played, pass return None ``` I'll probably make more updates to it as I debug. The comments hopefully make it fairly clear what's going on. ]
[Question] [ Your challenge is to translate a [Cubically](//git.io/Cubically) cube-dump to the format specified in [this challenge](https://codegolf.stackexchange.com/q/10768/61563). ## Input The input will represent a Rubik's Cube, formatted how Cubically prints its memory cube at the end of every program. This is a solved cube: ``` 000 000 000 111222333444 111222333444 111222333444 555 555 555 ``` This is a cube scrambled with `L2D2L2D2B2R2F2L2D2U2F2UF2U'R2UB2U'L2UB2U'LU'L2U'D'B2U'RBUBF'D'` ([Singmaster's notation](https://proofwiki.org/wiki/Definition:Singmaster_Notation)): ``` 201 501 331 132505224540 512324533442 404513210411 350 254 003 ``` ## Output **If you already understand this format, hit page down a few times to skip lots of explanation.** The output will represent a Rubik's Cube, formatted how solutions to [this challenge](https://codegolf.stackexchange.com/q/10768/61563) take input. > > The first 12 values are the edge cubies, and the next eight are the corners. The faces are U(p), D(own), R(ight), L(eft), F(ront), and B(ack). First the cubie that's in the UF position is given, by the color (in UFRDBL notation) that's on top first, and then the other color next, and so on. > > > This format is a bit confusing, so here's a way to visualize it. This is the solved cube: [![solved visualization](https://i.stack.imgur.com/TeKfU.png)](https://i.stack.imgur.com/TeKfU.png) That renders the output `UF UR UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR`. If we were to swap, for example, the red-white edge and the red-blue edge, the visualization would look like this (with no changes to the hidden faces): [![swapped visualization](https://i.stack.imgur.com/pdndD.png)](https://i.stack.imgur.com/pdndD.png) That renders the output `UR UF UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR` (which, btw, is an impossible cube state). Note that the order of the letters in cubies matter: ``` Above: UR UF UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR Below: RU FU UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR ``` [![swapped reversed visualization](https://i.stack.imgur.com/mQF50.png)](https://i.stack.imgur.com/mQF50.png) The cube scrambled with `L2D2L2D2B2R2F2L2D2U2F2UF2U'R2UB2U'L2UB2U'LU'L2U'D'B2U'RBUBF'D'` creates this cube (only the top, front, and right faces are shown): [![scrambled visualization](https://i.stack.imgur.com/X8S81.png)](https://i.stack.imgur.com/X8S81.png) ``` Solved: UF UR UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR Scrambled: RU LF UB DR DL BL UL FU BD RF BR FD LDF LBD FUL RFD UFR RDB UBL RBU ``` As you can see in the comparison above and in the visualizations, the blue-red `RU` edge of the mixed cube is in the place of the red-white `UF` edge of the solved cube. The green-white `LF` edge is in the place of the red-blue `UR` edge, etc. ## Rules * I/O will be done via any [allowed means](https://codegolf.meta.stackexchange.com/q/2447/61563). * The output cubies must be delimited by any whitespace character you choose. * The input will be formatted exactly how it is shown in the challenge, including whitespace. * Your program may do whatever you like if the inputted cube is unsolvable. ## Test cases * [Input](https://pastebin.com/raw/XqvgL266) -> output: `RU LF UB DR DL BL UL FU BD RF BR FD LDF LBD FUL RFD UFR RDB UBL RBU` * [Input](https://pastebin.com/raw/JQ73Gbep) -> output: `UF UR UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR` * [Input](https://pastebin.com/raw/CBZ0jyn2) -> output: `FU DL LB BU RU BR RF DR BD DF LF LU FUL FLD URB BLU RUF DBR BDL RFD` Here's a [reference program](https://tio.run/##xZRNb6MwEIbv/hWjVFWB0I0xeC9098A2SJU4scplqx5SIFlLFFZJumqzym9PbfMRnBrJ2h7KxWYYP@/MwEt2vc6y4/GCVVn5nBdws93lrP7y@ztSQiV7FDHEqh042fNj4cKPRTT/efdrHiJ0kRcrVhUyZL24r@7eBpF0b1kvttMl9hsbpmBZr7Ya2NsPCP2tWQ6bYpmL41Z8l8zBYZWN/iHgl1BfLTMuXnI5V2qUxc4FFsrnq3oDlngE3wCHMgluToXKwHRqQ0PrT7AmnSm5jCf2aeJaF7vM4rWE6uG2hgbR3QxBbewcJ2eFXdlIm2JzSKcC13CFr05aqvoBfaRfMUJ@wgvlMPkJ2uzOS/xQf32P8oV9Rpuf91rpf/d7aCz2tGSVJbzQffmdLkf5Ta6A87unZVnWmfUVnFOOst2yfVGvuMbOblV6ewmrC2kZnTlQ5OtiC86sCfzZ8DMra3KZXWYwcWGySOI0up3ct18ucT374TxMXCzCdsiBM1jERiTPJe9JvkpKjUhYV1OgkiLDmvB7kqeSEgMS1ddEmvG1pNvYiDQyJ4WUGpGIfk4KKTKsSTsnhWQyJzLWnRRoSXFqSNLWJAU6kklNgZ7kK6QoNSQRfU2n7qKkd2JWb6pio/fimBuJ3o0j1sIDk6aGGqMwojfdQCONjDWwHkb0dhxoRInxrEa8PTLCgUYSG2nQsVlppUnz9noLm2uMwEYsOdCIE0ONURjW/0AGGklkrEH0MKwf4UCDu@9wPHIVgj2hRpvF9z3k@YRiSkhAA4yoR3y@8/0gICjAAeVPPRx4TTbFYiE0EAvG/hs) using parts of Cubically's [rubiks.c](https://github.com/aaronryank/Cubically/blob/master/src/rubiks.c). ## Winner As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~87~~ ~~73~~ ~~62~~ ~~61~~ 60 bytes ``` fØDO“¬ụƘȷ$OkḌ×c¿?oƥ¤_Ọ6;ȤṚUȷ!8⁺⁻:ĠŻ’Œ?¤ịs24Ṗs"2,3ị“LFRBDU”ẎK ``` [Try it online!](https://tio.run/##y0rNyan8/z/t8AwX/0cNcw6tebh76bEZJ7ar@Gc/3NFzeHryof32@ceWHloS/3B3j5n1iSUPd84KPbFd0eJR465Hjbutjiw4uvtRw8yjk@wPLXm4u7vYyOThzmnFSkY6xkAe0EAftyAnl9BHDXMf7urz/v//v4KCgpGBIReQMoVQxsaGXIbGRqYGpkZGJqYmBlymhkbGQJaxsYmJEZeJgYkpUNbQwMQQotrUAEQZmZqAKAMDYwA "Jelly – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 115 bytes ``` ->s{"29&,<&$?&*6&`S&hV&nY&fP&GH&ED&KJ&MB&3:;&%=>&#@5&178&aUT&_RQ&mOZ&oXW".bytes{|i|$><<" ULFRBD"[s[i-32].ord%9]}} ``` [Try it online!](https://tio.run/##fY9JTwJREITv71dMRuiDEdKrisJoCC5xiYriRiYqUSIHxTBwIMBvH9@bORETT193qlNdNZkN5vmwldeSbBFzA7aaUDmAzW14vYXPe/h@guE1nJzCUQfOz@CyDbK3D9VWAhuHBrSzC2@9O3jp3sDX1TOMHx/i@mA@/cgWy9GykjSbcRRFvYvjbrsT97P@qCac1seT92ojXa3yYT/IjOQ8rIQIORI2NGY1RWfE4icRVXaKal4lVCqvDQPYNABR4tS5n9k0c640R0S3DiJiZgl@@s8SEpmt4485cVAUiwPlkI/8D29kKs7LFpIzKblQABnF1yrripSuxSuVInn@Cw "Ruby – Try It Online") A function taking the input as an argument and printing to stdout. Iterate through the long string. Each byte(minus 32) represents the index of the next character to be transcribed. To transcribe, take the ascii code of the character in the input (`012345` or newline) and find the value modulo 9. This gives a number in the range 3 to 8, which is treated as an index in the string `" ULFRBD"` to transcribe. Thus the ascii code for `0` is 48, 48%9 is 3, which is the index of `U` in the string above. The `&` signs in the long string point to the first newline in the input (character `#10`.) This is taken modulo 9 to give the value 1, which is looked up in `" ULFRBD"` and transcribed as a space. The indices in the input are looked up as follows (extra spaces added for clarity) ``` #$% *+, 123 567 89: ;<= >?@ BCD EFG HIJ KLM OPQ RST UVW XYZ _`a fgh mno ``` [Answer] # [Clean](https://clean.cs.ru.nl), ~~150~~ ~~145~~ 143 bytes Contains *many* non-printable characters. ``` import StdEnv $d=map(\c=['ULFRBD ']!!(digitToInt(['96':d]!!(toInt c))))[' ! B5J8P;H2)*\'&-,/$  "C76A43O1<Q:9'] ``` [Try it online!](https://tio.run/##fVHLTsJAFM1dqAkxbtT41kGJA0biPFHQLlQ0YkhE0VXLorRAmrRTgoOJP2@dlkqMC2dz7mvOuWfGCweuSqLYn4YDFLmBSoJoHE806mr/Tn0USr4VueOy41k2fmvfv9w0Ee4Vi2U/GAX6NW4pXbZxvYYbflrVaQF5FXNsvLYDK/uwWITlTbiR8HgBnUt4YFA5AQcfQ/UUzkqwvrsHSwcIFg43YHVrG27Pa3AtODzRK3hu1HEv6Wp3ogtHyJv2BxRZyMYIIUaoowzKHDk3SDmTRDImpCCOkpRxE3IuBHOUIEKaPiWC5jckyZBJkSEhHPdyGfYjQwjJm7@QUsoY4ymx@D9LF5TyL85l@FyGsqwpyGxIsGxjauQMoRTcUWZEpm4YFWb/1BVhhBuz@TtwntPPZAVP3VioNPOTfHnD0B29J9VWO2l@KjcKvFlivrkd9LOwE7p6GE@ipNr/Bg "Clean – Try It Online") Defines the function `$`, taking `[Char]`, and giving `[Char]`. This works by mapping each character position in the input to another character position in the output (using the character codes in a string), taking advantage of the swapped 'cubies' in the output being paralleled by swapped colors in the corresponding position in the input. Output is separated by spaces. ]
[Question] [ Your task is to write a program or function which, given two nonzero integers `x` and `y`, returns a truthy value if the image at coordinates `x` east and `y` north of xkcd's [click and drag comic](https://xkcd.com/1110/) is mostly white and a falsey value otherwise. # Specifications * The image should be retrieved from imgs.xkcd.com/clickdrag/[y]n[x]e.png, where `[y]` and `[x]` are replaced with the *absolute values* of the input `y` and `x` values. * If `x` is negative, `e` should be changed to a `w`. If `y` is negative, `n` should be changed to a `s`. * If a 404 error is returned, assume the image is mostly white (output truthy) if `y` is positive and mostly black otherwise. This is because (as far as I can tell) xkcd stores neither completely white regions of the sky nor completely black regions of the ground, leading to less data in their servers and these 404s you must handle. This error handling is not intended to deal with the images not being available. * "white" is defined as rgb #FFFFFF. You may assume that the images are only white(#FFFFFF) and black(#000000), without gray or other colors. "Mostly white" is defined as at least 2097153 pixels of the image are white (because the png the program should retrieve from img.xkcd.com is always 2048x2048 pixels). * The program may have any behavior when dealing with pixels that are not exactly #FFFFFF nor #000000 but must produce the same output as expected for the test cases. # Example The image at `x=2`, `y=9` should be retrieved from `imgs.xkcd.com/clickdrag/9n2e.png` and appears as follows (formatted as quote to show border): > > [![clickdrag/9n2e](https://i.stack.imgur.com/1AtPPm.png)](https://i.stack.imgur.com/1AtPPm.png) > > > It is mostly white, so the program should return a truthy value. # Input / Output Input should be two integers or a list of two integers representing `x` and `y`. Output should be a [truthy or falsy](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey/2194#2194) value corresponding to if the image is mostly white. Input and output should be through any [standard I/O method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). # Test Cases ### Truthy (as (x,y)) ``` 2,9 7,-17 9, 5 3, 2 -5, 1 1, 3 ``` ### Falsy (as (x,y)) ``` 3, 1 3, -1 7, -16 2, 1 5, 1 17, -1 ``` [Answer] # MATLAB, 144 bytes ``` function r=f(x,y);n=@num2str;r=1;try;r=nnz(imread(['http://imgs.xkcd.com/clickdrag/',n(y),'n'+5*(y<0),n(x),'e'+18*(x<0),'.png'],'png'))>2^21;end ``` This function takes two arguments `x,y`. `imread` reads the image at the given path. In this case we get a black and white image where each pixel (= entry in a matrix) contains the number `0` or `255`. To count the white (`255`) pixels, `nnz` is used (which conts the number of nonzero entries). To account for possible eerrors, we wrap this call in `try/end` and predefine the return value to `1` (nonzero numbers are truthy in MATLAB). The change of e.g. `n` and `s` depending on the sign of `y` is done via character arithmetic. [Answer] ## bash, ~~172~~ ~~164~~ 158 bytes ``` t=tr\ \\-0-9 curl imgs.xkcd.com/clickdrag/${2#-}$($t sn<<<${2::1})${1#-}$($t we<<<${1::1}).png|convert - a.pgm echo $[$??$2>0:`grep -ao ÿ a.pgm|wc -l`>2**21] ``` This won't work on TIO due to the requirement for internet access. There's an `\xFF` byte in the code, which is likely to be mangled due to encodings, so here's a script you can use to run all the test cases locally: ``` #!/bin/bash xxd -r >clickdrag.sh <<'end' 00000000: 743d 7472 5c20 5c5c 2d30 2d39 0a63 7572 t=tr\ \\-0-9.cur 00000010: 6c20 696d 6773 2e78 6b63 642e 636f 6d2f l imgs.xkcd.com/ 00000020: 636c 6963 6b64 7261 672f 247b 3223 2d7d clickdrag/${2#-} 00000030: 2428 2474 2073 6e3c 3c3c 247b 323a 3a31 $($t sn<<<${2::1 00000040: 7d29 247b 3123 2d7d 2428 2474 2077 653c })${1#-}$($t we< 00000050: 3c3c 247b 313a 3a31 7d29 2e70 6e67 7c63 <<${1::1}).png|c 00000060: 6f6e 7665 7274 202d 2061 2e70 676d 0a65 onvert - a.pgm.e 00000070: 6368 6f20 245b 243f 3f24 323e 303a 6067 cho $[$??$2>0:`g 00000080: 7265 7020 2d61 6f20 ff20 612e 7067 6d7c rep -ao . a.pgm| 00000090: 7763 202d 6c60 3e32 2a2a 3231 5d wc -l`>2**21] end for x in '2 9' '7 -17' '9 5' '3 2' '-5 1' '1 3' '3 1' '3 -1' '7 -16' '2 1' '5 1' '17 -1' do bash clickdrag.sh $x 2>/dev/null done rm clickdrag.sh ``` ### Explanation First, an explanation of how the URL is built: ``` imgs.xkcd.com/clickdrag/${2#-}$($t sn<<<${2::1})${1#-}$($t we<<<${1::1}).png ``` Here, `${2#-}` removes a leading negative sign from the second command line argument, and `${1#-}` does the same for the first. The `n`/`s` and `e`/`w` are generated, respectively, with the snippets (after expanding `$t`) ``` tr '\-0-9' sn<<<${2::1} tr '\-0-9' we<<<${1::1} ``` The `${_::1}`s take the first character of the appropriate command line argument (which will be `-` if it is negative and a digit otherwise). The `tr` command then turns `-` into `s`/`w` and digits into `n`/`e`. The URL is then passed to `curl`, which retrieves the image: ``` curl URL|convert - a.pgm ``` The `convert` command from ImageMagick turns the difficult PNG format into the much easier PGM, which uses one byte per pixel. It writes to the file `a.pgm`. If the URL 404s, the `convert` command will fail to find an image and exit with a nonzero status code. Thus, we can effectively use `$?` (exit code of the last command) as an indicator of whether the URL returned a 404. This comprises the remainder of the code: ``` echo $[$?? ``` If the exit code was nonzero (link was a 404), we simply check whether the y coordinate is positive: ``` $2>0 ``` Otherwise, we count the number of `\xFF` bytes (white) in the image and test to see whether it's greater than 221: ``` :`grep -ao ÿ a.pgm|wc -l`>2**21] ``` [Answer] ## Javascript (ES6), 317 bytes ``` f=(x,y)=>{l=console.log;c=document.createElement`canvas`.getContext`2d`;i=new Image;i.onload=_=>{c.drawImage(i,0,0,1,1);l(!!c.getImageData(0,0,1,1).data[0])};i.onerror=e=>l(y>=0);i.crossOrigin='anonymous';i.src=`https://crossorigin.me/https://imgs.xkcd.com/clickdrag/${(y<0?y*-1+'s':y+'n')+(x<0?x*-1+'w':x+'e')}.png`} ``` This works by shrinking the image to an 1\*1 pixel, and checking whether the red channel of this pixel is `0` or not (if white it would be `255`). Note that it has a *somehow* big margin of error for 50 white/50 black cases : on my computer, if there are less than between 50% - 1024px and 50%, it will report as gray, and hence white. But, as long as there is no proof that there is an image in the list with less than 1024 px of difference between black and white, I guess it's still valid. Ungolfed : ``` f=(x,y)=>{ l=console.log; // output in the console since the function is async c=document.createElement`canvas`.getContext`2d`; i=new Image; i.onload=_=>{ c.drawImage(i,0,0,1,1); // draw resized at 1px*1px // is the first red value of the pixel '0' ? l(!!c.getImageData(0,0,1,1).data[0]) }; // handle 404 i.onerror= e=> l(y>=0); // 56 bytes only for cross-origins... i.crossOrigin="anonymous"; i.src= `https://crossorigin.me/https://imgs.xkcd.com/clickdrag/${ // there could probably be some out-golfing to do here (y<0?y*-1+'s':y+'n') + (x<0?x*-1+'w':x+'e') }.png`; } ``` Here is a 319 bytes Promise based live version, for better logging of the outputs, since all this is async : ``` f=(x,y)=>new Promise(l=>{c=document.createElement`canvas`.getContext`2d`;i=new Image;i.onload=_=>{c.drawImage(i,0,0,1,1);l(!!c.getImageData(0,0,1,1).data[0])};i.onerror=e=>l(y>=0);i.crossOrigin='anonymous';i.src=`https://crossorigin.me/https://imgs.xkcd.com/clickdrag/${(y<0?y*-1+'s':y+'n')+(x<0?x*-1+'w':x+'e')}.png`}) var pos = [ // truthy {x:2,y:9}, {x:7,y:-17}, {x:9,y:5}, {x:3,y:2}, {x:-5,y:1}, {x:1,y:3}, // falsy {x:3,y:1}, {x:3,y:-1}, {x:7,y:-16}, {x:2,y:1}, {x:5,y:1}, {x:17,y:-1} ]; function test(i){ let p = pos[i]; let prom = f(p.x, p.y) prom.then(r=>{ console.log(p.x, p.y, ': ', r); if(i < pos.length) test(++i); }); } test(0); ``` And if ever someone find an image with less than 1024px of difference between whites and blacks, here is a 378 bytes version which handles it : ``` f=(x,y)=>{l=console.log;o=document.createElement`canvas`;w=o.width=o.height=2048;i=new Image;i.onload=_=>{c=o.getContext`2d`;c.drawImage(i,0,0);l(c.getImageData(0,0,w,w).data.reduce((a,v,i)=>(i%4&&v?++a:a),0)/4>w*w/2)};i.onerror=e=>l(y>=0);i.crossOrigin='anonymous';i.src=`https://crossorigin.me/https://imgs.xkcd.com/clickdrag/${(y<0?y*-1+'s':y+'n')+(x<0?x*-1+'w':x+'e')}.png`} ``` ]
[Question] [ Not entirely sure if this one or a similar challenge has already been posted, but here it goes anyway. Write a program that takes a `string` as input and writes its trucated/summarized `output` form such that a specific `sep` (separator) is placed in the middle, removing the necessary characters of the original `string` so that the length of `output` equals a given `width`. # Rules * Input is a `string`, a `width` and a `sep` (separator); * `if len(string) <= width: output = string`, meaning that the output is the string itself unchanged; * `if width <= len(sep): output = sep`, meaning that the output is the separator only; * `len(output)` must be equal to `width`, with the exception of the previous case; * The excess character in case of uneven number of remaining characters for each half of the string can be placed on the left or right halve; * Standard code-golf challenge with the smallest program to win. # Examples Format: `"string" [length(string)] --> "output" [length(ouput) / width]` with `sep` equal to `_(...)_` (`_` are whitespaces). ``` "xtlgxbdwytxcjacu" [16] --> "x (...) " [8 / 8] "upjptz" [6] --> " (...) " [7 / 3] "h" [1] --> "h" [1 / 1] "qsshkvmawcmf" [12] --> " (...) " [7 / 7] "tvdknroxszhufgck" [16] --> "tv (...) k" [10 / 10] "ag" [2] --> "ag" [2 / 5] "vbgdegtgshnzjrudca" [18] --> "vbgd (...) udca" [15 / 15] "bscwimjjhmgvcwp" [15] --> "bscwimjjhmgvcwp" [15 / 18] "xwhgbaenornbzwirlp" [18] --> "xwhgbaenornbzwirlp" [18 / 18] "tbqyrekkzyizc" [13] --> "t (...) " [8 / 8] "oowdwbeezeh" [11] --> "o (...) h" [9 / 9] "avlzfzpjazhjc" [13] --> "avlzfzpjazhjc" [13 / 15] "dngxmebwenfrbidonses" [20] --> "dngxme (...) donses" [19 / 19] "bqfxyffdemjghipk" [16] --> "bqfxyffdemjghipk" [16 / 16] "sfwnlkreghzff" [13] --> " (...) " [7 / 5] "dznlsyaojtferxh" [15] --> "dznlsyaojtferxh" [15 / 17] "zwkhjdafkzjdgc" [14] --> "zwk (...) dgc" [13 / 13] "kpzochngmwoulne" [15] --> "kpz (...) lne" [13 / 13] "vluqvhpcxg" [10] --> "vluqvhpcxg" [10 / 10] "wuc" [3] --> "wuc" [3 / 8] ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~93~~ ~~76~~ 72 bytes ``` s,w,p=input() l=len(s) if w<l:w=max(w-len(p),0);s[-~w/2:l-w/2]=p print s ``` [Try it online!](https://tio.run/nexus/python2#Lcs9CsMwDAXg3acwmmxQ3J@taXySkKGlSTE4rolSlKlXd2Xw8AnxnlQIGbMPKX93Y1X0cU6GrAqL5iH27NfHYbirabZ4tncaux@frn3sZE4@q7yFtGsqZYQXICTxFodYxSyegtte@0VsLQ@i/n1aR@2OYMLLDUEb55zV8Ac "Python 2 – TIO Nexus") Input and output are a list of characters [Answer] ## JavaScript (ES6), 78 bytes ``` (w,s,e,l=s.length,m=e.length)=>l>w?m<w?s.slice(0,w-m>>1)+e+s.slice(m-w>>1):e:s ``` I was pleasantly surprised to discover that `w-m>>w` and `m-w>>1` give the desired result. [Answer] # Python 2, 76 bytes ``` def f(s,p,w):t=len(s);q=len(p)-w;print[s,[p,s[:~q/2]+p+s[t+q/2:]][q<0]][t>w] ``` Tests are at **[TryItOnline!](https://tio.run/nexus/python2#dVLLctwgEDx7v4LiJNWSjZ2UnUSO8yMqlUu8hSSEAAmJQ359jSjv3nyBmZ6herqHK2Uc8MIhg0JZ@beB6cKVr3MOTPktvBrbaV87VBvk6ur//P1HczZnV/tzCqumqee/j@n0/0Jz9cx5B95AXcDND2LDNOx@I6olC0S/S1TAxSjjI0Q/j0RC9HTcs3OyX8c2kJFD9OuA/Ep7bafNRblwQfrU@XjgrYDo@QhWLCgTXjipo7ILJW1qyRXsSOhGpeQoVhJMgjPzFqTALdOT1TiGzg73isfzblnfx72L5HPOaQo0YMYiS0P@yczrEHk0qo1SkRsX1WIbGQ5Mc4s7OmnHXKrlB3jm2845ZaMSsjOHhJcDdzzoobdMyMj5pxoa9eD2dlKeM7sdvmQXYuiloi3vo6LiIM229SZORGoxhmkZNLvB67DMqzRkEzezwpLlNCeTdgLfi8vlUr7DE58scAgE0GmQN1adHvKWAey0WXwFESjSlwAmNZXl6YHfk3sjvH6pHUGQmQD8AA)** *Note:* Places the extra character for odd splits on the right hand side (question states that either is fine, although the examples show left only). [Answer] # JavaScript ES6, 103 99 bytes ``` (a,b,c,d=a.length,e=c.length,f=(b>e?b:e)-e,g=a.split(""),h=g.splice(-~f/2,d-f,c))=>b<d?g.join(""):a ``` ``` f=(a,b,c,d=a.length,e=c.length,f=(b>e?b:e)-e,g=a.split(""),h=g.splice(-~f/2,d-f,c))=>b<d?g.join(""):a; console.log(f("dngxmebwenfrbidonses", 19, " (...) ")); ``` [Answer] # Mathematica, 90 bytes ``` If[(l=Length)[i=#2]<=#,#2,If[#<=(s=l@#3),#3,Join[(t=i~Take~Floor[#/2]&)[#-s],#3,t[s-#]]]]& ``` Unnamed function taking an integer (the width) as its first argument and two lists of characters (the string and the separator) as its second/third arguments, and returning a list of characters. ]
[Question] [ Are you feeling jealousy towards Mathematica, Matlab et al. for their intricate plotting capabilities? If you answered yes, this challenge is for you! # Challenge Given, via parameters or standard input, a list of numbers `list` and a positive integer `h` for the height of the plot, write a program/function/snippet that prints a character array of `length(list)` columns and `h` rows, where each column contains exactly one special non-whitespace character, e.g. `#` and `h-1` spaces. For the *nth* column the position of the special character corresponds to the value of the *nth* element in the list. Lower rows correspond to lower values, so if `list[a]≥list[b]`, then in column `a` the special character must be at least as high than in column `b`. The scaling from the value to the y-position of the special character must *essentially* be an affine mapping (`x ↦ ax+b`) plus any necessary rounding so for example integer division is allowed but clipping is not. The scaling must be done so that the full extent of the plot is used, i.e. the first and last row contain at least one special character. The numbers can be of any numeral type that is at least 8 bits wide. Labels or axes aren't needed. Built-in plotting functions are allowed if the output conforms to the required format. The standard loopholes are disallowed. ## Example ### Input: ``` list = [0.0,0.325,0.614,0.837,0.969,0.997,0.916,0.736,0.476,0.165,-0.165,-0.476,-0.736,-0.916,-0.997,-0.969,-0.837,-0.614,-0.325,0.0] h = 8 ``` ### One possible output: ``` ### ## # # # # # # # # # # ## ### ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] # Mathematica, 91 bytes ``` StringRiffle[(Join[" "~Table~#,{"#"},Table[" ",a-#]]&/@⌊(a=#2-1)Rescale@#⌋)," ",""]& ``` Anonymous function. The Unicode characters are respectively U+230A LEFT FLOOR for `\[LeftFloor]`, U+230B RIGHT FLOOR for `\[RightFloor]`, and U+F3C7 (private use) for `\[Transpose]`. Output for the test case: ``` # ## ## # # # # # # # # # # ##### ``` [Answer] # Python 2, 118 bytes Saving 2 bytes thanks to Shebang ``` def f(n,L): for i in range(n):print''.join(' #'[i==j]for j in[n-1-int(~-n*(x-min(L))/(max(L)-min(L))+0.5)for x in L]) ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 26 bytes ``` tX<-tX>/iq*Yo"@Z"35h]Xhc!P ``` [Try it online!](http://matl.tryitonline.net/#code=dFg8LXRYPi9pcSpZbyJAWiIzNWhdWGhjIVA&input=WzAuMCwwLjMyNSwwLjYxNCwwLjgzNywwLjk2OSwwLjk5NywwLjkxNiwwLjczNiwwLjQ3NiwwLjE2NSwtMC4xNjUsLTAuNDc2LC0wLjczNiwtMC45MTYsLTAuOTk3LC0wLjk2OSwtMC44MzcsLTAuNjE0LC0wLjMyNSwwLjBdCjg) Explanation ``` tX<- % Input array of values implicitly. Subtract minimum tX>/ % Divide by maximum iq % Input height and subtract 1 * % Multiply Yo % Round to nearest integer " % For each number in that array @ % Push current number Z" % String with that number of spaces 35h % Append a '#' character to that string ] % End Xh % Collect all strings into a cell array c % Convert into 2D char array, right-padding with spaces !P % Transpose and flip vertically. Implicitly display ``` [Answer] ## JavaScript (ES6), 125 bytes ``` list=[0.0,0.325,0.614,0.837,0.969,0.997,0.916,0.736,0.476,0.165,-0.165,-0.476,-0.736,-0.916,-0.997,-0.969,-0.837,-0.614,-0.325,0.0]; h=8; f= (a,n,m=Math,u=m.max(...a),h=u-m.min(...a))=>[...Array(n--)].map((_,i)=>a.map(v=>m.round(i-(u-v)*n/h)?` `:`#`).join``).join` ` ; console.log(f(list,h)); ``` ]
[Question] [ Donald Knuth was born in 1938, on the 20th day of Capricorn. The first day of Capricorn is the 22nd December. Donald Knuth was born on the 10th of January (1938). --- **The challenge** Write a program or function which takes three **inputs** about a person (any other specified order is fine): * Their (calendar) year of birth (an integer) * Their sign of the zodiac (a string) - may be whichever you choose from the following, so long as it is consistent: + all lower case except the first character; + all lower case; or + all upper case. * The (1-based) day of the zodiac period on which they were born (an integer) ...and provides two **outputs** (the other order is fine if specified): * The day of the month on which they were born (an integer) * Their month of birth (an integer) **More details** If your answer were a function, `F`, then for Donald Knuth we would run `F(1938, 'Capricorn', 20)` and receive the output `(10, 1)` For the purposes of this challenge you do *not* need to shift the zodiac due to the shift between the Gregorian calendar and the tropical year, but you do need to account correctly for leap years. February has `29` days rather than `28` on leap years. A year is *usually* a leap year if it is divisible by `4` - the exceptions are when it is divisible by `100` but not `400` (so, `1600` and `2000` were, whereas `1700`, `1800`, and `1900` were not). For reference the names of the signs of the zodiac and their inclusive ranges are: ``` Aries 21 March – 20 April Taurus 21 April – 21 May Gemini 22 May – 21 June Cancer 22 June – 22 July Leo 23 July – 22 August Virgo 23 August – 23 September Libra 24 September – 23 October Scorpio 24 October – 22 November Sagittarius 23 November – 21 December Capricorn 22 December – 20 January Aquarius 21 January – 19 February Pisces 20 February – 20 March ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes is the aim. No loopholes, yada yada; you know the drill. --- **Test cases** ``` Charles Babbage F(1791, 'Capricorn', 5) --> (26, 12) George Boole F(1815, 'Scorpio', 10) --> ( 2, 11) Herman Hollerith F(1860, 'Pisces', 10) --> (29, 2) Vannevar Bush F(1890, 'Pisces', 20) --> (11, 3) Howard H. Aiken F(1900, 'Pisces', 17) --> ( 8, 3) - note 1900 was not a leap year Donald Knuth F(1938, 'Capricorn', 20) --> (10, 1) <Future Famed> F(2000, 'Pisces', 17) --> ( 7, 3) - note 2000 was a leap year ``` [Answer] # Javascript (ES6), ~~121~~ ~~120~~ 119 bytes ``` (y,s,d)=>[(d=new Date(y,m=s[2]=='s'?1:'r.sune0oapti'.search(s[4]||0),23+d-'343322110012'[m])).getDate(),d.getMonth()+1] ``` Format for the sign of the zodiac is either: * all lower case except the first character * all lower case ### Test cases ``` let f = (y,s,d)=>[(d=new Date(y,m=s[2]=='s'?1:'r.sune0oapti'.search(s[4]||0),23+d-'343322110012'[m])).getDate(),d.getMonth()+1] console.log(f(1791, 'Capricorn', 5)); // --> (26, 12) console.log(f(1815, 'Scorpio', 10)); // --> ( 2, 11) console.log(f(1860, 'Pisces', 10)); // --> (29, 2) console.log(f(1890, 'Pisces', 20)); // --> (11, 3) console.log(f(1900, 'Pisces', 17)); // --> ( 8, 3) console.log(f(1938, 'Capricorn', 20)); // --> (10, 1) console.log(f(2000, 'Pisces', 17)); // --> ( 7, 3) ``` [Answer] # TSQL, 147 bytes **Golfed:** ``` DECLARE @ DATETIME='2000',@s char(3)='Pisces',@d INT=17 SELECT @s=CHARINDEX(@s,' PisAriTauGemCanLeoVirLibScoSagCap')/3,@=DATEADD(m,@s*1,@)+18+substring('101122334432',@s+1,1)*1+@d SELECT day(@),month(@) ``` **Ungolfed:** ``` DECLARE @ DATETIME='2000',@s char(3)='Pisces',@d INT=17 SELECT @s=CHARINDEX(@s,' PisAriTauGemCanLeoVirLibScoSagCap')/3, @=DATEADD(m,@s*1,@)+18+substring('101122334432',@s+1,1)*1+@d SELECT day(@),month(@) ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/534807/when-is-their-birthday)** [Answer] ## Python 3 - ~~333~~ ~~309~~ ~~299~~ ~~240~~ 238 bytes ``` from datetime import* def f(y,s,d):y=datetime(y,1,1)+timedelta((([[[21,80,111,142,173,235,267,297,327,356]['rsuneoapti'.index(s[4])],51][s[2]=='s'],204][len(s)<4])+d)%(365+[[[0,1][y%4==0],0][y%100==0],1][y%400==0])-2);return y.day,y.month ``` Saved ~~24~~ 26 bytes thanks to @Jonathan Allan ]
[Question] [ Since this SE community is about golfing, I thought a golf-related challenge would be appropriate. ## Explanation Normally, the objective of golf is to finish a hole (and consequently, the entire round) with the least amount of strokes. This is a simple version of golf: Play until you hole the ball and sum up your score. Finally subtract it from the total par and the resulting number indicates your score: 0 if you played exactly par, positive if you played worse and negative if you played better. But in 1898 a guy named Dr. Frank Barney Gorton Stableford devised a new system of playing which was designed to be more forgiving. This system awards a number of points to a player, based on a relative rating per hole, called the stroke index (SI) which is based on a player rating called handicap. This limits the amount of points a player can lose per hole. Additionally, the handiccp ensures fair competition between players despite skill difference. This format isn't used in professional golf, but can be found almost anywhere in amateur golf. ## The scoring algorithm For anyone unfamiliar with golf, the algorithm for scoring a hole based version is as follows. 1. Beginning with the hardest hole (rating 1) to the easiest one (rating 18), increase the stroke index of that hole by 1 and decrement the handicap. If you exhaust the handicap, stop. If you hit the easiest hole you wrap around to the hardest and continue. (Ex: stroke index for hcp `24` and `[1..18]`: `[2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1]`). 2. For every score on a hole, subtract it from the sum of par and stroke index and add 2 (formula: `(par + stroke index) - achieved score + 2`). These are the stableford points received for that hole. Note that you cannot receive less than 0 points. 3. Sum up all the points. The resulting total is the total number of stableford points. Thus, reaching 36 points is equivalent to playing exactly one's handicap, and more points are better. ## Rules Your task will be to calculate the total number of stableford points of an arbitrary golf round on an arbitrary golf course given a handicap. You will be given a list of difficulty ratings, a list of pars, a list of scores and the handicap to use. You may order these arguments as you wish, but please state how you order them. You may write a function ot program, input can be taken either as command line argument or function argument. Output may either be printed to STDOUT or the return value of a function. You may assume the following about the input: * Every list will contain exactly 18 elements. * The lists are orderd by hole: First element = info for first hole, etc. * The handicap will be an integer between 0 and 54 inclusive. * Pars will be between 3 and 7. * The score is always a positive integer. * The difficulty rating list will always be a permutation of `[1..18]`. This is code golf, so the shortest answer in bytes wins. ## Examples ``` Input: hcp: 0 difficulty: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18] pars: [3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5] score: [3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5] Output: 36 Input: hcp: 15 difficulty: [9,3,1,13,11,17,15,7,5,18,14,10,4,6,12,16,8,2] pars: [4,4,4,3,5,4,3,4,4,4,3,4,4,4,5,3,5,4] score: [5,5,4,5,4,4,4,4,5,7,3,5,5,6,4,6,5,5] Output: 38 Input: hcp: 28 difficulty: [9,3,1,13,11,17,15,7,5,18,14,10,4,6,12,16,8,2] pars: [4,4,4,3,5,4,3,4,4,4,3,4,4,4,5,3,5,4] score: [5,5,5,6,3,7,3,6,5,8,4,6,7,8,4,7,6,5] Outut: 37 Input: hcp: 54 difficulty: [9,3,1,13,11,17,15,7,5,18,14,10,4,6,12,16,8,2] pars: [4,4,4,3,5,4,3,4,4,4,3,4,4,4,5,3,5,4] score: [9,10,9,10,9,10,9,10,9,10,9,10,9,10,9,10,9,10] Output: 3 ``` Happy golfing! [Answer] ## JavaScript (ES6), 72 bytes ``` (h,d,p,s)=>s.map((e,i)=>(e=p[i]+2-e+(h%18>=d[i])+h/18|0)<0?0:r+=e,r=0)|r ``` [Answer] # Pyth, 46 bytes ``` u+G.)S[0+-++@@Q2Hg%hQ18@@Q1H/hQ18@@Q3H2)Ul@Q1Z ``` A program that takes input as a list of the form `[handicap, [difficulties], [pars], [scores]]` and prints the overall score. I am very new to Pyth, so this can probably be golfed further. [Try it online](https://pyth.herokuapp.com/?code=u%2BG.%29S%5B0%2B-%2B%2B%40%40Q2Hg%25hQ18%40%40Q1H%2FhQ18%40%40Q3H2%29Ul%40Q1Z&input=%5B28%2C%5B9%2C3%2C1%2C13%2C11%2C17%2C15%2C7%2C5%2C18%2C14%2C10%2C4%2C6%2C12%2C16%2C8%2C2%5D%2C%5B4%2C4%2C4%2C3%2C5%2C4%2C3%2C4%2C4%2C4%2C3%2C4%2C4%2C4%2C5%2C3%2C5%2C4%5D%2C%5B5%2C5%2C5%2C6%2C3%2C7%2C3%2C6%2C5%2C8%2C4%2C6%2C7%2C8%2C4%2C7%2C6%2C5%5D%5D&debug=0) **How it works** ``` u+G.)S[0+-++@@Q2Hg%hQ18@@Q1H/hQ18@@Q3H2)Ul@Q1Z Program. Input: Q +G.)S[0+-++@@Q2Hg%hQ18@@Q1H/hQ18@@Q3H2) Function. Inputs: G, H @@Q2H Q[2][H] hQ Q[0] 18 18 % Q[0]%18 @@Q1H Q[1][H] g Q[0]%18>=Q[1][H] + Q[2][H]+Q[0]%18>=Q[1][H] hQ Q[0] 18 18 / Q[0]//18 + Q[2][H]+Q[0]%18>=Q[1][H]+Q[0]//18 @@Q3H Q[3][H] - Q[2][H]+Q[0]%18>=Q[1][H]+Q[0]//18-Q[3][H] 2 2 + Q[2][H]+Q[0]%18>=Q[1][H]+Q[0]//18-Q[3][H]+2 0 0 [ ) List [0, above expression] S Sort ascending .) Pop last value, clamping negatives to 0 G G + G + popped value u Ul@Q1Z @Q1 Q[1] l Length U Unary range, yielding [0, len(Q[1])-1] Z 0 u Reduce the function over that, start at 0 ``` [Answer] # Python 3, 71 bytes ``` lambda h,d,p,s:sum(max(0,j+(h%18>=i)+h//18-k+2)for i,j,k in zip(d,p,s)) ``` An anonymous function that takes input via argument of a handicap `h` as an integer, and difficulties `d`, pars `p` and scores `s` as lists, and returns the overall score. **How it works** ``` lambda h,d,p,s Anonymous funtion with inputs handicap h, difficulties d, pars p and scores s for i,j,k in zip(d,p,s) For each (difficulty, par, score) set (i, j, k): (h%18>=i)+h//18 Calculate the stroke index... j+...-k+2 ..calculate (par + stroke index) - score + 2... max(0,...) ...and clamp negative values to zero :sum(...) Return the sum of the above over all holes, which is the overall score ``` [Try it on Ideone](http://ideone.com/1BAhie) [Answer] # Haskell, 75 bytes This can definitely be golfed some more ``` (h!d)p s=sum[max 0$j-k+2+h`div`18+1`min`div(h`mod`18)i|(i,j,k)<-zip3 d p s] ``` [Answer] # [Perl 5](https://www.perl.org/), 142 bytes ``` ($h,@a)=map/\d+/g,<>;%d=map{$j++,$_}@a[0..17];$z+=($t=$a[18+$_]-$a[36+$_]+2+int$h/18+($k++<$h%18))>0?$t:0for sort{$d{$a}<=>$d{$b}}keys%d;say$z ``` [Try it online!](https://tio.run/##PY3RcoIwEEXf@xU8LDMyWTGrBKgC9Qf6BZZxUoFCtcIQ@oAMv16aSG125uZscu9uk7cXMU0LKHEvnfhLNqu3jK0@MEp2dmb6AT4ZQziOe3ngrktBuoMbixfQxSAPFDI4pktNG98QW7Pq2kG50h8LODMWQWlT6DgJf4Fuy4u6tVTddgNkA8gxihMD7@N4zntlZzsle7hNE4knaz5ZVRTV6fvS9Vvr8IwbJCQtWgMkgQEKpBDJQ@LooY@0RvIxxHX6mNDIVumsh6Y22m/00c23mN//I@pUt7nOiLtb/LkMBXen0IvMMk3pT910VX1V0/JVuJz4Lw "Perl 5 – Try It Online") There has got to be a shorter way to do this, but my brain can't come up with it right now. ]
[Question] [ The Post's Correspondence Problem (PCP) gives you a list of pairs of strings, P\_1 ... P\_n. Your task is to find a k, and some sequence of k indices such that fst(P\_i1) ... fst(P\_ik) = snd(P\_i1) ... snd(P\_ik) We're trying to find some sequence of the pairs where the word we build from the first part is equal to the word on the second part. A solution can use any of the pairs any number of times, and in any order. For example, if our pairs are `(0,110)`, `(11,1)` and `(001,100)` , then one solution is the world `11001110`, with the solution sequence of `2321`: ``` 11 001 11 0 1 100 1 110 ``` Some will have no solution, such as `(001, 01)`, `(0001, 01)`. ## Input: An arbitrary number of words, separated by spaces. Each word is of the format `seq1,seq2` where each `seq1` and `seq2` are strings consisting only of 0 or 1, of arbitrary length. ### Example: the above examples would have the following formats: ``` 0,110 11,1 001,110 001,01 0001,01 ``` ## Output: If there is some sequence of the pairs which solves the PCP, output the word of the solution, followed by a space, followed by the sequence. The pairs are numbered starting at 1. If there is no such sequence, run forever. (The problem is undecidable, so this will have to do). ### Example output ``` 11001110 2321 # second example never halts ``` ## Hint: This is Turing Complete, so you're going to have to use some sort of infinite search. [Answer] # Python 3, ~~223~~ ~~216~~ ~~199~~ ~~192~~ ~~191~~ ~~189~~ 183 bytes *Thanks to @KarlKastor for pointing out that I could use `count`* ``` from itertools import* j=''.join def f(x): for l in count(1): for i in product(x,repeat=l): *b,=zip(*i);c=j(b[0]) if c==j(b[1]):print(c,j(str(x.index(k)+1)for k in i));return ``` A function that takes input of a tuple of pairs of strings `x` in the form `((seq1,seq2),(seq1,seq2)...)` and prints the output to STDOUT in the same format as the test cases. To continuously output solutions rather than just one solution, remove the `return` statement. **How it works** The function generates all `l`-length arrangements of the string pairs using `product`, with `l` being initialised at `1`. This list is then unpacked and transposed using `zip`; this leaves a two-element list, where the first element contains all the first strings in the pairs, and the second all the second strings in the pairs. Each element is concatenated to a string using `join`; if these are the same, we have a hit and the string is printed to STDOUT. The sequence of pair indices is then generated by looking up each pair in the original arrangement using `index`; these indices are concatenated to a string, and also printed to STDOUT. If no solution exists for that `l`, `l` is incremented and the process repeated. [Try it on Ideone](https://ideone.com/AOCE1f) [Answer] # Python 2, ~~220~~ ~~215~~ ~~203~~ ~~199~~ ~~195~~ ~~193~~ 187 bytes ``` from itertools import* def f(p,o="".join): h=lambda s:o(x[s]for x in j) for i in count(1): for j in product(p,repeat=i): if h(0)==h(1):print h(0),o(`p.index(k)+1`for k in j);return ``` ### example use: ``` >>> f([("0","110"),("11","1"),("001","100")]) ('11110', '221') ``` [Answer] # Pyth - ~~55~~ 43 bytes ``` Msm@c@cz\ tvd\,H`G;.VZI>Z0B#=Z?qgb0gb1bZB;Z ``` Old version: ``` DgGH=TkV`G=+T@c@czdtvN\,H)RT;JZ.VZI>J0B#=J?qgb0gb1bJB;J ``` Explanation: ``` M #define a function g(G,H) s #join and return the following m `G; #for each char d in str(G): @cz\ tvd #split input on " " and get the element at index int(d)-1 @c \,H #split that on "," and get the element at index H ----------------------------------------------------------------------------------- .VZ ; #for b from 0 to infinity # B #try =Z? bZ #set var Z (which defaults to 0) to b if qgb0gb1 #g(b,0) is equal to g(b,1) I>Z0B #if Z>0, break Z #print Z ``` This program iterates from 0 to infinity. Each value is split digit by digit and that sequence is checked to see if it is valid. There is a try block so any sequences that go out of range are ignored, but considering how many sequences contain indexes that go out of bounds, this algorithm is painfully inefficient. But since when is code golf about efficiency? [Answer] # Haskell, ~~260~~ ~~253~~ ~~243~~ 230 Bytes ``` import Data.List c=concat x=concatMap l p=x(\n->sequence$replicate n[0..length p -1])[1..] i p=map(unzip.(map(p!!)))$l p f p=x(show.(+1))(a l)++" "++(c$fst$a i) where a e=e p!!((\(Just x)->x)$findIndex(\x->c(fst x)==c(snd x))$i p) ``` use like: `f([("0","110"),("11","1"),("001","110")])` This could probably be A LOT shorter, but what the hell... *-10 bytes thanks to @jmite* *-13 by replacing fromJust with lambda* ]
[Question] [ # Validating a CPR number A Danish CPR number (*Person Identification Number*) is date of birth followed by 4 digits (the last one being a control digit): DDMMYY-XXXX The final digit validates the CPR number using Modulo 11 by satisfying the following equation: [![mod11](https://i.stack.imgur.com/A7era.gif)](https://i.stack.imgur.com/A7era.gif) where the [![enter image description here](https://i.stack.imgur.com/4MfGq.gif)](https://i.stack.imgur.com/4MfGq.gif) are the ten digits of the complete ID number, and the coefficients (4, 3, 2, 7, …) are all nonzero in the finite field of order 11. # Input A CPR number formatted like this DDMMYY-XXXX where YY indicates a year within the last 100 years (between 1917 and 2016). # Output Indication whether CPR number is valid (1 or true) or invalid (0 or false) # Examples ``` 290215-2353 --> false 140585-2981 --> true 311217-6852 --> true 121200-0004 --> false 140322-5166 --> false 111111-1118 --> true ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - fewest bytes win! # Date validation All years refer to a period within the last 100 years. A valid date is a date that exists within it's calendar year. **290215** is not a valid date because 29/2 wasn't a date in 2015. **301216** is a valid date because 30/12 is a date in 2016. [Answer] # Python (2), ~~167~~ ~~156~~ ~~155~~ ~~142~~ 141 bytes ``` from time import* def f(s): try:return 1>sum(int(i)*(ord(j)-48)for i,j in zip("43276504321",s))%11;strptime(s[:6],"%d%m%y") except:return 0 ``` tried to do the date validation without the library, but it's 168 bytes: ``` lambda s:sum(int(i)*(ord(j)-48)for i,j in zip("43276504321",s))%11==0 and int(s[0:2])<([0,32,(29,30)[int(s[4:6])%4==0],32]+[31,32]*2+[32,31]*2+[32]+[0]*99)[int(s[2:4])] ``` *-12 bytes thanks to @GáborFekete* *-14 bytes thanks to @RootTwo* [Answer] # Ruby, ~~145~~ ~~113~~ ~~112~~ 103 + 8 (`-nrdate` flags) = 111 bytes Returns a date object (truthy) if it's a valid CPR, `false` if it fails the modulo test, and `nil` (falsy) if it fails the date test. Input is STDIN. *-33 bytes from @Jordan* ``` s=0 $_.size.times{|i|s+=12340567234/10**i%10*$_[i].to_i} p s%11<1&&Date.strptime($_,"%d%m%y")rescue p p ``` Version that returns literal `true` on valid CPR for +1 byte: ``` s=0 $_.size.times{|i|s+=12340567234/10**i%10*$_[i].to_i} p Date.strptime($_,"%d%m%y")&&s%11<1 rescue p p ``` Version that returns an error on invalid date instead of `nil`, for -10 bytes but probably invalid: ``` s=0 $_.size.times{|i|s+=12340567234/10**i%10*$_[i].to_i} p Date.strptime($_,"%d%m%y")&&s%11<1 ``` [Answer] # Mathematica, 130 bytes ``` DateObject[a={10#5+#6+4,10#3+#4,10#+#2}][[1]]==a&&11∣Tr[{4,3,2,7,6,5,4,3,2,1}{##}]&@@IntegerDigits@FromDigits[#~StringDrop~{7}]& ``` Anonymous function. Takes a string as input and returns `True` or `False` as output. The Unicode character is U+2223 DIVIDES, representing `\[Divides]`. [Answer] # Ruby + GNU date, ~~112~~ ~~111~~ 103 bytes -8 bytes from Kevin Lau. ``` ->n{s=0 n.size.times{|i|s+=12340567234/10**i%10*n[i].to_i} n=~/#{"(..)"*3}/ s%11<1&&`date -d#$3#$2#$1`>""} ``` Note that this prints e.g. "`date: invalid date ‘150229’`" to stderr if the date portion is invalid, but it still returns `true` or `false` (it doesn't raise an exception). If that's a disqualifier, though, I can add `⎵2>/dev/null` for a 12-byte penalty. ## Ungolfed ``` v = ->(cpr) { sum = 0 cpr.size.times do |idx| sum += 12340567234 / 10**idx % 10 * cpr[idx].to_i end cpr =~ /#{"(..)" * 3}/ sum % 11 < 1 && `date -d#$3#$2#$1` > "" } ``` ]
[Question] [ # ADFGX cipher encryption The ADFGX cipher was used by the German army in WWI. Write a program to encipher with it! It works as follows: 1. Create a 5x5 Polybius square with a mixed alphabet. The polybias square is labled `A D F G X` along the top and left. 2. Generate the pairs, so `A` in its non-mixed position is `AA`, `B` is `AD` and so on. 3. Perform [columnar transposition](https://en.wikipedia.org/wiki/Transposition_cipher#Columnar_transposition) using the columnar key. 4. Output the ciphertext. # Rules * Your program should either define a function that accepts the arguments of the mixed alphabet and the columnar transposition key, in that order, or accept the alphabet/key as command-line arguments. You can also get input from `STDIN`. * Standard loopholes apply. * You can't use a pre-written columnar transposition library (or, for that matter, ADFGX) - i.e. no running something like `import cipherpack`. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code (in bytes) wins! # Test cases My example runs used a failed source. I'll do some more later. # Leaderboard Run the Stack Snippet to generate a leaderboard. ``` /* Configuration */ var QUESTION_ID = 71997; // 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 = 50171; // 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> ``` **Note:** It is not necessary to split the output into groups of five. [Answer] ## Pyth, 26 bytes ``` seMhDC,Q.TcsXwz^"ADFGX"2lQ ``` For this, the second line (columnar key) needs to be in quotes, which is [acceptable by default](https://codegolf.meta.stackexchange.com/a/7634/39328). Try it [here](https://pyth.herokuapp.com/?code=seMhDC%2CQ.TcsXwz%5E%22ADFGX%222lQ&input=BTALPDHOZKQFVSNGJCUXMREWY%0A%27CARGO%27%0AATTACKATONCE&debug=0). [Answer] ## Pyth, ~~36~~ ~~34~~ ~~33~~ ~~32~~ 31 bytes ``` JwseMhDC,J.Tcsm@^"ADFGX"2xzdwlJ ``` ``` Jw assign (z, J) to 2 lines of input m w map over each char of a 3rd input line... ^"ADFGX"2 generate ['AA', 'AD', 'AF', ...] xzd find the index of this char in z @ index into ^^ with ^ s join groups of 2 ch. into one string c lJ split ^ into groups of len(J) chars .T transpose C,J pair elems up with chars of J hD sort by chars of J (the key) eM get rid of the chars of J now s join ``` Thanks to [Thomas Kwa](https://codegolf.stackexchange.com/users/39328/thomas-kwa) for a byte! Sample run, using [the example from Wikipedia](https://en.wikipedia.org/wiki/ADFGVX_cipher): ``` llama@llama:~$ pyth -c 'JwjdeMhDC,J.Tcsm@^"ADFGX"2xzdwlJ' BTALPDHOZKQFVSNGJCUXMREWY CARGO ATTACKATONCE FAXDF ADDDG DGFFF AFAX AFAFX ``` ]
[Question] [ **Introduction** Here at code colf SE, we appear to love meta-problems. Here, I've tried to compose a meta-problem that's an interesting, not-straightforward challenge. **Challenge** The answer code is allowed to read its own source code, but not allowed to use external resources. All characters should be 5-lines tall. Characters used in the ascii representation are also not important, though they must be visible. Each visible character in the output will count as one byte, regardless of cheaty byte-values. Spaces used in the code are necessary, and may be only one byte wide if desired. Lowest Byte Count ***of the output*** wins. Output must exist and include at least 1 visible byte. Example Input and Output **Input:** For an example code: ``` print theanswer ``` One possible answer is: **Output:** ``` PPPP RRRR III N N TTTTTT TTTTTT H H EEEE AA N N SSS W W EEEE RRRR P P R R I NN N TT TT H H E A A NN N S W W E R R PPPP RRRR I N N N TT TT HHHH EEE AAAA N N N SSS W W W EEE RRRR P R R I N NN TT TT H H E A A N NN S W W W E R R P R RR III N N TT TT H H EEEE A A N N SSSS W W EEEE R RR ``` The alphabet used should consist of the following ***patterns***, the characters used are not important: : ``` AA BBBB CCC DDD EEEE FFFF GGG H H III J K K L M M N N OOO PPPP QQQ RRRR SSS TTTTTT U U V V W W X X Y Y ZZZZZ A A B B C D D E F G H H I J K K L MM MM NN N O O P P Q Q R R S TT U U V V W W X X Y Y Z AAAA BBBB C D D EEE FFF G GG HHHH I J KK L M M M N N N O O PPPP Q Q RRRR SSS TT U U V V W W W X Y Z A A B B C D D E F G G H H I J J K K L M M N NN O O P Q Q R R S TT U U V V W W W X X Y Z A A BBBB CCC DDD EEEE F GGG H H III JJJ K K LLLL M M N N OOO P QQ Q R RR SSSS TT UUU V W W X X Y ZZZZZ 11 22 333 4 4 5555 6 77777 888 9999 000 //!!! @@@ # # % %% ^^ && (( )) 111 2 2 3 4 4 5 6 7 8 8 9 9 0 00 // !!! @ @ ##### %% ^ ^ & & (( )) 11 2 33 4444 555 6666 7 888 9999 0 0 0 // !!! @ @@ # # %% &&& &(( )) 11 2 3 4 5 6 6 7 8 8 9 00 0 // @ ##### %% & & & (( )) 11l1 2222 333 4 555 666 7 888 9 000 // !!! @@@ # # %% % &&&& (( )) ____ ``` For other characters, the [equivalent produced by this generator](http://www.kammerl.de/ascii/AsciiSignature.php) using the 'Alphabet' font will be acceptable. If the output generated by the tool is more than 5 characters tall, use the central 5 characters for output. **Edit -** I've allowed the program to read its own source code to possibly open this question up to interesting answers. [Answer] # Python 2, 2142 bytes Should work, it's pretty confusing to read the output. ``` n=["","","","",""] t=["EEEE","E E","EEE ","E "," EE "," E "," EEE ","E E","E "," EE ","EEEE "," EEEE"," ","EEE"," ","EE EE"," "] e=[[t[4],t[1],t[0],t[1],t[1]],[t[2],t[1],t[1],t[1],t[2]],[t[0],t[3],t[2],t[3],t[0]],[t[0],t[3],t[2],t[3],t[3]],[t[6],t[8],"E EE",t[7],t[6]],["EEE",t[5],t[5],t[5],"EEE"],[t[3],t[3],t[3],t[3],t[0]],[t[7],"EE E","E E E","E EE",t[7]],[t[6],t[7],t[7],t[7],t[6]],[t[10],t[7],t[10],t[8],t[8]],[t[10],t[7],t[10],"E E ","E EE"],[t[6],"E ",t[6]," E",t[6]],["E"*6,t[9],t[9],t[9],t[9]],[t[4],t[2],t[4],t[4],t[0]],[t[4],t[1]," E "," E ",t[0]],[t[2]," E",t[4]," E",t[2]],[t[1],t[1],t[0]," E"," E"],[t[0],t[3],t[2]," E",t[2]],[" E "," E ",t[10],t[7],t[6]],["EEEEE"," E "," E "," E "," E "],[t[6],t[7],t[6],t[7],t[6]],[t[11],t[7],t[11]," E "," E "],[t[6],"E EE","E E E","EE E",t[6]],["EE "," EE "," EE "," EE "," EE"],[t[12],t[13],t[12],t[13],t[12]],[t[0],"EE ","EE ","EE ",t[0]],[t[0]," EE"," EE"," EE",t[0]],[t[15],t[15],t[14],t[14],t[14]],[" "," "," "," ","EE"],[" EE","EE ","EE ","EE "," EE"],["EE "," EE"," EE"," EE","EE "],[t[12],t[5],t[13],t[5],t[12]],[t[16],t[16],t[16],t[16],t[0]],[" ","EE"," ","EE"," "],[" ","EE"," ","EE"," E"]] def s(i): if i==" ":r() if i=="a":g(e[0]) if i=="d":g(e[1]) if i=="e"or i=="E":g(e[2]) if i=="f":g(e[3]) if i=="g":g(e[4]) if i=="i":g(e[5]) if i=="l":g(e[6]) if i=="n":g(e[7]) if i=="o":g(e[8]) if i=="p":g(e[9]) if i=="r":g(e[10]) if i=="s":g(e[11]) if i=="t":g(e[12]) if i=="1":g(e[13]) if i=="2":g(e[14]) if i=="3":g(e[15]) if i=="4":g(e[16]) if i=="5":g(e[17]) if i=="6":g(e[18]) if i=="7":g(e[19]) if i=="8":g(e[20]) if i=="9":g(e[21]) if i=="0":g(e[22]) if i=="\\":g(e[23]) if i=="=":g(e[24]) if i=="[":g(e[25]) if i=="]":g(e[26]) if i=="\"":g(e[27]) if i==",":g(e[28]) if i=="(":g(e[29]) if i==")":g(e[30]) if i=="+":g(e[31]) if i=="_":g(e[32]) if i==":":g(e[33]) if i==";":g(e[34]) r() def g(p): for i in range(5):n[i]+=p[i] def r():g([" "," "," "," "," "]) for l in open(__file__).read().split("\n"): for i in l:s(i) print"\n".join(n);n=["","","","",""] ``` Output is 47965 bytes. Can probably be golfed a lot more. The code above uses half of the alphabet, all numbers and some symbols/special characters. I used the letter `E` for the output. The characters are a list of five strings, each for one line. Also, to save a few bytes, there's a list with common lines (`"EEEE"`, `"E E"`, etc.) The `,` has two lines, and one of them is below most characters, so I only included the upper one (same for underscore). [Answer] ## [Perl 5](https://www.perl.org/), 266 **34721 bytes code, 177815 total bytes of output, 266 bytes of which are non-whitespace.** ``` eval' '=~s' +\t'chr length$&'ger ``` Based on the [scoring confirmed by @Thomas Cleberg](https://codegolf.stackexchange.com/q/49850#comment217559_49850), something like this is likely optimal, but feels a little cheaty. This encodes a program that prints the desired output as space and tab characters, which are replaced with the result of running `ord` on the length of each run (spaces, terminated by a tab). To cater for this in the output, each tab is represented with two spaces (over the five lines) and all spaces are shown as described above. TIO limits the output to 128KiB so you can't see it all there, but if you run this program locally, it should work as expected. Something like: ``` perl -M5.010 metascii-code-golf.pl > metascii-code-golf.txt ``` and view `metascii-code-golf.txt` in a text editor with word-wrap disabled. [Try it online!](https://tio.run/##7Z1BTsNADEXXvkUWiCwQqCy65AjcgA1CUYsUtVVbseTohDNQEdvfft1OYns8tseeH09P03neLsv09T6Pg/vP5BncytjKqXpl1s2IWEqrjB7POev1LSaTXkVsxDL7oehkGXc3lhokMfO@EdJSWKzFG7naZu8f7aBI8kcVmNtPtXKoJNJokYmoiaCpT5ME6O9yeD3jo1NLodd29RFbDESonvy3OVNwFZAmnVnnj6scNkTlCTkWLsNk876c7qsPpGuwSYnAYiiWJBFsS2drAXdKVsBrQSvKmVWSMzu@h8pBk93z//lkoOEDemhwkTzsaBEA60VxZYkBlcJTAKSOshj9ThjS87WtHPX5qLe1dHTi4DQxjzaIOl3Ahqp0@Gyr3yZFY45UWZzZ4YFa4sQofP4BcEMmcoscdMjESiTiYwR40i3qE7d1aIFsFm0i0dQVrS94TovTkLrtLVg1S4J1dI1rBeXowBGUQ6zYbXnDVsq5VSm9dGsCQIf6cqh0m9SjQuDKJGbD5EM9o@aasw4WWmJWHL83owUEwLjW8kOSccbDrJK/WGlVu@SNh0qIBZkkVe76XgGkFOciTa66SZIKg84EBCLaOOKfAsspGJTJjKiJ8m61PsxzX1QTz9LkpLG0a25OBmIu75i25bmysUBbs/Hl@zIOD2/X8WN/HubpsLvu7@7H3XRelp/j6fp5PFyWx9ft0@Z58ws "Perl 5 – Try It Online") ]
[Question] [ An *incremental word chain* is a sequence of words of a vocabulary such that each word is the result of either prepending or appending a single character to the previous word, ignoring capitalization. An example of such a chain can be found below. > > I → is → his → hiss > > > Your task is to write a program that for a given vocabulary finds the longest incremental word chain. The input is provided from standard input a vocabulary as one word per line. The words are composed of the lowercase letters a to z only. The output of your program shall go to standard output and shall be one word per line a longest word chain of the input vocabulary, starting with the shortest word. This is code golf, the solution with the least character count wins. Different forms of input or output are not possible, but the terms *standard input* and *standard output* may be interpreted in a reasonable way for the language you are solving this problem in. Please demonstrate that your code works by publishing the longest word chain you find on the xz-compressed vocabulary found [here](http://fuz.su/~fuz/files/voc.xz). This vocabulary was generated by executing the following series of commands on the file *british-english-insane* from the [SCOWL project](http://wordlist.aspell.net/) in the C locale: ``` tr 'A-Z' 'a-z' <british-english-insane | sed -n '/^[a-z]*$/p' | sort -u | xz -9e >voc.xz ``` A solution in polynomial time is possible and highly appreciated. [Answer] # Ruby, 127 Runs in about 6.5 seconds. Uses a couple of cool tricks. ARGF (`$<` or stdin, really) is enumerable! If an array is passed as a block argument, it can be "exploded" and assigned to a parameter using `{|w,| ... }`. Notice the comma. I found an even shorter solution which uses `Array#&` (set intersection) to do the lookup of words, but that runs extremely slow, unfortunately. Thanks to w0lf for shaving off a few characters ``` D={} $<.map{|l|D[l.strip!]=l} puts D.map{|w,|c=[w] w.chars.all?{w=c[0] r=D[w.chop]||D[w[1..-1]] r ?c=[r]+c :p} c}.max_by &:size ``` ### Output ``` r ra rah rahm brahm brahma brahman brahmani brahmanis brahmanism brahmanisms ``` ### Readable version ``` D = {} $<.lines { |l| D[l.strip] = l.strip } chains = D.map do |word, _| chain = [word] word.chars.all? do word = c.first result = D[w.chop] || D[w[1..-1]] result ? chain.unshift(result) : nil end end puts chains.max_by(&:size) ``` [Answer] ### Ruby ~~139~~ 127 ``` h={} $<.map{|l|h[l.strip]=1} v=->w,c=[]{w<?a?c:h[w]&&(v[w.chop,z=[w]+c]||v[w[1..-1],z])} puts h.map{|k,_|v[k]||0}.max_by &:size ``` Runs in ~3.5 seconds and prints: ``` r ra rah rahm brahm brahma brahman brahmani brahmanis brahmanism brahmanisms ``` [Answer] # Python 2, 208 bytes Here is a not very small solution. It firsts creates an index of the word parts, then recursively searches for the longest chain. ``` import sys d={} b=lambda k:d.setdefault(k,[]).append(e) for e in sys.stdin:e=e[:-1];b(e[1:]);b(e[:-1]) def f(a): g=a for c in d.get(a[-1],[]):g=max(g,f(a+[c]),key=len) return g for e in f([''])[1:]:print e ``` It returns: ``` a ab rab arab arabi arabin arabine carabine carabiner carabinero carabineros ``` in 6.2 seconds. The code before minifier looks like this: ``` import sys lookup = {} addindex = lambda k: lookup.setdefault(k, []).append(word) for word in sys.stdin : word = word[:-1]; addindex(word[1:]); addindex(word[:-1]) print 'Indexed' # DEBUG def find(wordlist): best = wordlist for newword in lookup.get(wordlist[-1], []) : best = max(best, find(wordlist+[newword]), key=len) return best for word in find([''])[1:] : print word ``` [Answer] # Haskell, 175 Bytes ``` import Data.Set main=interact$unlines.snd.maximum.g.lines g l=Prelude.map(f(0,[]))l where f z@(d,r)w|notMember w(fromList l)=z|1<2=max(f(d+1,w:r)(tail w))(f(d+1,w:r)(init w)) ``` finds ``` r ra ran fran franc franci francis francisc francisca franciscan franciscans ``` Spent about 30 bytes for the use of a `Set` data structure for efficient lookups but that are useless (in code golf!) otherwise. How it works: for every word from the input build recursively a list with valid child words. Take the longest list and print it. A "child word" is the word with either first or last letter missing. It is "valid" if it's in the input. If both child words exist, take the one that builds the longer sublist. [Answer] **J: 246 bytes** ``` 's p'=:(*(>./i)>:])|:(6 s:[:s:}.;}:)S:0 w[i=:6 s:v=:s:w=:~.a:,<;._2 fread'voc' l=:[:,([:(#S:0)5 s:_6 s:])"0 f=:3 :'(y{~])^:(~:0:)^:a:"0 y' q=:_6 s:] d=:[:+/@:*"1 f ds=:d s[dp=:d p n=:(ds<:dp)}s,:p[m=:ds>.dp echo}:"1 q(r{i),.(r=:([:I.]=>./)m){f n ``` output: ``` `franciscans `franciscan `francisca `francisc `francis `franci `franc `fran `fra `fr `f ``` [Version with comments.](https://github.com/tangentstorm/tangentlabs/blob/master/j/growvoc.ijs) ]
[Question] [ Write a program in the shortest number of **bytes** possible that will parse any string given to it by input, and output that string with any and all numbers padded with leading zeroes to match the largest number's length. For example: Input: ``` This 104 is an -8 example of 4.518 a string 50. ``` The generated output should become: ``` This 104 is an -008 example of 004.518 a string 050. ``` Note that any digits after the period are not considered part of the "length" of a number. Numbers are considered any sequence of digits with either 0 or 1 periods in the sequence. Numbers will be delimited with either the string boundary, spaces, commas, or newlines. They can also be followed by a period, but only if the period is then followed by a delimiting character. They can also be preceded with a '-' to indicated negatives. So something like this: ``` The strings 20.d, 5.3ft and &450^ are not numbers, but 450.2 is. ``` Should output the following: ``` The strings 20.d, 5.3ft and &450^ are not numbers, but 450.2 is. ``` That is to say, no modifications. String input will be no more than 200 characters, if your program has an upper bound for some reason. The winning answer will be the answer in the shortest number of bytes in **seven days** from the posting of this question. ### Test cases Input: ``` 2 40 2 ``` Output: ``` 02 40 02 ``` Explanation: both substrings `2` are bounded on one side by a string boundary and on the other side by . --- Input: ``` E.g. 2,2.,2.2,.2,.2., 2 2. 2.2 .2 .2. 2d 2.d 2.2d .2d .2.d 40 ``` Output: ``` E.g. 02,02.,02.2,00.2,00.2., 02 02. 02.2 00.2 00.2. 2d 2.d 2.2d .2d .2.d 40 ``` Explanation: in the first two groups the first four numbers are followed by a delimiter (`,` or ) and the final one is followed by a period then a delimiter; in the third group, each sequence is followed by the non-delimiter `d`. [Answer] ## Ruby, 111 bytes I hope this catches all the details of the spec ``` puts $*[0].gsub(r=/(?<![^,\s])(-?)(\d+)(?=\.?\d*(?![^,\s]))/){$1+$2.rjust(i.scan(r).map{|m|m[1].size}.max,'0')} ``` It reads the input as the first command line argument and prints the result to STDOUT. [Answer] # Cobra - 282 ``` class P def main r,s,l,n=RegularExpressions.Regex(r'^[\n,]?-?(\d+).?\d*[\n,]?$'),Console.readLine.split(' '),0,0 for m in 2,for y,x in s.numbered,if r.isMatch(x),while (n-=n-r.match(x).groups[1].length)<if(n>l,l-=l-n,l),x=s[y]=if(x[0]=='-','-0'+x[1:],'0'+x) print s.join(' ') ``` For those of you wishing to test this without installing Cobra, it's rather easily converted into equivalent C# code. [Answer] ## JavaScript, 201 chars ``` s=prompt();j=k=l=0,t={} for(i in s){s[i]==+s[i]&&s[i]!=" "?j++:(t[i-j]=j,j=0);if(j>k)k=j;}if(j!=0)t[+i+1-j]=j for(i in s){if(t[i])while(k-t[i]){s=s.slice(0,+i+l)+"0"+s.slice(+i+l);t[i]++;l++;}}alert(s) ``` ]
[Question] [ Write the shortest possible program that turns a binary search tree into an ordered doubly-linked list, by modifying the pointers to the left and the right children of each node. **Arguments**: a pointer to the root of the binary tree. **Return value**: a pointer to the head of the linked list. The binary tree node has three fields: * the ordering key, an integer * a pointer to the left child * a pointer to the right child The pointers should be modified so that "left child" points to the previous node of the list and "right child" points to the next node of the list. * Y̶o̶u̶'̶r̶e̶ ̶n̶o̶t̶ ̶a̶l̶l̶o̶w̶e̶d̶ ̶t̶o̶ ̶c̶r̶e̶a̶t̶e̶/̶a̶l̶l̶o̶c̶a̶t̶e̶ ̶m̶o̶r̶e̶ ̶n̶o̶d̶e̶s̶. * The tree and the list are both ordered increasingly. * You have to write the implementation of the node object. * The tree is not necessarily complete Example: ``` input: 5 <- root / \ 2 8 / \ / \ 1 4 6 9 output: head -> 1-2-4-5-6-8-9 ``` EDIT: I removed the 1st rule, since people complained it was not possible to do using functional programming languages. [Answer] # Python: 100 ``` class N:l=r=v=None def T(p,q=None): if not p:return q r=p.r=T(p.r,q) if r:r.l=p return T(p.l,p) ``` ## Ungolfed Version ``` class Node: left = right = value = None def transform(node, next=None): """ node: head node to convert next: next node for the tail node to connect return: The converted head """ if not node: return next node.right = transform(node.right, next) if node.right: node.right.left = node return transform(node.left, node) ``` Instead of returning a (head, tail) pair, in my solution, a `next` node is passed as argument to the transform function so that it only need to return the head node. This make the code shorter and cleaner. [Answer] # Javascript 238 (163 not including the input tree declaration/initialization) Tested in google chrome. To see the result, open the javascript console and traverse any node of the list. jsfiddle: <http://jsfiddle.net/49grd/1/> ``` b={val:5,n1:{val:2,n1:{val:1},n2:{val:4}},n2:{val:8,n1:{val:6},n2:{val:9}}} o=[] function r(t){if(t.n1)r(t.n1);o.push(t);if(t.n2)r(t.n2);} r(b); for(var i=0;i<o.length;i++){if(o[i-1])o[i].n1=o[i-1];if(o[i+1])o[i].n2=o[i+1];} console.dir(o[0]); ``` **Ungolfed:** jsfiddle avbailable here: <http://jsfiddle.net/s8PsU/> ``` var binaryTree = { val: 5, n1: { val: 2, n1: { val: 1}, n2: { val: 4} }, n2: { val: 8, n1: {val: 6}, n2: {val: 9} } } var orderedNodes = [] function traverse(t) { if(t.n1) traverse(t.n1); orderedNodes.push(t); if(t.n2) traverse(t.n2); } traverse(binaryTree); for(var i = 0; i < orderedNodes.length; i++) { if(orderedNodes[i-1]) orderedNodes[i].n1 = orderedNodes[i-1]; if(orderedNodes[i+1]) orderedNodes[i].n2 = orderedNodes[i+1]; } console.dir(orderedNodes[0]); ``` [Answer] # C: 79 114 I'm not sure exactly how this is supposed to be scored, so if someone thinks that other parts of my code should be counted as well, please say so. Here's the function that does the conversion: ``` t*f(t*n,t*h){static t*p=0;n?f(n->l,h),(p?(n->l=p),p->r=n:(h=n)),p=n,f(n->r,h):0;t*r=h;for(;r->l;r=r->l);return r;} ``` This is the `struct` that I use to represent a tree: ``` typedef struct n { int o; struct n* l; struct n* r; } t; ``` You can see the rest of the code that I used to test it [here](http://codepad.org/Hu90vD2F) (re-compile it, it uses STDIN). Here's a sample run: ``` $ ./tree2list < in Insert nodes to tree: Tree traversal: -527 -7 0 2 3 6 8 23 63 conversion done List traversal: -527 -7 0 2 3 6 8 23 63 ``` The contents of the file `in`: ``` 6 8 2 3 0 -7 23 63 -527 ``` I used code from [here](http://leetcode.com/2010/11/convert-binary-search-tree-bst-to.html) to help me fix my conversion algorithm. Edit: I didn't notice that we're supposed to return a pointer to the list, so I still need to fix that. Fixed. [Answer] # Scala - (207/188) Characters ``` class n(a:n,b:Int,c:n){var l:n=a;var n:Int=b;var r:n=c}def t(r:n):(n,n)=(if(r.l==null)r else{val y=t(r.l);r.l=y._2;y._2.r=r;y._1},if(r.r==null)r else{val y=t(r.r);r.r=y._1;y._1.l=r;y._2}) def a(r:n)=t(r)._1 ``` Without the function a wich just gets the head of the list, this are 188 characters. Idea is: return a tuple wich consist of the most left element of you and your children and the most right element. Also link your left element to the most element of your left children and your right element to the most left element of your right children. Code for printing the list: ``` def printN(r:n)=if(r==null)"null" else (r.n + "->" +printN(r.r)) ``` Ungolfed: ``` class Node(a:n,b:Int,c:n){//our Node Class var l:Node=a //left child var n:Int=b //data of the node var r:Node=c //right cild } def traverse(r:Node):(Node,Node)=(//return a pair //get smallest known element if(r.l==null) r //smallest is identity if left child is null else { //sethighest of traverse of left child as left child val y=traverse(r.l) r.l=y._2 //left child is highest of traverse left child y._2.r=r //and right of this is me y._1 //return the currently smallest known element (maybe allways the smallest? }, //get highest known element if(r.r==null) r //if right is null, current node is the highest known else { val y=ttraverse(r.r) //traverse right child r.r=y._1 //set pointers for list y._1.l=r y._2 //return most right child of right child } )//end of return pair def traverseWrapper(r: Node)=t(r)._1 //just return the smallest element ``` Note that the list is now double linked, it is possible to ignore the back links and save characters (but this is too ugly). Bring my first and second semester labs back to mind ;-) [Answer] # Haskell: 96 In this solution, new nodes are created, which violate the first rule. However, creating new nodes seems unavoidable in pure functional style code. ``` data N=N Int N N|L f L=[] f(N v l r)=f l++v:f r g _[]=L g p(x:y)=n where n=N x p$g n y t=g L .f ``` ## Ungolfed Version ``` data Node = Node Int Node Node | Leaf flatten :: Node -> [Int] flatten Leaf = [] flatten (Node value left right) = flatten left ++ [value] ++ flatten right link :: Node -> [Int] -> Node link _ [] = Leaf link prev (x:xs) = node where node = Node x prev $ link node xs transform = link Leaf . flatten ``` ### Some code for testing: ``` toList Leaf = [] toList (Node v l r) = v:toList r toReverseList' Leaf = [] toReverseList' (Node v l r) = v:toReverseList' l toReverseList node@(Node v l Leaf) = toReverseList' node toReverseList (Node v l r) = toReverseList r toReverseList Leaf = [] t = Node 4 (Node 2 (Node 1 Leaf Leaf) (Node 3 Leaf Leaf)) (Node 5 Leaf Leaf) main = do print $ toList $ transform t print $ toReverseList $ transform t ``` ]
[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/19354/edit). Closed 7 years ago. [Improve this question](/posts/19354/edit) Given an array of 32-bit integers which represent a bit array, shift the values by a specified amount in either direction. Positive shifts go to the left and negative values go to the right. This is a bit array so bits should wrap across values in the array. For example, given the following data: ``` a[2] = 11110000 11110000 11110000 11110000 a[1] = 11110000 11110000 11110000 11110000 a[0] = 11110000 11110000 11110000 11110000 <-- 0th bit ``` Shifting the original by 2 should result in: ``` a[3] = 00000000 00000000 00000000 00000011 a[2] = 11000011 11000011 11000011 11000011 a[1] = 11000011 11000011 11000011 11000011 a[0] = 11000011 11000011 11000011 11000000 <-- 0th bit ``` Shifting the original by -3 should result in: ``` a[2] = 00011110 00011110 00011110 00011110 a[1] = 00011110 00011110 00011110 00011110 a[0] = 00011110 00011110 00011110 00011110 <-- 0th bit ``` There's no restriction on shift amount (i.e., can be greater than 32) so be mindful of where your bits are going! Here's the method signature: ``` int[] bitArrayShift(int[] bits, int shift) ``` Implementations should: * Return an array whose contents represented the original bit array's contents shifted by the supplied number. * Return an array whose size is the minimum amount required to hold the values after the shift. You should not wrap back around to the 0th bit but rather expand to hold it. * Not mutate the input array. It should be treated as being passed by reference (therefore having mutable contents). Basically, don't put any new values at any position in the input array. The following assertion should always return true for any value of 'bit' and 'shift': ``` // Given 'originalBits' as incoming bit array. // Given 'bit' as a number between [0, originalBits.length * 32). // Given 'shift' as any integer value. // Get the value in the array at the index of 'bit' bool original = ((originalBits[bit / 32] & (1 << (bit % 32)) != 0 // Shift the original bits by the specified 'shift' int[] shiftedBits = bitArrayShift(originalBits, shift) // Offset the original 'bit' by the specified 'shift' int shiftedBit = bit + shift // Get the value in the shifted array at the index of 'shiftedBit' bool shifted = ((shiftedBits[shiftedBit / 32] & (1 << (shiftedBit % 32)) != 0 // They should be equal. assert original == shifted ``` Smallest character count wins. Count method body contents ONLY sans leading and trailing whitespace. That is, the method declaration up to and including the block start (if any) and ending exclusively at the block end (if any). E.g., for Java: ``` public static int[] shiftBitArray(int[] bits, int shift) { << COUNT THIS ONLY >>> } ``` [Answer] # Java 306 ``` public static int[] shiftBitArray(int[] bits, int shift) { BigInteger r = BigInteger.ZERO; for (int i = bits.length - 1; i >= 0;) r = BigInteger.valueOf(0xffffffffL & bits[i--]).or(r.shiftLeft(32)); r = r.shiftLeft(shift); int[] a = new int[(int) Math.ceil(r.bitLength() / 32d)]; for (int i = 0; i < a.length; r = r.shiftRight(32)) a[i++] = r.intValue(); return a; } ``` [Answer] # Java 500 ``` public static int[] shiftBitArray(int[] bits, int shift) { int t = 32, w; long x = 1L << t; String s = "", z = Long.toString(x, t / 2).substring(1); z += z; z += z; for (int i : bits) s = Long.toString(i & x - 1 | x, 2).substring(1) + s; for (; shift > 0; shift -= t) s += z; s = -shift > s.length() ? z : z.substring(shift & t - 1) + s.substring(0, s.length() + shift); while (s.startsWith(z)) s = s.substring(t); int[] r = new int[(w = s.length()) / t]; for (int j = 0; j < r.length; j++) r[j] = (int) Long.parseLong(s.substring(w -= t, w + t), 2); return r; } ``` [Answer] **Python (181)** ``` def bitArrayShift(b, s): a=''.join(bin(x)[2:].zfill(32)for x in b) a=(a+'0'*s if s>0 else a[:s]).lstrip('0') return[int(a[b:c],2)for b,c in[(x-32if x>31 else 0,x)for x in range(len(a),0,-32)]][::-1]or[0] ``` It basically just turns the array into a single string of bits, rotates by string manipulation and converts it back to integers. [Answer] ### GolfScript, 32 characters ``` {{2.5??base}:^[[email protected]](/cdn-cgi/l/email-protection)>{?*}{~)?/}if^}:S; ``` (Character count without `{}:S;` as specified in the question) Defines a function `S` with works on the stack (there is no such thing like call by reference for stack-based languages). Usage: ``` 2 [4042322160 4042322160 4042322160] S p # => [3 3284386755 3284386755 3284386752] -3 [4042322160 4042322160 4042322160] S p # => [505290270 505290270 505290270] ``` 6 characters more if one prefers lowest-word first. [Answer] ## J (32) ``` shift=:4 :'#.|."1|._32>\|.({.~x+#);y#:~32#2' ``` (Not counting the `shift=:4 :'`...`'`.) Test: ``` 9!:11[20 NB. set print precision high enough for the large numbers to show shift=:4 :'#.|."1|._32>\|.({.~x+#);y#:~32#2' 2 shift 4042322160 4042322160 4042322160 3 3284386755 3284386755 3284386752 _3 shift 4042322160 4042322160 4042322160 505290270 505290270 505290270 ``` Explanation: * `y#:~32#2`: encode each value in `y` as 32 bits, giving a matrix. * `;`: join the rows of the matrix together, giving a list of bits. * `{.~x+#`: take the first `x+length` elements from the list, padding with zeroes. (so zeroes get added to the end if `x` is positive, dropped if `x` is negative.) * `|.`: flip the list (to make partitioning easier) * `_32>\`: group the bits into groups of 32, padding with zeroes. (the extra zeroes go on the end, which is why the list had to be flipped.) * `|."1|.`: flip the resulting matrix both horizontally and vertically, putting the bits back in the right order. * `#.`: decode each line of bits back into an integer. [Answer] # APL, 49 ``` shift←{⌽2⊥⍉(c,32)⍴⌽(32×c←⌈n÷32)↑⌽(n←⍺+⍴v)↑v←∊(32/2)∘⊤¨⌽⍵} ``` Could probably be golfed some more. The entire `(32×⌈n÷32)↑` and the following reshaping is probably overkill. **Examples** ``` 0 shift 3/4042322160 4042322160 4042322160 4042322160 2 shift 3/4042322160 3284386752 3284386755 3284386755 3 ¯3 shift 3/4042322160 505290270 505290270 505290270 ``` [Answer] **Golfscript (57)** A first draft, slightly longer than APL but all ascii. Probably possible to golf a little more. ``` ~.~)@2 32?:q;{\q*+}*@{2*}*\{2/}*{q%1$}{;q/}/\;-1%.![0]*+p ``` [Answer] # Scala 324 ``` def shiftBitArray(bits: Array[Int], shift: Int): Array[Int] = { def f(i:Array[Int])=i.map(x => String.format("%32s",x.toBinaryString).replace(' ','0')).mkString def g(x:Int)=List.fill(x)("0").mkString def h(s:String)=s.grouped(32).toArray.map(x=>java.lang.Long.parseLong(x, 2).toInt) val s=shift if (s<=0)h(g(-1*s)+f(bits).dropRight(-1*s)) else h(g(32-s)+f(bits)+g(s)) } ``` [Answer] # Mathematica 57 In infix form: ``` a_~f~n_ := Flatten@a~RotateLeft~n~ArrayReshape~Dimensions@a ``` In standard prefix form: ``` f[a_,n_]:=ArrayReshape[RotateLeft[Flatten[a], n], Dimensions[a]] ``` where `a` is the array and `n` is the shift parameter. --- `Flatten` transforms `a` into a list of integers. `RotateLeft[list,n]` rotates `list` n places leftward (if >= 0) or rightward (if n<0). `Dimensions` obtains the dimensions of the input matrix. `ArrayReshape[list, Dimensions[a]]` transforms `list` into an array with the dimensions of the original matrix, `a`. `RotateRight[a,n]` has the same effect as `RotateLeft[a,-n]` for all integers n. ]
[Question] [ This question is inspired by a similar question [first asked on StackOverflow by Florian Margaine](https://stackoverflow.com/questions/17807531), then asked in variant forms on [CS by Gilles](https://cs.stackexchange.com/questions/13420) and on [Programmers by GlenH7](https://softwareengineering.stackexchange.com/questions/206073). This time, it's a code golf, with specific metrics for success! In an office of ten people, it's someone's turn to buy croissants every morning. The goal is to produce a schedule that lists whose turn it is on any given day, subject to the following constraints: 1. Presence. Each person is away from the office on business or vacation on average ~20% of the time. Each time you schedule a person who is away, lose one point per person who didn't get to eat croissants. For simplicity, generate the away-schedule with the random number generator `seed = (seed*3877 + 29573) % 139968`, starting with `42*(10*i + 1)` as the initial (unused) seed, where `i` is the zero-indexed number of the employee; whenever `seed` is below 27994, that person will be away. Note that if everyone is away, you can assign anyone and not lose points. 2. Fairness. Each person will keep track of whether they have bought more or fewer croissants than the average. A person who never buys more than 10 more than the average will give you one point (they understand that someone has to buy first, and they'll of course go above the average). Otherwise, let `k` be the farthest above the average that a person has gotten in `n` days of buying; that person will give you `1 - (k-10)/100` points. (Yes, this may be negative.) 3. Randomness. The employees get bored if they can predict the sequence. Gain ten times the number of bits of information revealed a typical choice; assume that the employees can search for repetitive patterns and know the order of how long it's been since each of them bought croissants. 4. Non-repetitiveness. Employees hate buying croissants two days in a row. Each time this happens, lose a point. 5. Brevity. if `b` is the number of bytes of the gzipped\* version of your solution, reduce your score by `b/50`. The solution should be an output of letters or numbers (0-9 or A-J) indicating who should buy croissants on each day. Run the algorithm for five hundred days (two years of work); give yourself a point if the output is in 10 rows of 50. You *only* need to produce the sequence, not calculate the score. Here is a reference program in Matlab (or Octave) that picks people completely at random except for avoiding people who are away: ``` function b = away(i) b=zeros(500,1); seed=42*(10*i+1); for j=1:500 seed=mod((seed*3877+29573),139968); b(j)=seed<27994; end end A=zeros(500,10); for i=1:10 A(:,i)=away(i-1); end for i=1:10 who = zeros(1,50); for j=1:50 k = 50*(i-1)+j; who(j)=floor(rand(1,1)*10); if (sum(A(k,:)) < 10) while (A(k,who(j)+1)==1) who(j)=floor(rand(1,1)*10); end end end fprintf(1,'%s\n',char(who+'A')); end ``` Here is a sample run: ``` HHEADIBJHCBFBGBIDHFFFHHGGHBEGCDGCIDIAEHEHAJBDFIHFI JFADGHCGIFHBDFHHJCFDDAEDACJJEDCGCBHGCHGADCHBFICAGA AJAFBFACJHHBCHDDEBEEDDGJHCCAFDCHBBCGACACFBEJHBEJCI JJJJJBCCAHBIBDJFFFHCCABIEAGIIDADBEGIEBIIJCHAEFDHEG HBFDABDEFEBCICFGAGEDBDAIDDJJBAJFFHCGFBGEAICEEEBHAB AEHAAEEAJDDJHAHGBEGFHJDBEGFJJFBDJGIAJCDCBACHJIJCDF DIJBHJDADJCFFBGBCCEBEJJBAHFEDABIHHHBDGDBDGDDBDIJEG GABJCEFIFGJHGAFEBHCADHDHJCBHIFFHHFCBAHCGGCBEJDHFAG IIGHGCAGDJIGGJFIJGFBAHFCBHCHAJGAJHADEABAABHFEADHJC CFCEHEDDJCHIHGBDAFEBEJHBIJDEGGDGJFHFGFJAIJHIJHGEBC ``` which gives a total score of -15.7: ``` presence: 0 (Nobody scheduled while away) fairness: 6.6 (~340 croissants bought "unfairly") randomness: 33.2 (maximum score--uniformly random) no-repeat: -51.0 (people had to bring twice 51 times) size: -5.5 (275 bytes gzipped) format: 1 (50 wide output) ``` Here is the reference Scala method I'm using to compute the score ``` def score(output: String, sz: Either[Int,String], days: Int = 500) = { val time = (0 until days) def away(i: Int) = Iterator.iterate(42*(10*i+1))(x => (x*3877+29573)%139968).map(_<27994) val everyone = (0 to 9).toSet val aways = (0 to 9).map(i => away(i).drop(1).take(days).toArray) val here = time.map(j => everyone.filter(i => !aways(i)(j))) val who = output.collect{ case x if x>='0' && x<='9' => x-'0' case x if x>='A' && x<='J' => x-'A' }.padTo(days,0).to[Vector] val bought = time.map(j => if (here(j) contains who(j)) here(j).size else 0) val last = Iterator.iterate((0 to 10).map(_ -> -1).toMap){ m => val j = 1 + m.map(_._2).max if (bought(j)==0) m + (10 -> j) else m + (who(j) -> j) }.take(days).toArray def log2(d: Double) = math.log(d)/math.log(2) def delayEntropy(j0: Int) = { val n = (j0 until days).count(j => who(j)==who(j-j0)) val p = n.toDouble/(days-j0) val q = (1-p)/9 -p*log2(p) - 9*q*log2(q) } def oldestEntropy = { val ages = last.map{ m => val order = m.filter(_._1<10).toList.sortBy(- _._2) order.zipWithIndex.map{ case ((w,_),i) => w -> i }.toMap } val k = last.indexWhere(_.forall{ case (k,v) => k == 10 || v >= 0 }) (k until days).map{ j => ages(j)(who(j)) }. groupBy(identity).values.map(_.length / (days-k).toDouble). map(p => - p * log2(p)).sum } def presence = time.map(j => if (here(j) contains who(j)) 0 else -here(j).size).sum def fairness = { val ibought = (0 to 9).map{ i => time.map(j => if (i==who(j)) bought(j) else 0). scan(0)(_ + _).drop(1) } val avg = bought.scan(0)(_ + _).drop(1).map(_*0.1) val relative = ibought.map(x => (x,avg).zipped.map(_ - _)) val worst = relative.map(x => math.max(0, x.max-10)) worst.map(k => 1- k*0.01).sum } def randomness = ((1 to 20).map(delayEntropy) :+ oldestEntropy).min*10 def norepeat = { val actual = (who zip bought).collect{ case (w,b) if b > 0 => w } (actual, actual.tail).zipped.map{ (a,b) => if (a==b) -1.0 else 0 }.sum } def brevity = -(1/50.0)*sz.fold(n => n, { code => val b = code.getBytes val ba = new java.io.ByteArrayOutputStream val gz = new java.util.zip.GZIPOutputStream(ba) gz.write(b, 0, b.length); gz.close ba.toByteArray.length + 9 // Very close approximation to gzip size }) def columns = if (output.split("\\s+").filter(_.length==50).length == 10) 1.0 else 0 val s = Seq(presence, fairness, randomness, norepeat, brevity, columns) (s.sum, s) } ``` (there is a usage note^). The winner is the one with the highest score! Actually, there will be two winners: a globally optimizing winner and a short-notice winner for algorithms where earlier selections do not depend vacations that will happen in the future. (Real office situations are in between these two.) One entry may of course win both (i.e. it is short-notice but still outperforms other entries). I'll mark the short-notice winner as the "correct" winner, but will list the globally optimizing winner first on the scoreboard. Scoreboard: ``` Who What Score Short-notice? ============== ====================== ======= === primo python-miniRNG 37.640 Y Peter Golfscript-precomputed 36.656 N Rex Scala-lottery 36.002 Y Rex Matlab-reference -15.7 Y ``` \*I'm using gzip 1.3.12 with no options; if there are multiple files, I cat them together first. \*\*A list prepared in advance is not considered short-notice unless it would be swapped out for a better list if an away-day appeared the day before; if this is a major issue (e.g. an unanticipated away day causes reversion to an algorithm that performs horribly) I'll define precise criteria. ^ If you use gzip, pass in the size as `Left(287)`; otherwise if your code is in `code` (`val code="""<paste>"""` is useful here), use `Right(code)`) [Answer] ## Python (37.640 points) ``` i=61 r=[420*n+42for n in range(10)] for n in r: o='' for n in r*5: r=[(n*3877+29573)%139968for n in r] f=[n<27994for n in r] l=i while~-all(f)*f[i%10]or(i-l)%10<1:i=i**3%1699 o+=str(i%10) print o ``` *The second level of indentation is with literal tab characters.* Score breakdown: ``` presence: 0.0 fairness: 8.618 randomness: 31.502 no-repeat: 0.0 size: -3.48 format: 1.0 ``` The PRNG i'm using is a simplified version of [Keith Randall's solution](https://codegolf.stackexchange.com/a/10583/4098) to the Diehard challenge, which despite its extreme brevity, passes all 15 tests. The solution is short notice: the absentee list is calculated on the day of, and all previous attendance is forgotten. The only thing which is recorded is who bought on the previous day, so that repetition may be avoided. I suspect that the fairness score could be improved by keeping a queue of individuals who should have bought, but didn't, and adding them into the rotation as soon as possible. I'm not sure if this would lead to an overall improvement, though, due to a lower score for size. About the randomness upper-bound, it is certainly higher than 32. Replacing line 7 with `i=i**3%1699` (removing the attendance and repetition constraints) results in a randomness score of `32.966`. **Update:** Most of the improvement comes from better zip compression, by renaming variables, and reusing constructs such as `for n in r` numerous times. [Answer] ## GolfScript (36.656 points) ``` presence: 0 fairness: 9.498 randomness: 31.778 no-repeat: 0 size: -5.62* format: 1 ``` \* The Lempel-Ziv step is actually bad for this program: it would only be `5.46` (including the 9-character "penalty" from the Scala code) if strategy `HUFFMAN_ONLY` where used. (By my Huffman tree calculations, it should be 1839 bits, which suggests that there are 34 bytes of overhead - more than I remember from the last time I read the gzip file format spec, but my memory could be off). ``` '45274749890953461384092895296161282397696128454780712395638361237579450740141057012045098236468567830463395138297694808909654367173131250582012342078481734627820869476489062315253101230346792585956785940285674601914907495382306749019845658361271737890123953439852610678507814707530469358317402346278901984267190129362162512915678681507567831843423709082970928201432569730525454784512915686709218065814323413439817345681607567947860143456038712392671909236989193072045789650183645701325105856402426275'50/n* ``` [Answer] ### Scala (36.002 points) Code (run in REPL): ``` val (p,d,s)=(0 to 9,0 to 499,Array.fill(10)(0d)) val h=p.map{i=>var s=42*(i*10+1);d.map{_=>s=(s*3877+29573)%139968;s>27993}} val n=d.map{j=>h.count(_(j))} var q=0 d.map{j=>val t=s.map(_+util.Random.nextGaussian);t(q)+=9;p.map{i=>if(h(i)(j))t(i)-=9};val k=t.indexWhere(_==t.min);q=k;s(k)+=0.3;k}.mkString.grouped(50).foreach(println) ``` Example output (for which score was calculated): ``` 71756902145841391934765437292035652843760984098583 86397265015640974915628232730106147281529836713094 08565240287124932136398520876027407943071218763914 50987680167146425903575318020863656749795382985435 07941018246493815719641937560694585402820150738727 13126926431856275181072676938295301345412807480484 81839634956059251426350709373902682797204746548906 16175895303731651486209495295428383160620710851569 74013482373647246513814672019837413985207414790529 39206976935168020524260381937139452108673574826406 ``` Score breakdown: ``` presence: 0 fairness: 9.094 randomness: 31.448 no-repeat: 0 size: -5.54 format: 1 ``` Short-notice: yes, here-list `h` is used on the day of selection only. ]