text
stringlengths
180
608k
[Question] [ English is such an inefficient language. We've got enormous words when there are plenty of two or three letter words we never used! As computer scientists, every keystroke matters. We need to be more efficient. Just think of how many words we could have had! In fact, don't think about it, tell me. Given a string (or list) of letters, I want you to output how many words we could make using those letters. You must use every letter in the string exactly one time. Words can't just be any old string of letters though, how would you say "yffghtjrufhr"? To be a word, it has to satisfy the following conditions: * It must contain at least one vowel ('y' is always a vowel). * There must be no more than 2 vowels in a row. * There must be no more than 3 consonants in row. * The combinations "ch", "sh", and "th" count as one consonant. * "s" counts as neither a consonant nor vowel ("length" is just as valid as "lengths"). For example: ``` Input -> Output a -> 1 (a) b -> 0 ab -> 2 (ab, ba) abbbb -> 3 (babbb, bbabb, bbbab) abbbbbbb -> 0 essss -> 5 (essss, sesss, ssess, ssses, sssse) abbbth -> 46 (thabbb, thbabb, thbbab, bathbb, ...) ``` Obviously, since this challenge is all about character efficiency, I think a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge is in order. Standard rules apply! (For clarification, an 's' breaks any streaks of vowels or consonants. The word "abbbsbbb" is ok, since there are no more than 3 consonants in a row".) [Answer] # Python 3, 166 Bytes ``` import itertools as i,re;print(len([w for w in[re.sub('[cst]h','b',''.join(x))for x in set(i.permutations(input()))]if not re.search('[aeiouy]{3}|[^aeiouys]{4}',w)])) ``` Takes a string from input(). The string is passed to itertool's (built-in library) permutations function, in this case taking a string and returning tuples of unique combinations when wrapped in set(). ''.join() turns the tuples into strings again. Combinations 'th', 'ch', and 'sh' are replaced with an arbitrary consonant, 'b' using re's (regular expression, built-in library) sub function. Words (variable 'w' in the list comprehension) are are then filtered based on if they contain 4 or more consonants, or 3 or more vowels using re's search. [Answer] # JavaScript, 275 bytes ``` a=>(a.match(/[^aeiouys]/g)||[])[L='length']<a[L]*.85|0&&[...Array(1<<(n=(a=[...a])[L])*--n/2)].map((_,b)=>a.slice().sort(_=>(b/=2)*2&1?1:-1).join``).filter((a,b,c)=>c.indexOf(a)==b&&/[aeiouy]/[t='test'](d=a.replace(/[cst]h/,1))&!/[aeiouy]{3}/[t](d)&!/[^aeiouys]{4}/[t](d))[L] ``` [Try it online](https://tio.run/##TVBdT8IwFH3fr6gJWVuytQ41MUJnfCfxB9TK7kaBkdktayGSwW@fHcTpfTm9p/fcj7OHI9iiLRsXm3qt@43oQaQE2Be4Yke4/ARd1oeTVXxLz2epqFwKXGmzdTusFiCXasqen873YSgZY29tCyeSLBbECAJioGCQKDqNY8NnVPnGDSGrKKciBWarstCEMlu3jqz84JyLGZ3OwuQ1eYkTyvZ1abKMsk1ZOd0SAlEeFV5asNKs9ff7hgAVIg9DLm@LKi6dwE5bhxVZC2CtbirwQ7gsrFM7HiWUhndjefdw8QpfeiXHa7vHX3rYvj9Ci0rTHBwSSAYIYcDRAPkNYEQf/55jpq2Pvw/vXaDmQVDUxtaVZlW9Jdf2V3cAiRRlkw4uKI7jFE264cpLdnOD4A@DKZ33Pw) ]
[Question] [ Your task is to write a program or function that checks if a string is a valid URL. Given a string as input, you will output a truthy value if the input is a valid URL. If it is not, output a falsey value. An input string is considered a valid URL if all of the following criteria are met: * Begins with `http://` or `https://` * At least one and up to 128 labels (parts of URL delimited by a period) + Labels delimited by a period + Contain only letters, digits, and hyphens + Do not start nor end with a hyphen + Third and fourth characters cannot be a hyphen, unless the first two characters are 'xn' + A label may contain zero to 63 characters * The length of the string does not exceed 253 characters This is a code-golf, with standard rules. --- <https://en.wikipedia.org/wiki/Domain_Name_System#Domain_name_syntax> [Answer] # JavaScript, 114 bytes ``` x=>RegExp(`^(?!.*([./](-|(?!xn)[^/]{2}--)|-[./]|-$))https?://${a='[a-zA-Z0-9-]{0,63}'}(?:\\.${a}){0,127}`).test(x) ``` Hopes it works. For *real* URLs, you should use: ``` x=>eval(`try{new URL(x)}catch(e){}`) ``` Thanks to ThePirateBay, construct regex from string save 3 bytes. ]
[Question] [ For this challenge you need to make a given word by concatenating "pieces" (a.k.a contiguous substrings) from other words. Given a word and a list of words as input, output the fewest number of pieces needed to create the first word. # Rules * Words consist of characters in the ASCII range 33 to 126. * The word list may have repeats. * Construction of words is case sensitive (you can not use the piece "Head" as part of the word "forehead".) * Once you have used a piece in a construction, you can not use any part of that piece again (e.g if I use "lo" from "lone" as part of constructing "lolo", I cannot use "lo" from that "lone" again. However, if I had two "lone" in my word list, I could use one "lo" from each.) * Once you use a piece, you can still make pieces out of unused substrings in the word. (E.g. If I used "tt" in "butter", I still have "bu" and "er" left over to use. However, I can't combine them into one "buer" piece.) * If it is impossible to construct the input word using the word list given, output nothing, or something other than a positive integer. # Examples (you only need to output the number) * `"snack" ["food","Shoe","snack"]` => 1 (`snack`) * `"Snack" ["food","Shoe","snack"]` => 2 (`S` + `nack`) * `"frog" ["cat","dog","log"]` => 0 * `"~~Frank~~" ["Frog~","~~Love","Hank~"]` => 4 (`~~` + `Fr` + `ank~` + `~`) * `"loop-de-loop" ["loop", "frien-d","-elk","pool"]` => 7 (`loop` + `-d` + `e` + `-` + `l` + `oo` + `p`) * `"banana" ["can","can","boa"]` => 4 (`b`+`an`+`an`+`a`) * `"banana" ["can","boa"]` => 0 * `"13frnd" ["fr13nd"]` => 3 (`13` + `fr` + `nd`) Let me know if you think of more useful test cases. [Answer] # JavaScript, ~~209~~ 206 bytes ``` f=(a,b,F)=>a?[...a].map((_,i)=>[...Array(i+1)].map((_,j)=>F||b.forEach((q,k)=>!F&&~(I=q.indexOf(a[S='substring'](j,r=a.length-i+j)))&&(F=b[k]=q[S](0,I)+' '+q[S](I+r+j),a=a[S](0,j)+a[S](r)))))&&F&&1+f(a,b):0 ``` [Try it online](https://tio.run/##jZJfa4MwFMXf@ymcD22CUSp7m6RjjMkKgz34KGFcNbb@WdJGVzbW@dW7G9vJXgZDSE7O@cXcq6nhAF1uql3vK13I0wGM08uuv4dOdg530pnjpG6nIG9chqrUunCZm2y1xOnsC8FGKvkXVRq9GaEcegwLu3JbHH@AYYgNqGYYRipGHBW6T/pg3/Zoswlutd75hfTtPPIXgcdUUvm2Cl@2WJW707qdtmWg8LmUoTA9j5mGv5HfYXhdGlWcezXhNUohZiI6lZwAy1hM@Qpu0yAIQASvsCPkhVXoWefOGPgglRfSKaoxio/HLCi1eYB8S8ieNehdxfP5QNZ8H1SqkO/PJYE04YvuLet6U6nNQpCaGQ5BK9Wm3/qVV1NK53MS8yxtBN@niSBLtqbewll442rtGYQYcDhnNfVGZSgdt@KJoVfaJujN8hRNV2EqzToOXzmf@B1yrTrdygD/HikJ9mZDSqPZF41O3w) Returns `NaN` if the combination is not found. ]
[Question] [ For the question [Find the highest unique digit](https://codegolf.stackexchange.com/questions/128784/find-the-highest-unique-digit) , here is [my answer](https://codegolf.stackexchange.com/a/132539/46313) : ``` 9A,sqfe=W%X#- ``` At the end I am essentially trying to achieve a lastIndexOf. I do that by reversing my array, using indexOf, and subtracting from 9. This adds 4 (`9` `W` `%` `-`) extra bytes to get from indexOf to lastIndexOf. Furthermore, if I didn't know my array was length 10 the code would be even longer, and secondly, this code returns `10` when indexOf is `-1` which may not be acceptable in many situations. Any suggestions on a shorter way to do the lastIndexOf operation (generally or just as needed for this challenge)? [Answer] Splitting is sometimes a good way to do this. E.g. ``` e# Stack: ... haystack needle a/);S*, ``` With variants, such as removing the `a` if both needle and haystack are strings. [Answer] # 9 bytes ``` _,(@@W%#- ``` [Try it online!](https://tio.run/##S85KzP2fqqwQUFqioJGTmpdekqGgq2CoqZBYrJCWWVRcopCZV5Kanlqkx8VVWPc/XkfDwSFcVVn3f2pKrPV/Q4VoMwVTBUMgNFIwBpImCgYKhrEA "CJam – Try It Online") You must have `...element list` exactly like this in the stack. If `W` doesn't contain `-1` you must replace it with something that does evaluate to `-1`. ]
[Question] [ This challenge was inspired by the game Flood. # Challenge Given a grid of colors, determine the optimal list of moves to take to convert the whole grid to the same color. First of all, let us say that a pixel is in the "top left chunk" if and only if it is either the top left pixel or it shares an edge with a pixel of the same color in the top left chunk. Then, a move is defined as changing the color of all pixels in the top left chunk to a specific color. If you change the color of the top left chunk to match the color of one of the pixels adjacent to the top left chunk, then that pixel joins the top left chunk. The input will be given as a matrix of positive integers with each integer representing a distinct color. A move is defined by the color to which you change the top left chunk; thus, a move is represented as an integer, The output should be a list of integers representing which moves to take to convert the entire grid to one color in as few moves as possible. If multiple methods are possible, outputting all of them or any one of them is allowed. # Example Let's take this as an example: ``` 123 132 223 ``` In this case, both `[2, 3, 2]` and `[3, 2, 3]` work. We observe the following for `[2, 3, 2]`: ``` 123 223 333 222 132 -> 232 -> 332 -> 222 223 223 333 222 ``` and the following for `[3, 2, 3]`: ``` 123 323 223 333 132 -> 332 -> 222 -> 333 223 223 223 333 ``` # Test Cases ``` 123 132 -> 2 3 2 OR 3 2 3 223 111 111 -> [] 111 123 231 -> 2 3 1 2 312 123 312 -> 2 1 3 1 2 OR 2 1 3 2 1 OR 2 3 2 1 3 OR 2 3 2 3 1 OR 3 1 2 1 3 OR 3 1 2 3 1 OR 3 2 3 1 2 OR 3 2 3 2 1 (Thanks @JonathanAllan) 231 ``` # Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest valid submission is determined as the winner, tiebreak by earlier submission winning * The input and output can be in any reasonable format for matrices and lists * The input is not necessarily square but is necessarily rectangular * Your program must be able to handle at least 128 x 128 * Your program must be able to handle at least 16384 colors * You may also take the number of distinct colors as an input Please correct my test cases if they are wrong. Thanks! # Note: I believe that this is different enough from Create A Flood AI to warrant its own post because the winning criteria are very different; that one mainly asks to find a small number of steps to solve all of the test cases; this one requires one of the shortest solutions and is a code-golf. However, if you disagree, please close-vote as duplicate and then the community can decide. [Answer] ## CJam (77 bytes) ``` {Ma+a{():B;:A:|{A((:C;0\+a\+_e_,2*{[0C]f/[0_]f*z}*{0Der}%BD+a+a+}fDAe_(-}g;B} ``` [Online demo](https://tio.run/##S85KzP1fWPe/2jdRO7FaQ9PKydrK0aqm2lFDw8rZ2iBGOzFGOz41XsdIqzrawDk2TT/aID42TauqVqvawCW1qFbVyUUbqFO7Ns3FMTVeQ7c23dqp9n9dwf/oaEMFIwXjWK5oYwUgC0gDeQqGsbEA). This is an anonymous block (function) which takes the input as a 2D array and provides the output as a 1D array. ]
[Question] [ # Introduction Wardialing was a very interesting way to try to hack people back in the '80s and '90s. When everyone used dial-up, people would dial huge amounts of numbers to search for BBS's, computers, or fax machines. If it was answered by a human or answering machine, it hung up and forgot the number. If it was answered by a modem or a fax machine, it would make note of the number. ["Of course, you realize this means War...dialing?"](http://www.youtube.com/watch?v=4XNr-BQgpd0 "quot;Of course you realize...this means warquot;") <--- Pun made by @Shaggy # Challenge Your job is to make a URL wardialer. Something that tests and checks if it's a valid website from one letter of the alphabet. # Constraints * Program must take user input. This input has to be a letter of the alphabet, no numbers. Just one letter of the alphabet and form multiple URLs that start with the letter. **Input letter will be lowercase, not uppercase.** * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * You must make 8 URLs from 1 letter, and test to see if it is a valid site. * If you hit an error (not a response code), instead of leaving it blank, go ahead and return a 404 * If you hit a redirect (3xx), return a 200 instead. * **You may output the results in any reasonable format, as long as it includes the website name, status codes for all the websites and the redirects.** * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest amount of bytes wins. # What counts as a URL for this challenge? http://{domain-name}.{com or net or org} For this challenge, the domain name should only be 4 letters long, no more, no less. # What should I test? For each 4 letter domain name, test it against three top-level domains (.com, .net, .org). Record all the response codes from each URL, remember from the constraints that any (3xx) should return 200 and be recorded as a redirect in the output and any error getting to the website should result in a 404. # Input > > a > > > # Output ``` +---------+------+------+------+------------+ | Website | .com | .net | .org | Redirects? | +---------+------+------+------+------------+ | ajoe | 200 | 200 | 200 | .com, .net | +---------+------+------+------+------------+ | aqiz | 200 | 404 | 404 | no | +---------+------+------+------+------------+ | amnx | 200 | 503 | 404 | .com | +---------+------+------+------+------------+ | abcd | 200 | 404 | 200 | .com | +---------+------+------+------+------------+ | ajmx | 200 | 503 | 404 | no | +---------+------+------+------+------------+ | aole | 200 | 200 | 200 | .com | +---------+------+------+------+------------+ | apop | 404 | 200 | 200 | .net | +---------+------+------+------+------------+ | akkk | 200 | 200 | 200 | .com | +---------+------+------+------+------------+ ``` [Answer] # Python 2 + requests, ~~198~~ 191 bytes ``` from requests import* def f(c): for i in range(24): u='http://'+c+`i/3`*3+'.'+'cnooermtg'[i%3::3] try:a=get(u,allow_redirects=0).status_code except:a=404 if a/100==3:a='200 R' print u,a ``` --- Sample output for `a`: ``` http://a000.com 404 http://a000.net 404 http://a000.org 404 http://a111.com 200 ... http://a666.org 502 http://a777.com 403 http://a777.net 200 R http://a777.org 200 ``` [Answer] # Ruby, 145 + 10 = 155 bytes + 10 bytes for command line arguments. Probably not winning any beauty contests with this: ``` x=[*$<.getc+?a*3..?z*4] 24.times{|i|r=Net::HTTP.get_response(URI(p"http://#{x[i/3]}."+'comnetorg'[i*3%9,3])).code rescue"404" p r=~/^3/?"200R":r} ``` Run with `ruby -rnet/http wardialing.rb` Example: ``` $ ruby -rnet/http wardialing.rb <<< g "http://gaaa.com" "200R" "http://gaaa.net" "200" "http://gaaa.org" "200" "http://gaab.com" "200" "http://gaab.net" "200" "http://gaab.org" "200" "http://gaac.com" "404" (etc) ``` [Answer] # Bash, 90 bytes ``` for i in $1{100..104}.{com,net,org};{ echo $i;(curl -IL $i 2>:||echo HTTP 404)| grep HTTP;} ``` Sample output: ``` b100.com HTTP/1.1 301 Moved Permanently HTTP/1.1 200 OK b100.net HTTP/1.1 301 Moved Permanently HTTP/1.1 200 OK b100.org HTTP 404 b101.com HTTP/1.1 301 Moved Permanently HTTP/1.1 200 OK b101.net HTTP/1.1 406 Not Acceptable b101.org HTTP/1.1 406 Not Acceptable b102.com HTTP/1.1 200 OK b102.net HTTP 404 b102.org HTTP 404 b103.com HTTP/1.1 301 Moved Permanently HTTP/1.1 200 OK b103.net HTTP 404 b103.org HTTP 404 b104.com HTTP/1.1 301 Moved Permanently HTTP/1.1 200 OK b104.net HTTP/1.1 301 Moved Permanently HTTP/1.1 200 OK b104.org HTTP 404 ``` [Answer] # PHP, 221 bytes ``` for($c=8;$c--;){$u=$argv[1];for($i=3;$i--;)$u.=chr(rand(97,122));for($z=0;$z<3;){$r="$u.".['com','net','org'][$z++];$h=get_headers("http://$r");$s=$h?substr($h[0],9,3):404;$t=(3==intval($s/100))?"200R":$s;echo"$r $t\n";}} ``` With CRs and indentation ``` for($c=8;$c--;){ $u=$argv[1]; for($i=3;$i--;)$u.=chr(rand(97,122)); for($z=0;$z<3;){ $r="$u.".['com','net','org'][$z++]; $h=get_headers("http://$r"); $s=$h?substr($h[0],9,3):404; $t=(3==intval($s/100))?"200R":$s; echo"$r $t\n"; } } ``` Sample output on 'b': ``` bnjz.com 404 bnjz.net 200 bnjz.org 404 bkxw.com 200 bkxw.net 200 bkxw.org 403 biak.com 200 biak.net 403 biak.org 200R bpzb.com 200 bpzb.net 200 bpzb.org 404 bigr.com 404 bigr.net 200 bigr.org 200 bcei.com 404 bcei.net 200R bcei.org 200 bexc.com 200 bexc.net 200 bexc.org 404 bset.com 404 bset.net 200 bset.org 200 ``` [Answer] # NodeJS, ~~249~~ 246 bytes -3 bytes thanks to @ASCII-only. ``` c=>{r=_=>Math.random().toString(36).slice(-3),o="",q=i=>(u=`http://${n=i%3?n:c+r()}.`+["com","net","org"][i%3],o+=u+" ",d=r=>(o+=(/^3/.test(s=r.statusCode||404)?"200R":s)+` `,--i?q(i):console.log(o)),require("http").get(u,d).on("error",d)),q(24)} ``` Creates random three-letter strings from 1-9 and a-z for each domain. Redirects are shown as `200R`. [Try it online](http://code.runnable.com/WSn4VKce2ckjbhqd/wardialing) (Note: may take a minute or two to complete all requests) ### Sample output ``` http://a9k9.com 200 http://a9k9.net 404 http://a9k9.org 404 http://a529.com 200 http://a529.net 404 http://a529.org 404 http://asor.com 200R http://asor.net 404 http://asor.org 404 ``` ## Longer version with table output, 278 bytes ``` c=>{r=_=>Math.random().toString(36).slice(-3),o=h=`name .com .net .org `,q=i=>(i%3||(n=c+r(),o+=n+` `),u=`http://${n}.`+h.substr(6+i%3*5,3),d=r=>(o+=(/^3/.test(s=r.statusCode||404)?"200R":s)+(++i%3?` `:` `),i<24?q(i):console.log(o)),require("http").get(u,d).on("error",d)),q(0)} ``` Whitespace in `name .com .net .org` and `n+` `` are literal tab characters. ### Sample table output ``` name .com .net .org aa4i 200 200 200 a66r 404 404 404 anmi 200 200 403 aaor 403 200R 200R ``` [Answer] # q/kdb+, ~~392~~ ~~378~~ ~~300~~ 276 bytes **Solution:** ``` t:{ w:y,($:)x; r:@[{"J"$-3#12#(`$":http://",x)y}[w;];"GET / HTTP/1.1\r\nHost:",w,4#"\r\n";404]; (x,`w`r)!(r;`$y;$[(r>299)&r<400;[r:200;x];`]) } f:{ R:(`w,x,`r)xcols(,/)each(x)t\:/:{x,/:3 cut 24?.Q.a}y; (`Website,x,`$"Redirects?")xcol update r:`No from R where r=` }[`.com`.org`.net;] ``` **Example:** ``` q)f"a" Website .com .org .net Redirects? --------------------------------- amik 200 200 200 .net abjl 200 200 503 No afuw 403 200 200 No agby 200 200 200 No afen 200 200 200 .net ajch 200 404 200 No aaro 200 200 200 No ajsr 200 404 503 No ``` **Notes:** Current solution is fairly hefty... Half the code is trying to fetch a URL, the other half is presenting the results nicely, unsure how much further I can golf this. **Explanation:** Function t ``` w:y,($:)x // convert suffix (`.com) to string, prepend host and save in w @[x;y;404] // try function x with parameter y, on error return 404 "GET /..." // HTTP GET request in shortest form `:http://x y // open web connection to x, send request y -3#12# // truncate output to 12 chars, take last 3 chars "J"$ // cast result to long $[x;y;z] // if x then y, else z (x)!(y) // create a dictionary with x as keys, y as values ``` Function f ``` 24?.Q.a // take 24 random characters from a-z x,/:3 cut // cut into 3-character lists, prepend input 'x' t\:/: // call function t with each combination of left and right (,/) each // raze (reduce) each result xcols // re-order columns into output format xcol // rename columns ``` ]
[Question] [ After giving back the results of the last topology exam to his students, Pr. Manifold was worried about complaints. Since he is aware his students know where his office is located, Prof. Manifold decided to transform his office into a bunker with a 10 digit password (all characters are digits). But he suspected his students to be very clever (despite having tremendously bad grades). Knowing that, he's not going to pick a password containing certain sequences, such as his StackExchange ID, university parking spot number, and annual salary. ## Your task Your program or function will take as input an array of integers. No single integer will contain duplicate digits, which implies that none of the integers will have more than 10 digits. Your code will output how many unique 10 digit passwords Prof. Manifold can choose, taking into account that correct passwords * must contain each digit 0-9 exactly once, and * must not contain any of the sequences present in the input array. ### Example Input: `[18062,6042,35876]` * `1806234579`, `6042135789`, `3587612409`, `3418062579`, `1237896042`, and `1243587609` are all incorrect passwords, because they each contain at least one of the sequences present in the input array. * `0113456789` is an incorrect password, because the professor's password must contain each digit exactly once. * `0123456789` is a correct password, because it doesn't contain any sequence present in the array, and it contains each digit exactly once. Test case: ``` [18062,6042,35876] -> 3622326 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -3 bytes thanks to Dennis (avoid a chain separation allowing some implicit actions; use a filter to avoid the two byte `œ&` multi-set intersection I was using.) ``` ⁵ḶŒ!Ẇf¥ÐḟDL ``` **[Try it online!](https://tio.run/nexus/jelly#@2/6cMe2o5MUH@5qSzu09PCEhzvmu/j81zncrvKoaU0WEINQw1wdMLNxn65d5P//0dGxOtEGQGxoBCZ0jA0htKEBjNYxMkRi6hiDJYBMAyBTx8RAByRjrGNoomNkrGNkomNsEhsLAA)** - the specified version is far too slow for the online interpreter, so **this is a proof of concept** test suite: - it does the same thing for only **5** digits `01234`, - the first example is the empty list, yielding `120` as expected (**5!**), - the last returns `1` as the only permutation still available to the professor is `04321`, - an offline run of the full version with input `[18062,6042,35876]` yielded `3622326` as expected. ### How? ``` ⁵ḶŒ!Ẇf¥ÐḟDL - Main link: list a ⁵ - literal 10 Ḷ - lowered range: [0,1,2,3,4,5,6,7,8,9] Œ! - all permutations D - decimal list (vectorises across a) Ðḟ - filter discard (from the permutations) if: (note - non-empty is truthy) ¥ - last two links as a dyadic operation: Ẇ - all sublists (of the current permutation) f - filter keep (if in the decimal list) L - length ``` ]
[Question] [ (*randomly inspired by [this question](https://monero.stackexchange.com/q/2633)*) Let's make a drawing from some pipes `|` and hyphens `-`. Choosing a subset, if chosen carefully, you can form a rectangular box or block shape (meaning that the corners are formed by `|-` or `-|`). For this challenge, we're concerned only with identifying the corners -- the vertical and horizontal pieces of the block shape can be made of either `|` or `-`, and the block may be hollow. Here's the original drawing, and the subset showing a block shape. ``` |--|---| |--|---| |-|||-|| --> | | |------| |------| ``` However, note that the following subsets from this same example do *not* make a block, because the corners are not all `-|` or `|-` ``` |--| |-|| ||-|| ----| |-| --- ``` Each combination of `-|` or `|-` can only form one corner. This means that the smallest possible block shape is these eight characters ``` |--| |--| ``` and that these six characters do *not* form a block shape, since the corners are being "doubled up." ``` |-| |-| ``` The challenge here is to turn these blocks fluffy. How? Replace every hard-edged straight character that forms the block edges (both corners and sides) with a much rounder, fluffier character, in this case, an `o`. But, don't fill in the block - we only want to get rid of the hard edges and sharp corners. ``` |--|---| oooooooo |-|||-|| --> o-|||-|o |------| oooooooo ``` ### Input A 2D string representation of the pipe/hyphen diagram. Input can be as a multiline string, an array of strings, etc., however is [convenient for your language](http://meta.codegolf.stackexchange.com/q/2447/42963). The input is guaranteed to be rectangular (i.e., every row will be the same length), and will only contain `|` and `-`. ### Output The same diagram, with the "block" characters replaced with `o` as described above and the remaining characters unchanged. The result can be printed to the screen or STDOUT, returned from a function, etc. ### Rules * Note that blocks can overlap (see example #8) and blocks can share corners (see example #5). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. ### Examples ``` #1 -|--| |--|- |--|| -|--| oooo- oooo| #2 |--|---| |-|||-|| |------| oooooooo o-|||-|o oooooooo #3 ||||| ||||| #4 |-----| ||---|- ||---|- |-----| ooooooo ooooooo ooooooo ooooooo #5 -|--|--| |||-|--| -|-----| -ooooooo |o|-oooo -ooooooo #6 |-||-| |----| oooooo oooooo #7 --|--|- |-----| --|--|- |-----| #8 |-----|--- ||--||-|-- ||||--|--| |-|-||||-| |--|--|-|| ---||---|| ---|-----| ooooooo--- o|--||o|-- o||ooooooo o-|o||o|-o ooooooo-|o ---o|---|o ---ooooooo ``` [Answer] ## Perl, 448 bytes ``` $_=<>;$o=$_;~y/-|/Aa/;$N=$_;while($n ne $N){$n=$N;$c=$N;$M=$c;while($c=~s/^(.*?;)??([aA]*?)aA([aA]*)Aa(.*;(?i)\2)aA((?i)\3)Aa(.*)$/\L\1\2\UAA\3AA\L\4\UAA\5AA\L\6/){if($N eq $n){substr($N,(length $1)+(length $2),1)="X"}substr($M,-(length $6)-1,1)="X";$c=~s/^([xa;]*;)?(a*)A(A*)A(a*;)\2a((?i)\3)a/\1\2A\3A\4\2A\5A/;1 while $c=~s/(^|;)(a*)A(a*)A(a*;)\2a((?i)\3)a/\1\2A\3A\4\2A\5A/;while($c=~/A/g){substr($o,(pos $c)-1,1)="o"}$c=$M}}$o=~y/;/\n/;print$o ``` I haven't used perl before so there's going to be *massive* room for improvement here (especially since I was mostly glad to get it working, so haven't tried to optimise it yet). I was a bit disappointed that **the** regular expression language didn't have some of the features I wanted, but I think it does pretty well. ### Usage Takes input on stdin, with lines semicolon-separated (optionally add a semicolon to the end to make the final printed output end with a newline). Outputs to stdout. Example command: ``` printf -- "-|--|--|;|||-|--|;-|-----|;" | perl boxes.perl ``` ### Breakdown ``` $_=<>; # Load input $o=$_; # Create output variable ~y/-|/Aa/; # Replace - and | with A and a so that we can use case insensitive tricks later $N=$_; # For each distinct top-left corner... while($n ne $N){ $n=$N; $c=$N; $M=$c; # For each distinct box... while($c=~s/^(.*?;)??([aA]*?)aA([aA]*)Aa(.*;(?i)\2)aA((?i)\3)Aa(.*)$/\L\1\2\UAA\3AA\L\4\UAA\5AA\L\6/){ if($N eq $n){ # mark top-left corner used (x) substr($N,(length $1)+(length $2),1)="X" } # mark bottom-right corner used (x) substr($M,-(length $6)-1,1)="X"; # Fill in sides of identified box $c=~s/^([xa;]*;)?(a*)A(A*)A(a*;)\2a((?i)\3)a/\1\2A\3A\4\2A\5A/; 1 while $c=~s/(^|;)(a*)A(a*)A(a*;)\2a((?i)\3)a/\1\2A\3A\4\2A\5A/; # Replace output chars with "o" where box was found while($c=~/A/g){ substr($o,(pos $c)-1,1)="o" } # Continue to next box $c=$M } } # Convert to nice output & print $o=~y/;/\n/; print$o ``` ]
[Question] [ I recently found out about the [Fishing](https://esolangs.org/wiki/Fishing) language, and it is now a favorite of mine. However, I'm finding it difficult to do anything cool with it, including code golf. Are there any tips for golfing with Fishing to use the least characters? And any string manipulation tricks would be cool, as I am finding that difficult in Fishing. [Answer] # `a` and `m` work on strings too Though it isn't explicitly stated in the spec, `a` (add) and `m` (multiply), at least in the official Ruby interpreter, also work on strings. Say you had two cells with strings in them at the end of the tape, and wanted to concatenate and print them. You could do it with `c`: ``` c{{P ``` However, as long as you don't want to preserve the original value of your first cell, you could append the second string directly onto the first with `a` and avoid having to go to the end of the tape: ``` aP ``` Now let's say you want to print 20 spaces. The naive way to do it would be to simply hardcode them: ``` ` `P ``` As long as the cell to the right is free, though, you can save 11 instructions by using `m`: ``` ` `{`20`n}mP ``` Note, however, that due to the way Ruby works, you *cannot* do this with the order of the cells reversed (i.e. multiply a number by a string); that causes an error. [Answer] # `?` doesn't need both an adjacent `=` *and* an adjacent `!` This isn't explicitly stated in the spec either, but with the official interpreter, you do not need to surround a conditional (`?`) with both `=` *and* `!`; if one is not present and the condition matches it, the program will keep going in its original direction. An example: ``` v+CCCCCC?=CCCCCCCC I{`0`}! E`Zero`N [CCCCCCCCCCCC E`Not zero`N ``` This program prints takes a string and prints "Zero" or "Not zero", depending on whether it equals `"0"`. You could shave off two bytes, however, by removing the `=` sign: ``` v+CCCCCC?CCCCCCCC I{`0`}!E`Zero`N [CCCCCCCCCCCC E`Not zero`N ``` ]
[Question] [ Welcome to BBC Casting. We need a program that we can use to select a new actor to play **The Doctor** on **Doctor Who**. In the spirit of the show, your program will perform a regeneration from one actor's name to the next. We will test your program by running through the 13 names of actors who have already played The Doctor and then run it another 13 times. We will pass the output from one call as the input to the next in a loop. **Detailed Requirements** * Your program will take a string as its only input and output a single string. It must not store any state between calls or use any additional resources outside of the program. * If the input is your starting string, your program must return "William Hartnell", the first name on the list. + You should select and document any string you wish to use as the starting string, as long as it isn't the name of a listed actor. My example below uses an empty string. * If the input string is an actor's name (other than the last), your program must return the next name on the list following the name inputted. * For any other inputs, behavior of your program is undefined. * The list of actors below is incomplete. You must complete the list by selecting 13 more names of actors you feel would be good at playing The Doctor. + Each extra name must be of a professional actor with an IMDB page. + The extra names returned by your program must be the actors' names exactly as listed on IMDB, including case, accents and diacritics. + The completed list of 26 actors must be 26 distinct individuals with distinct names. * You may interpret input and output according to the constraints of your language's execution environment. (Parameters, quotes, end-of-lines, stdin/out, encoding etc.) * Shortest conforming program wins. Normal code-golf rules apply. * You may use someone else's list of actors. If you do, give appropriate credit and share the glory. (Finding a list of actors that would compress well might be part of the challenge.) The first half of the list of names is as follows. These strings must be output exactly as shown, preserving case including the extra capital letter in "McCoy" and "McGann". ``` William Hartnell Patrick Troughton Jon Pertwee Tom Baker Peter Davison Colin Baker Sylvester McCoy Paul McGann John Hurt Christopher Eccleston David Tennant Matt Smith Peter Capaldi ``` **For example:** ``` YourProgram("") returns "William Hartnell". YourProgram("William Hartnell") returns "Patrick Troughton". YourProgram("Patrick Troughton") returns "Jon Pertwee". /* 10 more. */ YourProgram("Peter Capaldi") returns "Pauley Perrette". YourProgram("Pauley Perrette") returns "Nathan Fillion". /* 12 more. */ ``` [Answer] ## Python 2, 340 bytes ``` #coding:L1 import zlib;r=zlib.decompress("x5mÂ@¯Â 8]c]u×Xã-q1H5½ýRãþ#÷O³PÌsÆ=¹IºÁÑêx¼*~W=¿ñX ,èÆ{v6ø¢§<⦩Yô³é¦üäǼݥ¦NAs+Ò5(´£96ÉÃë}»eJ9>3óz8²*©ãÜ¡+âÃG®¡;å^pY\nÁ|þ7Ü9¿\"®ICmYXqÁʽ$f,g¶3yÞ!ZéûfÇñÑTU¶ Û\r[M8̨põ)ËåÂxïѬLÂÜlßÜ\nwI×+nX`£åep;·ûÃVÿ À]b").split('.');print r[r.index(input())+1] ``` The encoding is Latin-1 (aka ISO-8859-1). That first line is important because Python 2 doesn't like non-ASCII characters in files by default (and using Python 3 wouldn't help, because it expects UTF-8 by default, along with loads of other issues). Takes quoted input (single and double both work), with the initial input as the empty string (`''`). The strategy I used was constructing a list of period-separated names (starting with an empty string) and compressing it with zlib (which gave better results over both shoco and lzma). This program decompresses that list, splits it on periods, and outputs the element in the list that follows the input. I didn't use any real strategy with choosing the next 13 actors, other than picking living British actors (sorry, Alan Rickman, you would've been great) that I liked who haven't played a Doctor yet. The rationale was, the character distribution in the first 13 names is fairly random (as far as names go), so it's unlikely (in my opinion) that 13 more names could be picked that would make a significant difference in compressed size. For reference, the list I used (with an extra linebreak to separate the new actors): ``` William Hartnell Patrick Troughton Jon Pertwee Tom Baker Peter Davison Colin Baker Sylvester McCoy Paul McGann John Hurt Christopher Eccleston David Tennant Matt Smith Peter Capaldi Emma Watson Patrick Stewart Ian McKellen Benedict Cumberbatch Tom Hiddleston Sean Connery Hugh Laurie Daniel Radcliffe Rupert Grint Gary Oldman Simon Pegg Keira Knightley Liam Neeson ``` ]
[Question] [ Disclaimer: This challenge is *extremely* scientifically inaccurate. ;) Given an input of a list of molecules, output what the result would be if they were to all combine via dehydration synthesis, if possible. For the purposes of this challenge, although this description is inaccurate, a [dehydration reaction](https://en.wikipedia.org/wiki/Dehydration_reaction) between two molecules is performed as follows: 1. Remove `OH` (one oxygen and one hydrogen atom) from either of the two molecules. 2. Remove `H` (a single hydrogen atom) from the other one. 3. Combine the two molecules into one. For instance, combining two `C6H12O6` molecules via dehydration synthesis would result in `C12H22O11`. Note that there are two less `H`s and one less `O` in the product than in the reactants. (These missing parts would form `H2O`, hence "dehydration," but that's irrelevant to this challenge.) An example of molecules that cannot be combined via dehydration synthesis is `C6H12O6` + `CO2`. The required amount of hydrogen and oxygen is present, but neither `OH` nor `H` can be taken from the `CO2`. The format of the input for each molecule is a list of atoms concatenated. An atom is always a single capital letter, possibly followed by a single lowercase letter (you don't have to handle atoms like `Uuo`). Atoms may also have integers ≥ 2 after them, representing how many of them there are; if this number is not present, it is assumed to be 1. Atoms will never be repeated within the same molecule. Input may be provided as either an array/list/etc. of strings, or a single string separated by any non-alphanumeric character. Output must be a single string, but the output for "invalid input" (i.e. a list of molecules that cannot be combined via dehydration synthesis) may be any string containing at least one non-alphanumeric character (to distinguish from valid output). The order of the atoms in the output does not matter. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win. Test cases (invalid output is represented here by an asterisk `*`): ``` In Out ------------------------------------------------------------------ C6H12O6 C6H12O6 C6H12O6 C6H12O6 C6H12O6 C6H12O6 | C36H62O31 CHO5 CH2 CH2 CH2 CH2 CH2 | C6H CHO4 CH2 CH2 CH2 CH2 CH2 | * H H H CH3O3 | C H H H CH4O2 | * C6H12O6 ABCDELMNOP C6H12O6 | * HO HO HO H3 | <empty string> HgO4 C6H12O6 | * HgHO4 C6H12O6 | HgH11O9C6 PdZnXeRaHO KrArKRbFH | PdZnXeRaKrArKRbF ``` [Answer] # Pyth (95 chars) After seeing tiny, unreadable programs in CJam, Jelly, and Pyth, I decided to learn a golfing language, and because I am familiar with Python, I learned Pyth. Here is my code to solve this question: ``` FNQ aY.dm.Dd0:N"([A-Z][a-z]*)(\d*)"4;FNYFkN XkH|s@Nk1; X"O"HJ-1lQ; X"H"H*2J;FNHI@HNpNI>@HN1p@HN ``` The method that I have used to combine the molecules is similar to the one that I have used above implemented in Python. Here is a breakdown of that happens, statement by statement, character by character. ``` FNQ For N in Q (input): m Map (same as python map()) .Dd0 Function for removing first element :N"([A-Z][a-z]*)(\d*)"4; Get array of matches & groups .d Convert to dict aY Append to Y (pre-defined as an array) FNY For N in Y: FkN For K in N: XkH Increment/set H[k] (H pre-defined as a dict) to the following value |s@Nk1; if N[k] is null, then 1; else int(N[k]) X"O"HJ-1lQ; Decrement H["O"] by length of Q - 1, and set J to length of Q - 1 X"H"H*2J; Decrement H["H"] by 2 * J FNH For N in H: I@HN If H[N] (!= 0): pN Print N I>@HN1 If H[N] > 1: p@HN Print H[N] ``` [Test it!](https://pyth.herokuapp.com/?code=FNQ+aY.dm.Dd0%3AN%22%28%5BA-Z%5D%5Ba-z%5D*%29%28%5Cd*%29%224%3BFNYFkN+XkH%7Cs%40Nk1%3B+X%22O%22HJ-1lQ%3B+X%22H%22H*2J%3BFNHI%40HNpNI%3E%40HN1p%40HN&input=%5B%22C6H12O6%22%2C+%22HgHO4%22%5D&debug=0) Note: The spaces in the code are for suppressing outputs. [Answer] # Python (337 336 chars) ``` import re i=input().split() a,d,o,e=[],{},"",len(i)-1 for b in i:a.append(dict(re.findall(r"([A-Z][a-z]*)(\d*)",b))) a=[{b:int(c[b])if c[b]else 1for b in c}for c in a] for b in a: for c in b:d[c]=c in d and d[c]+b[c]or b[c] if"H"not in b:d["-"]=0 d["H"]-=2*e;d["O"]-=e for b in d:o+=b+(str(d[b])if d[b]-1else"")if d[b]else"" print(o) ``` Here is an example of how to use this program: ``` sh3.14$ python dehydrate.py <-Run the program C6H12O6 HgHO4 <-Input O9H11C6Hg <-Output ``` [Try it!](https://repl.it/Bx5D/0) ]
[Question] [ Isn't it annoying when you're working with floating point numbers and your code doesn't work because two numbers are not equal by the least significant bit? Now you can fix that! Write some code that takes two floating point numbers in any [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point) binary format and returns `TRUE` if: * the two numbers are exactly equal * for two positive numbers: adding the value of the least significant bit to the smaller number makes it exactly equal to the larger value * for two negative numbers: subtracting the value of the least significant bit from the larger number makes it exactly equal to the smaller value Return `FALSE` if: * any other case IEEE 754 allows both positive and negative zero. Treat all zeros as the sign of the other non-zero number. IEEE 754 defines `0 === -0`. You can enter the numbers as text only if the binary representation in memory is accurate to the least significant bit. ### Test Data The test data will vary slightly, depending on exactly which format your language uses. The table below shows the bit representation, followed by how to calculate the value, since most values will be impractical to directly input. A value such as `-1.5b-3` means -1.5 x 2-3. Your code must be able to handle every format your language supports: * binary16 (Half precision) * binary32 (Single precision) * binary64 (Double precision) * binary128 (Quadruple precision) If you are supporting any format other than binary64, expand or contract the bit patterns from the test data to their equivalents. If your language doesn't natively support IEEE 754 at all, you may import an external library at no cost that fully implements at least one IEEE 754 binary format, but with no extra functions, i.e. you can't put your own function in the included library. IEEE 754 binary64 (Double precision): Zero and Subnormals: ``` 0 00000000000 0000000000000000000000000000000000000000000000000000 (0) 0 00000000000 0000000000000000000000000000000000000000000000000001 (1b-1074) TRUE 0 00000000000 0000000000000000000000000000000000000000000000000001 (1b-1074) 0 00000000000 0000000000000000000000000000000000000000000000000010 (1b-1073) TRUE 0 00000000000 0000000000000000000000000000000000000000000000000000 (0) 0 00000000000 0000000000000000000000000000000000000000000000000010 (1b-1073) FALSE 0 00000000000 0000000000000000000000000000000000000000000000000111 (1.75b-1072) 0 00000000000 0000000000000000000000000000000000000000000000001000 (1b-1071) TRUE 0 00000000000 0000000000000000000000000000000000000000000000000000 (0) 1 00000000000 0000000000000000000000000000000000000000000000000001 (-1b-1074) TRUE 1 00000000000 0000000000000000000000000000000000000000000000000001 (-1b-1074) 1 00000000000 0000000000000000000000000000000000000000000000000010 (-1b-1073) TRUE 0 00000000000 0000000000000000000000000000000000000000000000000000 (0) 1 00000000000 0000000000000000000000000000000000000000000000000010 (-1b-1073) FALSE 0 00000000000 0000000000000000000000000000000000000000000000000001 (1b-1074) 1 00000000000 0000000000000000000000000000000000000000000000000001 (-1b-1074) FALSE ``` Normalised numbers: ``` 0 01111111111 0000000000000000000000000000000000000000000000000000 (1) 0 01111111111 0000000000000000000000000000000000000000000000000010 (1 + 1b-51) FALSE 0 01111111111 0000000000000000000000000000000000000000000000000000 (1) 0 01111111111 0000000000000000000000000000000000000000000000000001 (1 + 1b-52) TRUE 0 01111111111 0000000000000000000000000000000000000000000000000000 (1) 0 01111111111 0000000000000000000000000000000000000000000000000000 (1) TRUE 0 01111111111 0000000000000000000000000000000000000000000000000000 (1) 0 01111111110 1111111111111111111111111111111111111111111111111111 (1 - 1b-53) TRUE 0 01111111111 0000000000000000000000000000000000000000000000000000 (1) 0 01111111110 1111111111111111111111111111111111111111111111111110 (1 - 1b-52) FALSE 0 01111111111 0000000000000000000000000000000000000000000000000000 (1) 0 01111111110 0000000000000000000000000000000000000000000000000000 (0.5) FALSE 0 10000010101 1111111111111111111111111111111111111111111111111110 (16777216 - 1b-28) 0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216) FALSE 0 10000010101 1111111111111111111111111111111111111111111111111111 (16777216 - 1b-29) 0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216) TRUE 0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216) 0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216) TRUE 0 10000010110 0000000000000000000000000000000000000000000000000001 (16777216 + 1b-28) 0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216) TRUE 0 10000010110 0000000000000000000000000000000000000000000000000010 (16777216 + 1b-27) 0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216) FALSE 1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3) 1 01111111101 0101010101010101010101010101010101010101010101010111 (-1 / 3 - 1b-53) FALSE 1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3) 1 01111111101 0101010101010101010101010101010101010101010101010110 (-1 / 3 - 1b-54) TRUE 1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3) 1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3) TRUE 1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3) 1 01111111101 0101010101010101010101010101010101010101010101010100 (-1 / 3 + 1b-54) TRUE 1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3) 1 01111111101 0101010101010101010101010101010101010101010101010011 (-1 / 3 + 1b-53) FALSE 1 11111111110 1111111111111111111111111111111111111111111111111111 (-1b1024 + 1b971) 1 11111111110 1111111111111111111111111111111111111111111111111111 (-1b1024 + 1b971) TRUE 1 11111111110 1111111111111111111111111111111111111111111111111111 (-1b1024 + 1b971) 1 11111111110 1111111111111111111111111111111111111111111111111110 (-1b1024 + 1b970) TRUE 1 11111111110 1111111111111111111111111111111111111111111111111111 (-1b1024 + 1b971) 1 11111111110 1111111111111111111111111111111111111111111111111101 (-1b1024 + 1.5b970) FALSE ``` Infinity and Not A Number: ``` X 11111111111 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX INF INF TRUE INF Any other value FALSE -INF -INF TRUE -INF Any other value FALSE NAN Any value, including NAN FALSE ``` ### Scoring Number of bytes - (number of bytes needed for IEEE 754 library `include`, if an external library is used) [Answer] # C++14 using IEEE754 platform, 17 + 49 = 66 bytes Includes, 17 bytes: ``` #include <cmath> ``` Lambda expression, 49 bytes: ``` [](auto a,auto b){return b==std::nextafter(a,b);} ``` ]
[Question] [ Write a program or function to estimate as closely as possible the number of syllables in English words. The input list is here: [1000 basic English words](http://pastebin.com/wh6yxrqp). There are only 997 words because a few duplicates were removed. For each word, output a line containing the word, a comma (`,`), and the number of syllables and no other characters except for new-line, e.g. `photograph,3` (pho-to-graph). Use the code snippet below to score your answer. Paste your code and output into the respective boxes and press the "Submit" button. ### Scoring All scoring is calculated automatically by the snippet, but here is how it works in order to lower your score: * 60 points for each byte, however if you don't use any Unicode codepoints above U+00FF the snippet will calculate characters instead of bytes * Each word where the number of syllables is correct will score 0 Scoring table for wrong syllables. The axes are symmetrical, one is the number of wrong syllables per word, and the other is the number of words with that number of syllables wrong: ``` | 1| 2| 3| 4| … -+--+--+--+--+-- 1| 1| 3| 6|10| -+--+--+--+--+-- 2| 3| 9|18|30| -+--+--+--+--+-- 3| 6|18|36|60| -+--+--+--+--+-- 4|10|30|60|100 -+--+--+--+--+-- …| | | | | ``` * If you have 200 words with 1 wrong syllable and 100 words with 2 wrong syllables your score for wrong syllables will be `200*201/2 * 1*2/2 + 100*101/2 * 2*3/2` = `20100 * 1 + 5050 * 3` = `20100 + 15150` = `35250` * The scoring is designed to make it easy to lower your score when you have a lot of wrong syllables but hard when you only have a few * Duplicate words in your output will **not** be removed. Outputting `photograph,1`, `photograph,2`, `photograph,3` will simply increase your score * Post all three scores, Code, Word and Total. The Total Score will be used to determine a winner You can use the code snippet to see how many syllables are expected for each word. Simply run it with no input and it will output the list in the expected format, as well as all the words where the number of syllables is wrong, e.g. `photograph *1, (3)`. ``` var syl = { "a": 1, "about": 2, "above": 2, "across": 2, "act": 1, "active": 2, "activity": 4, "add": 1, "afraid": 2, "after": 2, "again": 2, "age": 1, "ago": 2, "agree": 2, "air": 1, "all": 1, "alone": 2, "along": 2, "already": 3, "always": 2, "am": 1, "amount": 2, "an": 1, "and": 1, "angry": 2, "another": 3, "answer": 2, "any": 2, "anyone": 3, "anything": 3, "anytime": 3, "appear": 3, "apple": 2, "are": 1, "area": 3, "arm": 1, "army": 2, "around": 2, "arrive": 2, "art": 1, "as": 1, "ask": 1, "at": 1, "attack": 2, "aunt": 1, "autumn": 2, "away": 2, "baby": 2, "back": 1, "bad": 1, "bag": 1, "ball": 1, "bank": 1, "base": 1, "basket": 2, "bath": 1, "be": 1, "bean": 1, "bear": 1, "beautiful": 3, "bed": 1, "bedroom": 2, "beer": 2, "before": 2, "begin": 2, "behave": 2, "behind": 2, "bell": 1, "below": 2, "besides": 2, "best": 1, "better": 2, "between": 2, "big": 1, "bird": 1, "birth": 1, "birthday": 2, "bit": 1, "bite": 1, "black": 1, "bleed": 1, "block": 1, "blood": 1, "blow": 1, "blue": 1, "board": 1, "boat": 1, "body": 2, "boil": 2, "bone": 1, "book": 1, "border": 2, "born": 1, "borrow": 2, "both": 1, "bottle": 2, "bottom": 2, "bowl": 1, "box": 1, "boy": 1, "branch": 1, "brave": 1, "bread": 1, "break": 1, "breakfast": 2, "breathe": 1, "bridge": 1, "bright": 1, "bring": 1, "brother": 2, "brown": 1, "brush": 1, "build": 1, "burn": 1, "bus": 1, "business": 2, "busy": 2, "but": 1, "buy": 1, "by": 1, "cake": 1, "call": 1, "can": 1, "candle": 2, "cap": 1, "car": 1, "card": 1, "care": 1, "careful": 2, "careless": 2, "carry": 2, "case": 1, "cat": 1, "catch": 1, "central": 2, "century": 3, "certain": 2, "chair": 1, "chance": 1, "change": 1, "chase": 1, "cheap": 1, "cheese": 1, "chicken": 2, "child": 1, "children": 2, "chocolate": 2, "choice": 1, "choose": 1, "circle": 2, "city": 2, "class": 1, "clean": 1, "clear": 2, "clever": 2, "climb": 1, "clock": 1, "close": 1, "cloth": 1, "clothes": 1, "cloud": 1, "cloudy": 2, "coat": 1, "coffee": 2, "coin": 1, "cold": 1, "collect": 2, "colour": 2, "comb": 1, "come": 1, "comfortable": 3, "common": 2, "compare": 2, "complete": 2, "computer": 3, "condition": 3, "contain": 2, "continue": 3, "control": 2, "cook": 1, "cool": 1, "copper": 2, "corn": 1, "corner": 2, "correct": 2, "cost": 1, "count": 1, "country": 2, "course": 1, "cover": 2, "crash": 1, "cross": 1, "cry": 1, "cup": 1, "cupboard": 2, "cut": 1, "dance": 1, "dangerous": 3, "dark": 1, "daughter": 2, "day": 1, "dead": 1, "decide": 2, "decrease": 2, "deep": 1, "deer": 2, "depend": 2, "desk": 1, "destroy": 2, "develop": 3, "die": 1, "different": 2, "difficult": 3, "dinner": 2, "direction": 3, "dirty": 2, "discover": 3, "dish": 1, "do": 1, "dog": 1, "door": 1, "double": 2, "down": 1, "draw": 1, "dream": 1, "dress": 1, "drink": 1, "drive": 1, "drop": 1, "dry": 1, "duck": 1, "dust": 1, "duty": 2, "each": 1, "ear": 2, "early": 2, "earn": 1, "earth": 1, "east": 1, "easy": 2, "eat": 1, "education": 4, "effect": 2, "egg": 1, "eight": 1, "either": 2, "electric": 3, "elephant": 3, "else": 1, "empty": 2, "end": 1, "enemy": 3, "enjoy": 2, "enough": 2, "enter": 2, "entrance": 2, "equal": 2, "escape": 2, "even": 2, "evening": 2, "event": 2, "ever": 2, "every": 2, "everybody": 4, "everyone": 3, "exact": 2, "examination": 5, "example": 3, "except": 2, "excited": 3, "exercise": 3, "expect": 2, "expensive": 3, "explain": 2, "extremely": 3, "eye": 1, "face": 1, "fact": 1, "fail": 2, "fall": 1, "false": 1, "family": 2, "famous": 2, "far": 1, "farm": 1, "fast": 1, "fat": 1, "father": 2, "fault": 1, "fear": 2, "feed": 1, "feel": 2, "female": 3, "fever": 2, "few": 1, "fight": 1, "fill": 1, "film": 1, "find": 1, "fine": 1, "finger": 2, "finish": 2, "fire": 2, "first": 1, "fit": 1, "five": 1, "fix": 1, "flag": 1, "flat": 1, "float": 1, "floor": 1, "flour": 2, "flower": 2, "fly": 1, "fold": 1, "food": 1, "fool": 1, "foot": 1, "football": 2, "for": 1, "force": 1, "foreign": 2, "forest": 2, "forget": 2, "forgive": 2, "fork": 1, "form": 1, "four": 1, "fox": 1, "free": 1, "freedom": 2, "freeze": 1, "fresh": 1, "friend": 1, "friendly": 2, "from": 1, "front": 1, "fruit": 1, "full": 1, "fun": 1, "funny": 2, "furniture": 3, "further": 2, "future": 2, "game": 1, "garden": 2, "gate": 1, "general": 2, "gentleman": 3, "get": 1, "gift": 1, "give": 1, "glad": 1, "glass": 1, "go": 1, "goat": 1, "god": 1, "gold": 1, "good": 1, "goodbye": 2, "grandfather": 3, "grandmother": 3, "grass": 1, "grave": 1, "great": 1, "green": 1, "grey": 1, "ground": 1, "group": 1, "grow": 1, "gun": 1, "hair": 1, "half": 1, "hall": 1, "hammer": 2, "hand": 1, "happen": 2, "happy": 2, "hard": 1, "hat": 1, "hate": 1, "have": 1, "he": 1, "head": 1, "healthy": 2, "hear": 2, "heart": 1, "heaven": 2, "heavy": 2, "height": 1, "hello": 2, "help": 1, "hen": 1, "her": 1, "here": 2, "hers": 1, "hide": 1, "high": 1, "hill": 1, "him": 1, "his": 1, "hit": 1, "hobby": 2, "hold": 1, "hole": 1, "holiday": 3, "home": 1, "hope": 1, "horse": 1, "hospital": 3, "hot": 1, "hotel": 2, "hour": 2, "house": 1, "how": 1, "hundred": 2, "hungry": 2, "hurry": 2, "hurt": 1, "husband": 2, "I": 1, "ice": 1, "idea": 3, "if": 1, "important": 3, "in": 1, "increase": 2, "inside": 2, "into": 2, "introduce": 3, "invent": 2, "invite": 2, "iron": 2, "is": 1, "island": 2, "it": 1, "its": 1, "jelly": 2, "job": 1, "join": 1, "juice": 1, "jump": 1, "just": 1, "keep": 1, "key": 1, "kill": 1, "kind": 1, "king": 1, "kitchen": 2, "knee": 1, "knife": 1, "knock": 1, "know": 1, "ladder": 2, "lady": 2, "lamp": 1, "land": 1, "large": 1, "last": 1, "late": 1, "lately": 2, "laugh": 1, "lazy": 2, "lead": 1, "leaf": 1, "learn": 1, "leave": 1, "left": 1, "leg": 1, "lend": 1, "length": 1, "less": 1, "lesson": 2, "let": 1, "letter": 2, "library": 2, "lie": 1, "life": 1, "light": 1, "like": 1, "lion": 2, "lip": 1, "list": 1, "listen": 2, "little": 2, "live": 1, "lock": 1, "lonely": 2, "long": 1, "look": 1, "lose": 1, "lot": 1, "love": 1, "low": 1, "lower": 2, "luck": 1, "machine": 2, "main": 1, "make": 1, "male": 2, "man": 1, "many": 2, "map": 1, "mark": 1, "market": 2, "marry": 2, "matter": 2, "may": 1, "me": 1, "meal": 2, "mean": 1, "measure": 2, "meat": 1, "medicine": 3, "meet": 1, "member": 2, "mention": 2, "method": 2, "middle": 2, "milk": 1, "million": 2, "mind": 1, "minute": 2, "miss": 1, "mistake": 2, "mix": 1, "model": 2, "modern": 2, "moment": 2, "money": 2, "monkey": 2, "month": 1, "moon": 1, "more": 1, "morning": 2, "most": 1, "mother": 2, "mountain": 2, "mouth": 1, "move": 1, "much": 1, "music": 2, "must": 1, "my": 1, "name": 1, "narrow": 2, "nation": 2, "nature": 2, "near": 2, "nearly": 2, "neck": 1, "need": 1, "needle": 2, "neighbour": 2, "neither": 2, "net": 1, "never": 2, "new": 1, "news": 1, "newspaper": 3, "next": 1, "nice": 1, "night": 1, "nine": 1, "no": 1, "noble": 2, "noise": 1, "none": 1, "nor": 1, "north": 1, "nose": 1, "not": 1, "nothing": 2, "notice": 2, "now": 1, "number": 2, "obey": 2, "object": 2, "ocean": 2, "of": 1, "off": 1, "offer": 2, "office": 2, "often": 2, "oil": 2, "old": 1, "on": 1, "one": 1, "only": 2, "open": 2, "opposite": 3, "or": 1, "orange": 2, "order": 2, "other": 2, "our": 2, "out": 1, "outside": 2, "over": 2, "own": 1, "page": 1, "pain": 1, "paint": 1, "pair": 1, "pan": 1, "paper": 2, "parent": 2, "park": 1, "part": 1, "partner": 2, "party": 2, "pass": 1, "past": 1, "path": 1, "pay": 1, "peace": 1, "pen": 1, "pencil": 2, "people": 2, "pepper": 2, "per": 1, "perfect": 2, "period": 3, "person": 2, "petrol": 2, "photograph": 3, "piano": 3, "pick": 1, "picture": 2, "piece": 1, "pig": 1, "pin": 1, "pink": 1, "place": 1, "plane": 1, "plant": 1, "plastic": 2, "plate": 1, "play": 1, "please": 1, "pleased": 1, "plenty": 2, "pocket": 2, "point": 1, "poison": 2, "police": 1, "polite": 2, "pool": 1, "poor": 1, "popular": 3, "position": 3, "possible": 3, "potato": 3, "pour": 1, "power": 2, "present": 2, "press": 1, "pretty": 2, "prevent": 2, "price": 1, "prince": 1, "prison": 2, "private": 2, "prize": 1, "probably": 3, "problem": 2, "produce": 2, "promise": 2, "proper": 2, "protect": 2, "provide": 2, "public": 2, "pull": 1, "punish": 2, "pupil": 2, "push": 1, "put": 1, "queen": 1, "question": 2, "quick": 1, "quiet": 2, "quite": 1, "radio": 3, "rain": 1, "rainy": 2, "raise": 1, "reach": 1, "read": 1, "ready": 2, "real": 2, "really": 2, "receive": 2, "record": 2, "red": 1, "remember": 3, "remind": 2, "remove": 2, "rent": 1, "repair": 2, "repeat": 2, "reply": 2, "report": 2, "rest": 1, "restaurant": 2, "result": 2, "return": 2, "rice": 1, "rich": 1, "ride": 1, "right": 1, "ring": 1, "rise": 1, "road": 1, "rob": 1, "rock": 1, "room": 1, "round": 1, "rubber": 2, "rude": 1, "rule": 1, "ruler": 2, "run": 1, "rush": 1, "sad": 1, "safe": 1, "sail": 2, "salt": 1, "same": 1, "sand": 1, "save": 1, "say": 1, "school": 1, "science": 2, "scissors": 2, "search": 1, "seat": 1, "second": 2, "see": 1, "seem": 1, "sell": 1, "send": 1, "sentence": 2, "serve": 1, "seven": 2, "several": 2, "sex": 1, "shade": 1, "shadow": 2, "shake": 1, "shape": 1, "share": 1, "sharp": 1, "she": 1, "sheep": 1, "sheet": 1, "shelf": 1, "shine": 1, "ship": 1, "shirt": 1, "shoe": 1, "shoot": 1, "shop": 1, "short": 1, "should": 1, "shoulder": 2, "shout": 1, "show": 1, "sick": 1, "side": 1, "signal": 2, "silence": 2, "silly": 2, "silver": 2, "similar": 3, "simple": 2, "since": 1, "sing": 1, "single": 2, "sink": 1, "sister": 2, "sit": 1, "six": 1, "size": 1, "skill": 1, "skin": 1, "skirt": 1, "sky": 1, "sleep": 1, "slip": 1, "slow": 1, "small": 1, "smell": 1, "smile": 2, "smoke": 1, "snow": 1, "so": 1, "soap": 1, "sock": 1, "soft": 1, "some": 1, "someone": 2, "something": 2, "sometimes": 2, "son": 1, "soon": 1, "sorry": 2, "sound": 1, "soup": 1, "south": 1, "space": 1, "speak": 1, "special": 2, "speed": 1, "spell": 1, "spend": 1, "spoon": 1, "sport": 1, "spread": 1, "spring": 1, "square": 1, "stamp": 1, "stand": 1, "star": 1, "start": 1, "station": 2, "stay": 1, "steal": 2, "steam": 1, "step": 1, "still": 1, "stomach": 1, "stone": 1, "stop": 1, "store": 1, "storm": 1, "story": 2, "strange": 1, "street": 1, "strong": 1, "structure": 2, "student": 2, "study": 2, "stupid": 2, "subject": 2, "substance": 2, "successful": 3, "such": 1, "sudden": 2, "sugar": 2, "suitable": 3, "summer": 2, "sun": 1, "sunny": 2, "support": 2, "sure": 1, "surprise": 2, "sweet": 1, "swim": 1, "sword": 1, "table": 2, "take": 1, "talk": 1, "tall": 1, "taste": 1, "taxi": 2, "tea": 1, "teach": 1, "team": 1, "tear": [1, 2], "telephone": 3, "television": 4, "tell": 1, "ten": 1, "tennis": 2, "terrible": 3, "test": 1, "than": 1, "that": 1, "the": 1, "their": 1, "then": 1, "there": 1, "therefore": 2, "these": 1, "thick": 1, "thin": 1, "thing": 1, "think": 1, "third": 1, "this": 1, "though": 1, "threat": 1, "three": 1, "tidy": 2, "tie": 1, "title": 2, "to": 1, "today": 2, "toe": 1, "together": 3, "tomorrow": 3, "tonight": 2, "too": 1, "tool": 1, "tooth": 1, "top": 1, "total": 2, "touch": 1, "town": 1, "train": 1, "tram": 1, "travel": 2, "tree": 1, "trouble": 2, "true": 1, "trust": 1, "try": 1, "turn": 1, "twice": 1, "type": 1, "uncle": 2, "under": 2, "understand": 3, "unit": 2, "until": 2, "up": 1, "use": 1, "useful": 2, "usual": 2, "usually": 3, "vegetable": 3, "very": 2, "village": 2, "visit": 2, "voice": 1, "wait": 1, "wake": 1, "walk": 1, "want": 1, "warm": 1, "wash": 1, "waste": 1, "watch": 1, "water": 2, "way": 1, "we": 1, "weak": 1, "wear": 1, "weather": 2, "wedding": 2, "week": 1, "weight": 1, "welcome": 2, "well": 1, "west": 1, "wet": 1, "what": 1, "wheel": 2, "when": 1, "where": 1, "which": 1, "while": 2, "white": 1, "who": 1, "why": 1, "wide": 1, "wife": 1, "wild": 2, "will": 1, "win": 1, "wind": 1, "window": 2, "wine": 1, "winter": 2, "wire": 2, "wise": 1, "wish": 1, "with": 1, "without": 2, "woman": 2, "wonder": 2, "word": 1, "work": 1, "world": 1, "worry": 2, "worst": 1, "write": 1, "wrong": 1, "year": 2, "yes": 1, "yesterday": 3, "yet": 1, "you": 1, "young": 1, "your": 1, "zero": 2, "zoo": 1 }; function checkcode(e) { var t = document.getElementById('words').value; var re = new RegExp(/^(\w+),(\d+)/gm); var lines = t.match(re); re = new RegExp(/^(\w+),(\d+)/); if (!lines) { lines = []; } var keys = JSON.parse(JSON.stringify(syl)); var tally = []; var wrong = []; for (i = 0; i < lines.length; ++i) { var num = lines[i].match(re); if (num[1] in syl) { var res = num[1] !== "tear"? Math.abs(syl[num[1]] - num[2]): Math.min(Math.abs(syl[num[1]][0] - num[2]), Math.abs(syl[num[1]][1] - num[2])); if (!(res in tally)) { tally[res] = 0; } ++tally[res]; if (res) { wrong.push(num[1] + " *" + num[2] + ", (" + syl[num[1]] + ")"); } delete(keys[num[1]]); } } for (i in keys) { if (!(keys[i] in tally)) { tally[keys[i]] = 0; } ++tally[keys[i]]; } var score = 0; for (i = 0; i < tally.length; ++i) { if (i in tally) { score += i * (i + 1) * tally[i] * (tally[i] + 1) / 4; } } var missing = 0; var missinglist = [] for (i in keys) { missinglist.push(i + "," + keys[i]); ++missing; } codescore = document.getElementById("code").value.length; codescore = document.getElementById("code").value; if (codescore.match(/[^\u0000-\u00FF]/)) { cs1 = codescore.match(/[\u0000-\u007F]/g); cs2 = codescore.match(/[\u0080-\u07FF]/g); cs3 = codescore.match(/[\u0800-\uFFFF]/g); codescore = (cs1? cs1.length: 0) + (cs2? cs2.length * 2: 0) + (cs3? cs3.length * 3: 0); } else { codescore = codescore.length; } codescore *= 60; document.getElementById("result").value = "Code score: " + codescore + "\nWord score: " + score + "\nTotal score: " + (codescore + score) + "\nValid lines: " + lines.length + "\nMissing words: " + missing + "\n\nMissing words:\n" + missinglist.join("\n") + "\n\nWrong number:\n" + wrong.join("\n"); } ``` ``` textarea { width: 320px; height: 480px; } textarea#code { width: 650px; height: 80px; } span { display: inline-block; } ``` ``` <span>Code:<br/> <textarea id="code"> </textarea></span><br/> <span>Output:<br/> <textarea id="words"> </textarea></span> <span>Score:<br/><textarea id="result" disabled="disabled"> </textarea></span><br/> <input type="submit" onclick="checkcode(this)"/> ``` The variant of English used for the syllables is Australian English, spoken slower than usual. There is one word in the list that has two pronunciations with different numbers of syllables: `tear` to rip, 1 syllable; and water from the eye, 2 syllables (te-ar). Either `tear,1` or `tear,2` is correct for this word. I have gone through the whole list twice, but there might be some errors. Please don't complain that a particular word has a different number of syllables in British, American, etc. English. I will only make changes to the expected number of syllables if I agree that the number of syllables is wrong in Australian English. Standard Code Golf rules with custom scoring. [Answer] # Ruby, 5160 code + 4008 words = 9168 ``` ->l{l.lines{|w|print w.chop,?,,w.sub("e\n","").tr_s('aeiouy','******').count('*'),$/}} ``` Anonymous function. Expects as an argument all the words in a single string, newline separated, (as direct from pastebin.) Requires a trailing newline in order to print `zoo` correctly (can be fixed for 1 byte if required.) **ungolfed** ``` f=->l{ #Lambda assigned to varible f. Call as f[list] l.lines{|w| #for each line, complete with newline print w.chop,?,, #print the word with the newline removed, and a comma, and the following: w.sub("e\n",""). #Take the word. If there is an (e and newline) at the end remove them tr_s('aeiouy','******'). #convert all vowel clusters to a single * count('*'), #and count the stars $/ #finally print a newline ($/ is a special variable holding the line separator, newline by default.) } } ``` **wrong words** About twice as many as Legionmamma's mathematica answer. I've marked 3 common and easy to fix errors. Whether difference in code length is worth it is another matter. I might get back to this later. ``` anyone *2, (3) appear *2, (3) apple *1, (2) #A consonant+le ending (19 incidences) area *2, (3) be *0, (1) #B words must have at least one syllable (7 incidences) beer *1, (2) besides *3, (2) #C es ending (3 incidences) boil *1, (2) bottle *1, (2) #A business *3, (2) candle *1, (2) #A careful *3, (2) careless *3, (2) chocolate *3, (2) circle *1, (2) #A clear *1, (2) clothes *2, (1) #C deer *1, (2) different *3, (2) double *1, (2) #A ear *1, (2) evening *3, (2) every *3, (2) everybody *5, (4) example *2, (3) #A extremely *4, (3) fail *1, (2) family *3, (2) fear *1, (2) feel *1, (2) female *2, (3) fire *1, (2) flour *1, (2) general *3, (2) he *0, (1) #B hear *1, (2) here *1, (2) hour *1, (2) I *0, (1) #B idea *2, (3) lately *3, (2) library *3, (2) lion *1, (2) little *1, (2) #A lonely *3, (2) male *1, (2) me *0, (1) #B meal *1, (2) middle *1, (2) #A near *1, (2) needle *1, (2) #A noble *1, (2) #A oil *1, (2) our *1, (2) people *1, (2) #A period *2, (3) piano *2, (3) pleased *2, (1) police *2, (1) possible *2, (3) quiet *1, (2) radio *2, (3) real *1, (2) restaurant *3, (2) sail *1, (2) science *1, (2) several *3, (2) she *0, (1) #B simple *1, (2) #A single *1, (2) #A smile *1, (2) something *3, (2) sometimes *4, (2) #C steal *1, (2) stomach *2, (1) suitable *2, (3) #A table *1, (2) #A terrible *2, (3) #A the *0, (1) #B therefore *3, (2) title *1, (2) #A trouble *1, (2) #A uncle *1, (2) #A useful *3, (2) we *0, (1) #B wheel *1, (2) while *1, (2) wild *1, (2) wire *1, (2) year *1, (2) ``` [Answer] # Mathematica, score 4560 (code) + 1128 (words) = 5688 (total) ``` ""<>({#,",",ToString@Length[#~WordData~"Hyphenation"]," "}&/@StringSplit@#)& ``` Anonymous function. Uses Mathematica's built-in `WordData`. For reference, here are the incorrect words (some of which I disagree with): ``` appear *2, (3) beer *1, (2) boil *1, (2) chocolate *3, (2) clear *1, (2) colour *1, (2) comfortable *4, (3) deer *1, (2) different *3, (2) ear *1, (2) fail *1, (2) family *3, (2) fear *1, (2) feel *1, (2) female *2, (3) fire *1, (2) flour *1, (2) general *3, (2) hear *1, (2) here *1, (2) hour *1, (2) library *3, (2) male *1, (2) meal *1, (2) near *1, (2) oil *1, (2) our *1, (2) over *1, (2) petrol *1, (2) piano *2, (3) police *2, (1) really *3, (2) restaurant *3, (2) sail *1, (2) several *3, (2) smile *1, (2) steal *1, (2) stomach *2, (1) tidy *1, (2) usual *3, (2) usually *4, (3) vegetable *4, (3) wheel *1, (2) while *1, (2) wild *1, (2) wire *1, (2) year *1, (2) ``` ]
[Question] [ In addition to contributing to Stack Overflow and other SE sites, I like to ride public transit during my free time. I'd be spending a fortune on cash fare and/or bus tickets every month if I didn't have a bus pass. But for the average passenger, how much would you need to ride to make it worthwhile to buy a pass? ## Input Two parameters: Passenger age and transit usage report. [Standard loopholes apply.](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) You can read input from CLI arguments, function arguments, or a file (whichever works best for your language). ### Transit usage log format Each line represents a trip: ``` <date> <time> <route number> <start> à <destination> <date> <time> <route number> <start> à <destination> // comments, if any ``` Date is in ISO 8601 format. Time is 24 hour format (hours and minutes, both with leading zeros). The remaining information on the line is irrelevant for this question. ### Fare structure Tickets are $1.60 each. ``` Child (0-5) Child (6-12) Student (13-19) Adult (20+) Cash Free 1.90 3.55 3.55 Tickets Free 1 2 2 DayPass Free 8.30 8.30 8.30 Monthly pass Free n/A 82.25 103.25 ``` ### Transfers When paying with cash or tickets, a transfer (proof of payment) will be provided. The validity of the transfer is calculated as follows: * Until 04:30 the next day if time of boarding is after 22:00, else * 105 minutes from time of boarding on weekends, else * 90 minutes from time of boarding If you have a valid transfer at the start of a trip, you do not have to pay anything. For the purposes of this question, make the following assumptions: * All routes cost the same * You never lose your transfer or day pass * You do **not** have a transfer from the last day of the previous month. ### Day pass If more than $8.30 in cash is spent in a day, a day pass is cheaper. A day pass is valid from 03:00 to 03:00 the next day. If a day pass is purchased at 02:30, it is only good for 30 minutes! ## Output Output may be in the form of a return value or written to STDOUT. A trailing newline is permitted. Your program/function must output the cost of each option as follows (order does not matter): ``` C: $50.45 T: $44.1 J: $47.25 P: $100.75 ``` J represents the calculation for a combination of cash with day passes where a day pass would have been cheaper. Numbers must be truncated to at most two decimal places. Trailing zeros can be omitted. For passengers age 6 through 12, passes are unavailable so any non-digit output for `P` is OK (whether it be false, empty string, nil, null, not a number, "Infinity", etc.) ### Bonus -5% if you indicate the least expensive valid option in the output by printing any printable character before method of payment. For example: ``` P: $NaN C: $117.80 *T: $99.20 J: $117.80 ``` ## Test cases ### Input transit usage log ``` body {white-space: pre; font-family: monospace} ``` ``` 2015-04-01 02:28 95 Barrhaven Centre à Laurier 2015-04-01 06:31 98 Laurier à Tunney's Pasture 2015-04-01 06:51 176X Tunney's Pasture à Merivale/Rossdale 2015-04-01 08:06 176 Merivale/Family Brown à Laurier 2015-04-01 22:16 97 Campus à Lincoln Fields 2015-04-01 22:51 95 Lincoln Fields à Barrhaven Centre 2015-04-02 02:00 95 Barrhaven Centre à Laurier 2015-04-02 19:01 95 Campus à Barrhaven Centre 2015-04-02 22:31 170 Barrhaven Centre à Fallowfield 2015-04-02 23:22 95 Fallowfield à Trim 2015-04-02 00:41 95 Trim à Barrhaven Centre 2015-04-02 03:48 95 Barrhaven Centre à Laurier 2015-04-02 20:25 95X Laurier à Mackenzie King 2015-04-02 20:49 95 Mackenzie King à Barrhaven Centre 2015-04-02 23:58 95 Barrhaven Centre à Laurier 2015-04-04 21:26 96 Laurier à Lincoln Fields 2015-04-04 21:51 94 Lincoln Fields à Fallowfield 2015-04-04 22:10 95 Fallowfield à Barrhaven Centre 2015-04-04 22:38 95 Barrhaven Centre à Hurdman 2015-04-04 23:24 95 Hurdman à Mackenzie King 2015-04-05 00:03 1 Dalhousie/York à Johnston/Bank 2015-04-05 00:43 97 Greenboro à Lincoln Fields 2015-04-06 01:41 95 Lincoln Fields à Fallowfield 2015-04-06 02:11 95 Fallowfield à Barrhaven Centre 2015-04-06 05:21 95 Longfields à Laurier 2015-04-06 18:17 94 Laurier à Mackenzie King 2015-04-06 18:49 95 Mackenzie King à Barrhaven Centre 2015-04-06 23:18 95 Barrhaven Centre à Place d'Orléans 2015-04-06 00:41 95 Place d'Orléans à Barrhaven Centre 2015-04-06 02:01 95 Barrhaven Centre à Laurier 2015-04-06 19:15 94 Laurier à Mackenzie King 2015-04-06 19:49 95 Mackenzie King à Barrhaven Centre 2015-04-06 23:51 170 Strandherd à Fallowfield 2015-04-07 00:21 DH Fallowfield à Baseline 2015-04-07 00:39 95 Baseline à Laurier 2015-04-07 17:20 71 Mackenzie King à Berrigan/Edge 2015-04-07 23:18 95 Barrhaven Centre à Laurier 2015-04-09 00:40 95 Trim à Barrhaven Centre 2015-04-09 02:00 95 Barrhaven Centre à Laurier 2015-04-09 16:32 41 Campus à Hurdman 2015-04-09 16:37 94 Hurdman à St. Laurent 2015-04-09 17:41 95 St. Laurent à Campus 2015-04-10 01:06 95 Laurier à Barrhaven Centre 2015-04-10 02:01 95 Barrhaven Centre à Laurier 2015-04-10 17:15 66 Campus à Lincoln Fields 2015-04-10 17:44 95 Lincoln Fields à Barrhaven Centre 2015-04-10 23:38 95 Barrhaven Centre à Longfields 2015-04-11 00:05 95 Longfields à Laurier 2015-04-11 01:30 95 Laurier à Barrhaven Centre 2015-04-11 04:47 95 Barrhaven Centre à Fallowfield //stop engine 2015-04-11 05:17 95 Fallowfield à Laurier 2015-04-11 17:15 94 Laurier à Mackenzie King 2015-04-11 17:41 95 Mackenzie King à Barrhaven Centre 2015-04-11 23:30 170 Barrhaven Centre à Fallowfield 2015-04-12 00:21 95 Fallowfield à Laurier 2015-04-12 17:30 98 Laurier à Mackenzie King 2015-04-12 21:25 95 Laurier à Barrhaven Centre 2015-04-12 23:18 95 Barrhaven Centre à Laurier 2015-04-13 07:01 16 Laurier/Cumberland à Tunney's Pasture 2015-04-13 07:27 176X Tunney's Pasture à Merivale/Meadowlands 2015-04-13 09:12 176 Merivale/Baseline à LeBreton 2015-04-13 09:21 96 LeBreton à Blair 2015-04-14 00:34 95 Laurier à Barrhaven Centre 2015-04-14 02:30 95 Barrhaven Centre à Laurier 2015-04-14 07:06 86C Laurier à Tunney's Pasture 2015-04-14 07:21 176 Tunney's Pasture à Merivale/Meadowlands 2015-04-14 08:54 86 Meadowlands/Merivale à Laurier 2015-04-14 18:43 97X Laurier à Hurdman 2015-04-14 18:55 95 Hurdman à St. Laurent 2015-04-14 19:23 95 St. Laurent à Barrhaven Centre 2015-04-14 23:18 95 Barrhaven Centre à Trim 2015-04-15 00:38 95 Trim à Laurier 2015-04-15 08:00 35 Laurier à Mackenzie King 2015-04-15 08:35 94 Mackenzie King à Campus 2015-04-15 22:15 95 Laurier à Barrhaven Centre 2015-04-16 02:01 95 Barrhaven Centre à Laurier 2015-04-16 21:01 95 Laurier à Woodroffe/Tallwood 2015-04-16 21:34 86 Meadowlands/Woodroffe à Meadowlands/Merivale 2015-04-16 21:56 176 Merivale/Meadowlands à Barrhaven Centre 2015-04-17 02:00 95 Barrhaven Centre à Laurier 2015-04-17 11:52 96 Laurier à Bayshore 2015-04-17 13:21 96 Bayshore à Campus 2015-04-17 22:10 95X Campus à Baseline 2015-04-17 22:47 95 Baseline à Barrhaven Centre 2015-04-18 02:53 95 Barrhaven Centre à Laurier 2015-04-18 20:14 86X Laurier à Hurdman 2015-04-18 20:22 94 Hurdman à St. Laurent 2015-04-18 20:44 94 St. Laurent à Fallowfield 2015-04-18 21:43 95 Fallowfield à Barrhaven Centre 2015-04-19 00:58 95 Barrhaven Centre à Laurier 2015-04-19 15:16 95 Laurier à Mackenzie King 2015-04-19 16:22 94 Mackenzie King à Hurdman 2015-04-19 16:34 98 Hurdman à South Keys 2015-04-19 16:51 97 South Keys à Airport 2015-04-19 17:21 97 Airport à Laurier 2015-04-19 21:30 95 Laurier à Barrhaven Centre 2015-04-19 23:18 95 Barrhaven Centre à Laurier 2015-04-20 19:30 95 Laurier à Barrhaven Centre 2015-04-20 23:18 95 Barrhaven Centre à Trim 2015-04-21 00:38 95 Trim à Laurier 2015-04-21 19:30 95 Laurier à Barrhaven Centre 2015-04-22 02:00 95 Barrhaven Centre à Laurier 2015-04-22 19:30 95 Laurier à Barrhaven Centre 2015-04-23 01:28 95 Barrhaven Centre à Woodroffe/Medhurst 2015-04-23 02:11 95 Woodroffe/Medhurst à Laurier 2015-04-23 19:30 95 Laurier à Barrhaven Centre 2015-04-23 23:18 95 Barrhaven Centre à Trim 2015-04-24 00:38 95 Trim à Laurier 2015-04-24 23:15 95 Laurier à Barrhaven Centre 2015-04-25 00:23 95 Barrhaven Centre à Rideau St. 2015-04-25 01:44 96 Rideau St à Laurier 2015-04-25 16:58 86B Laurier à Albert/Bank 2015-04-25 17:44 87 Mackenzie King à Laurier 2015-04-26 01:25 95 Laurier à Barrhaven Centre 2015-04-27 01:04 95 Laurier à Rideau St 2015-04-27 01:31 95 Rideau St à Laurier 2015-04-27 17:25 41 Campus à Heron/Baycrest 2015-04-27 17:54 112 Baycrest/Heron à Elmvale 2015-04-27 18:30 114 Elmvale à Hurdman 2015-04-27 18:41 94 Hurdman à Laurier 2015-04-29 02:02 95 Barrhaven Centre à Laurier 2015-04-29 17:01 8 Campus à Heron 2015-04-29 17:37 118 Heron à Baseline 2015-04-29 18:01 95 Baseline à Barrhaven Centre 2015-04-29 20:32 95 Barrhaven Centre à Mackenzie King 2015-04-29 21:31 2 Rideau St à Bank/Queen 2015-04-29 21:35 95 Albert/Bank à Barrhaven Centre 2015-04-30 02:02 95 Barrhaven Centre à Laurier 2015-04-30 02:20 86C Campus à Mackenzie King 2015-04-30 02:44 96 Mackenzie King à Campus 2015-04-30 19:36 95 Laurier à Strandherd ``` ### Output ``` $ node --harmony golfed.js trips.txt 5 "Toddler" P: $0.00 C: $0.00 T: $0.00 J: $0.00 $ node --harmony golfed.js trips.txt 10 "Child" P: $NaN C: $117.80 T: $99.20 J: $117.80 $ node --harmony golfed.js trips.txt 15 "Student" P: $82.25 C: $220.10 T: $198.40 J: $194.20 $ node --harmony golfed.js trips.txt 61 "Adult" P: $103.25 C: $220.10 T: $198.40 J: $194.20 ``` [Answer] I'm going to kick off my own question by providing my own golfed solutions in two languages. These functions write to STDOUT. ## CoffeeScript, 438 bytes ``` F=(I,a)->f=[C=T=x=A=0,1.9,K=3.55,K,0,1,2,2];J=[];I.split('\n').map((r)->W=new Date w=r[..9];(y=+w[-2..]-((h=R.getUTCHours())<3);C+=f[A=a>19&&3||a>12&&2||a>5&&1||0];T+=f[A+4]*1.6;J[y]=J[y]||0;J[y]++;x=h>21&&+W+1026e5||h<3&&+W+162e5||+R+(R.getUTCDay()%6&&54e5||63e5))if x<R=new Date r=w+'T'+r[11..15]+':00');o={P:[0,NaN,Z=82.25,Z+21][A],C:C,T:T,J:J.reduce ((p,v)->v*f[A]>8.3&&p+8.3||p+v*f[A]),0};console.log(O+': $'+$.toFixed 2)for O,$ of o ``` ## JavaScript (ES6), 445 bytes ``` F=(I,a)=>{f=[C=T=x=0,1.9,K=3.55,K,0,1,2,2],J=[];I.split('\n').map(r=>{W=new Date(w=r[s='slice'](0,10));if((R=new Date(r=w+'T'+r[s](11,16)+':00'))>x){y=+w[s](-2)-(V=(h=R.getUTCHours())<3);C+=f[A=a>19?3:a>12?2:a>5?1:0];T+=f[A+4]*1.6;J[y]=J[y]||0;J[y]++;x=h>21?+W+1026e5:V?+W+162e5:+R+(R.getUTCDay()%6?54e5:63e5)}});for($ in(o={P:[0,NaN,Z=82.25,Z+21][A],C:C,T:T,J:J.reduce((p,v)=>v*f[A]>8.3?p+8.3:p+v*f[A],0)}))console.log($+': $'+o[$].toFixed(2))} ``` ## JavaScript (ES5), 474 bytes There really wasn't much ES6 other than arrow functions. ``` F=function(I,a){f=[C=T=x=0,1.9,K=3.55,K,0,1,2,2],J=[];I.split('\n').map(function(r){W=new Date(w=r[s='slice'](0,10));if((R=new Date(r=w+'T'+r[s](11,16)+':00'))>x){y=+w[s](-2)-(V=(h=R.getUTCHours())<3);C+=f[A=a>19?3:a>12?2:a>5?1:0];T+=f[A+4]*1.6;J[y]=J[y]||0;J[y]++;x=h>21?+W+1026e5:V?+W+162e5:+R+(R.getUTCDay()%6?54e5:63e5)}});for($ in(o={P:[0,NaN,Z=82.25,Z+21][A],C:C,T:T,J:J.reduce(function(p,v){return v*f[A]>8.3?p+8.3:p+v*f[A]},0)}))console.log($+': $'+o[$].toFixed(2))} ``` ### Demo ``` F = function(I, a) { f = [C = T = x = 0, 1.9, K = 3.55, K, 0, 1, 2, 2], J = []; I.split('\n').map(function(r) { W = new Date(w = r[s = 'slice'](0, 10)); if ((R = new Date(r = w + 'T' + r[s](11, 16) + ':00')) > x) { y = +w[s](-2) - (V = (h = R.getUTCHours()) < 3); C += f[A = a > 19 ? 3 : a > 12 ? 2 : a > 5 ? 1 : 0]; T += f[A + 4] * 1.6; J[y] = J[y] || 0; J[y] ++; x = h > 21 ? +W + 1026e5 : V ? +W + 162e5 : +R + (R.getUTCDay() % 6 ? 54e5 : 63e5) } }); for ($ in (o = { P: [0, NaN, Z = 82.25, Z + 21][A], C: C, T: T, J: J.reduce(function(p, v) { return v * f[A] > 8.3 ? p + 8.3 : p + v * f[A] }, 0) })) console.log($ + ': $' + o[$].toFixed(2)) } // Demonstration stuff console.log = function(x) { O.innerHTML += x + '\n' } F(D.innerHTML, 5); console.log('<hr>Child'); F(D.innerHTML, 10); console.log('<hr>Student'); F(D.innerHTML, 15); console.log('<hr>Adult'); F(D.innerHTML, 20); ``` ``` <div id=D hidden style=display:none> 2015-04-01 02:28 95 Barrhaven Centre à Laurier 2015-04-01 06:31 98 Laurier à Tunney's Pasture 2015-04-01 06:51 176X Tunney's Pasture à Merivale/Rossdale 2015-04-01 08:06 176 Merivale/Family Brown à Laurier 2015-04-01 22:16 97 Campus à Lincoln Fields 2015-04-01 22:51 95 Lincoln Fields à Barrhaven Centre 2015-04-02 02:00 95 Barrhaven Centre à Laurier 2015-04-02 19:01 95 Campus à Barrhaven Centre 2015-04-02 22:31 170 Barrhaven Centre à Fallowfield 2015-04-02 23:22 95 Fallowfield à Trim 2015-04-02 00:41 95 Trim à Barrhaven Centre 2015-04-02 03:48 95 Barrhaven Centre à Laurier 2015-04-02 20:25 95X Laurier à Mackenzie King 2015-04-02 20:49 95 Mackenzie King à Barrhaven Centre 2015-04-02 23:58 95 Barrhaven Centre à Laurier 2015-04-04 21:26 96 Laurier à Lincoln Fields 2015-04-04 21:51 94 Lincoln Fields à Fallowfield 2015-04-04 22:10 95 Fallowfield à Barrhaven Centre 2015-04-04 22:38 95 Barrhaven Centre à Hurdman 2015-04-04 23:24 95 Hurdman à Mackenzie King 2015-04-05 00:03 1 Dalhousie/York à Johnston/Bank 2015-04-05 00:43 97 Greenboro à Lincoln Fields 2015-04-06 01:41 95 Lincoln Fields à Fallowfield 2015-04-06 02:11 95 Fallowfield à Barrhaven Centre 2015-04-06 05:21 95 Longfields à Laurier 2015-04-06 18:17 94 Laurier à Mackenzie King 2015-04-06 18:49 95 Mackenzie King à Barrhaven Centre 2015-04-06 23:18 95 Barrhaven Centre à Place d'Orléans 2015-04-06 00:41 95 Place d'Orléans à Barrhaven Centre 2015-04-06 02:01 95 Barrhaven Centre à Laurier 2015-04-06 19:15 94 Laurier à Mackenzie King 2015-04-06 19:49 95 Mackenzie King à Barrhaven Centre 2015-04-06 23:51 170 Strandherd à Fallowfield 2015-04-07 00:21 DH Fallowfield à Baseline 2015-04-07 00:39 95 Baseline à Laurier 2015-04-07 17:20 71 Mackenzie King à Berrigan/Edge 2015-04-07 23:18 95 Barrhaven Centre à Laurier 2015-04-09 00:40 95 Trim à Barrhaven Centre 2015-04-09 02:00 95 Barrhaven Centre à Laurier 2015-04-09 16:32 41 Campus à Hurdman 2015-04-09 16:37 94 Hurdman à St. Laurent 2015-04-09 17:41 95 St. Laurent à Campus 2015-04-10 01:06 95 Laurier à Barrhaven Centre 2015-04-10 02:01 95 Barrhaven Centre à Laurier 2015-04-10 17:15 66 Campus à Lincoln Fields 2015-04-10 17:44 95 Lincoln Fields à Barrhaven Centre 2015-04-10 23:38 95 Barrhaven Centre à Longfields 2015-04-11 00:05 95 Longfields à Laurier 2015-04-11 01:30 95 Laurier à Barrhaven Centre 2015-04-11 04:47 95 Barrhaven Centre à Fallowfield //stop engine 2015-04-11 05:17 95 Fallowfield à Laurier 2015-04-11 17:15 94 Laurier à Mackenzie King 2015-04-11 17:41 95 Mackenzie King à Barrhaven Centre 2015-04-11 23:30 170 Barrhaven Centre à Fallowfield 2015-04-12 00:21 95 Fallowfield à Laurier 2015-04-12 17:30 98 Laurier à Mackenzie King 2015-04-12 21:25 95 Laurier à Barrhaven Centre 2015-04-12 23:18 95 Barrhaven Centre à Laurier 2015-04-13 07:01 16 Laurier/Cumberland à Tunney's Pasture 2015-04-13 07:27 176X Tunney's Pasture à Merivale/Meadowlands 2015-04-13 09:12 176 Merivale/Baseline à LeBreton 2015-04-13 09:21 96 LeBreton à Blair 2015-04-14 00:34 95 Laurier à Barrhaven Centre 2015-04-14 02:30 95 Barrhaven Centre à Laurier 2015-04-14 07:06 86C Laurier à Tunney's Pasture 2015-04-14 07:21 176 Tunney's Pasture à Merivale/Meadowlands 2015-04-14 08:54 86 Meadowlands/Merivale à Laurier 2015-04-14 18:43 97X Laurier à Hurdman 2015-04-14 18:55 95 Hurdman à St. Laurent 2015-04-14 19:23 95 St. Laurent à Barrhaven Centre 2015-04-14 23:18 95 Barrhaven Centre à Trim 2015-04-15 00:38 95 Trim à Laurier 2015-04-15 08:00 35 Laurier à Mackenzie King 2015-04-15 08:35 94 Mackenzie King à Campus 2015-04-15 22:15 95 Laurier à Barrhaven Centre 2015-04-16 02:01 95 Barrhaven Centre à Laurier 2015-04-16 21:01 95 Laurier à Woodroffe/Tallwood 2015-04-16 21:34 86 Meadowlands/Woodroffe à Meadowlands/Merivale 2015-04-16 21:56 176 Merivale/Meadowlands à Barrhaven Centre 2015-04-17 02:00 95 Barrhaven Centre à Laurier 2015-04-17 11:52 96 Laurier à Bayshore 2015-04-17 13:21 96 Bayshore à Campus 2015-04-17 22:10 95X Campus à Baseline 2015-04-17 22:47 95 Baseline à Barrhaven Centre 2015-04-18 02:53 95 Barrhaven Centre à Laurier 2015-04-18 20:14 86X Laurier à Hurdman 2015-04-18 20:22 94 Hurdman à St. Laurent 2015-04-18 20:44 94 St. Laurent à Fallowfield 2015-04-18 21:43 95 Fallowfield à Barrhaven Centre 2015-04-19 00:58 95 Barrhaven Centre à Laurier 2015-04-19 15:16 95 Laurier à Mackenzie King 2015-04-19 16:22 94 Mackenzie King à Hurdman 2015-04-19 16:34 98 Hurdman à South Keys 2015-04-19 16:51 97 South Keys à Airport 2015-04-19 17:21 97 Airport à Laurier 2015-04-19 21:30 95 Laurier à Barrhaven Centre 2015-04-19 23:18 95 Barrhaven Centre à Laurier 2015-04-20 19:30 95 Laurier à Barrhaven Centre 2015-04-20 23:18 95 Barrhaven Centre à Trim 2015-04-21 00:38 95 Trim à Laurier 2015-04-21 19:30 95 Laurier à Barrhaven Centre 2015-04-22 02:00 95 Barrhaven Centre à Laurier 2015-04-22 19:30 95 Laurier à Barrhaven Centre 2015-04-23 01:28 95 Barrhaven Centre à Woodroffe/Medhurst 2015-04-23 02:11 95 Woodroffe/Medhurst à Laurier 2015-04-23 19:30 95 Laurier à Barrhaven Centre 2015-04-23 23:18 95 Barrhaven Centre à Trim 2015-04-24 00:38 95 Trim à Laurier 2015-04-24 23:15 95 Laurier à Barrhaven Centre 2015-04-25 00:23 95 Barrhaven Centre à Rideau St. 2015-04-25 01:44 96 Rideau St à Laurier 2015-04-25 16:58 86B Laurier à Albert/Bank 2015-04-25 17:44 87 Mackenzie King à Laurier 2015-04-26 01:25 95 Laurier à Barrhaven Centre 2015-04-27 01:04 95 Laurier à Rideau St 2015-04-27 01:31 95 Rideau St à Laurier 2015-04-27 17:25 41 Campus à Heron/Baycrest 2015-04-27 17:54 112 Baycrest/Heron à Elmvale 2015-04-27 18:30 114 Elmvale à Hurdman 2015-04-27 18:41 94 Hurdman à Laurier 2015-04-29 02:02 95 Barrhaven Centre à Laurier 2015-04-29 17:01 8 Campus à Heron 2015-04-29 17:37 118 Heron à Baseline 2015-04-29 18:01 95 Baseline à Barrhaven Centre 2015-04-29 20:32 95 Barrhaven Centre à Mackenzie King 2015-04-29 21:31 2 Rideau St à Bank/Queen 2015-04-29 21:35 95 Albert/Bank à Barrhaven Centre 2015-04-30 02:02 95 Barrhaven Centre à Laurier 2015-04-30 02:20 86C Campus à Mackenzie King 2015-04-30 02:44 96 Mackenzie King à Campus 2015-04-30 19:36 95 Laurier à Strandherd </div> <pre id=O></pre> ``` ]
[Question] [ Write a self replicating program, in the source code filename `H.*`, contianed in an empty folder then manually compile and run or just run the program if your chosen language is dynamic, and it should then just create a new source file, `e.*`, with the same exact source code, and automatically compile/run that new program, which makes the new source file `l.*`, etc. until the source file `!.*` is made, and that program should do essentially nothing once it is compiled/run. "Hello world!" has some repeated characters, so the second character should be created by a similar filename, just with a new `<space>` at the end. Programs that just make/compile source files from the single instance of the program are invalid, and yes, " " is a valid filename. It should appear to say "Hello World!" when viewed in the file explorer sorted by time created. --- For example, if you were to attempt this challenge in python, than you would create the source file `H.py`, which complies and runs `e.py`, which then itself creates `l.py`, that file `l .py`, `o.py`, `.py`, `w.py`, `o .py`, `r.py`, `l .py` and `d.py` which finally creates and runs `!.py`, which does not do anything once run. [Answer] # Python 2, 194 ``` import os,sys h,A='H|e|l|l |o| |w|o |r|l |d|!'.split('|'),sys.argv[0] d,a,F=dict(zip(h,h[1:])),A.split('.')[0],file if a in d:o=d[a]+'.py';F(o,'w').write(F(A).read());os.popen('python "'+o+'"') ``` [Answer] # Bash, ~~99~~ ~~88~~ 84 ``` X=`grep -Po "(?<=#$0#)[^#]*" "$0"` #H#e#l#l #o# #W#o #r#l #d#! cp "$0" "$X" sh "$X" ``` ## Explanation: 1. First we create a regex from the name of the file (the argument `$0`). For example, here is the regex constructed when the first file executes (`$0` is `H`): ``` (?<=#H#)[^#]* ``` This searches for a sequence of non-`#` characters preceded by `#H#`. That is, it finds the next filename in a sequence of `#`-separated filenames. (I used `#` so that the separator before `H` would function as the string delimiter itself, with the bonus of not needing a closing delimiter.) 2. Then we search (`grep`) the currently-executing file `"$0"` with this regex. We need the `-P` flag (or similar) to use the lookbehind construct, and `-o` to only return the new filename, not the whole line. 3. We store the result (using backticks ```) of this whole evaluation in the variable `X`. 4. We copy (`cp`) the current file to the new file. 5. Finally we execute the new file with `sh`. ## Example usage: ``` robert@unity:~/hwbash$ ls -lrt total 4 -rw-r--r-- 1 robert robert 97 May 25 23:52 H robert@unity:~/hwbash$ sh H cp: cannot create regular file `': No such file or directory sh: 0: Can't open robert@unity:~/hwbash$ ls -lrt total 48 -rw-r--r-- 1 robert robert 97 May 25 23:52 H -rw-r--r-- 1 robert robert 97 May 25 23:52 e -rw-r--r-- 1 robert robert 97 May 25 23:52 l -rw-r--r-- 1 robert robert 97 May 25 23:52 l -rw-r--r-- 1 robert robert 97 May 25 23:52 o -rw-r--r-- 1 robert robert 97 May 25 23:52 -rw-r--r-- 1 robert robert 97 May 25 23:52 W -rw-r--r-- 1 robert robert 97 May 25 23:52 o -rw-r--r-- 1 robert robert 97 May 25 23:52 r -rw-r--r-- 1 robert robert 97 May 25 23:52 l -rw-r--r-- 1 robert robert 97 May 25 23:52 d -rw-r--r-- 1 robert robert 97 May 25 23:52 ! robert@unity:~/hwbash$ ``` ## Updates 1. I saved some bytes by using `bash H` instead of `#!/bin/bash`. This also means that I don't have to copy the executable permission, so sorting by timestamps works now (but you need to add a `sleep 1` or something to make it reliable). 2. Saved some more bytes by moving the string to a comment and changing the command from `bash` to `sh`. ]
[Question] [ Write a program or function that takes a base `n` and a number `x`, and returns or outputs the [`n`-ary Gray code](https://en.wikipedia.org/wiki/Gray_code#n-ary_Gray_code) of `x`. ## Rules * `n` is an integer in the range `2 <= n <= 16`. * `x` is an integer in the range `0 <= n < 2**32`. * The inputted numbers can either be two integer arguments if you write a function, or two arguments to `ARGV` or a space separated pair to `STDIN` if you write a program. * The output should be a string, either returned or printed to `STDOUT`. * If `n` is 10 or more, use hex digits to represent digits with a value greater than 9. The case of the digits does not matter. * If the `n`-ary Gray code of `x` is zero, `'0'` must be printed or returned. * Code length is in bytes, and standard loopholes are not permitted. * You do not need to use the same algorithm as below, but if you use a different one, make sure it produces valid Gray codes. ## Example Example code adapted from [Wikipedia](https://en.wikipedia.org/wiki/Gray_code#n-ary_Gray_code): ``` >>> import string >>> >>> def nary_gray_code(base, num): ... base_num = [] ... # Convert to num to base base ... while num: ... base_num.append(num % base) ... num = num // base ... # Convert base base number to base-ary Gray code ... shift = 0 ... gray = [] ... for b in reversed(base_num): ... gray.insert(0, (b + shift) % base) ... shift += base - gray[0] ... return "".join(string.hexdigits[i] for i in reversed(gray)) or "0" ... >>> nary_gray_code(2, 100) '1010110' >>> nary_gray_code(2, 1) '1' >>> nary_gray_code(2, 0) '0' >>> nary_gray_code(10, 23) '21' >>> nary_gray_code(10, 100) '190' >>> nary_gray_code(3, 26) '200' >>> nary_gray_code(3, 27) '1200' >>> for i in range(2, 17): ... print(i, nary_gray_code(i, 2**32 - 1)) ... 2 10000000000000000000000000000000 3 122102120011102000122 4 3000000000000000 5 34020102231331 6 1401154214013 7 260241350125 8 34000000000 9 11762782617 10 4875571576 11 1824007509 12 92b627446 13 5b25a2c00 14 2ac96ab2b 15 197dde1a7 16 f0000000 >>> ``` [Answer] # Pyth, 20 bytes ``` Msme.H%dGu+G-HsGjHGY ``` This defines a function `g` which takes two integers as parameters. Take a look at this online demonstration: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=Msme.H%25dGu%2BG-HsGjHGY%0Ag+2+100%0Ag+2+1%0Ag+2+0%0Ag+10+23%0Ag+10+100%0Ag+3+26%0Ag+3+27%0Ag+2+4294967295%0Ag+3+4294967295%0Ag+4+4294967295%0Ag+5+4294967295%0Ag+6+4294967295%0Ag+7+4294967295%0Ag+8+4294967295%0Ag+9+4294967295%0Ag+10+4294967295%0Ag+11+4294967295%0Ag+12+4294967295%0Ag+13+4294967295%0Ag+14+4294967295%0Ag+15+4294967295%0Ag+16+4294967295&debug=0). ## Explanation: ``` Msme.H%dGu+G-HsGjHGY M def g(G, H): return _ jHG convert H to base G u jHGY reduce(lambda G, H: _, jHG, []) +G-HsG G + [H - sum(G)] m map each number d to: e.H%dG hex-representation(d % G)[-1] s sum (join all digits) ``` This code is a little bit confusing. There are 4 function parameters in this code: two of them are called `G` and two of them are called `H`. The `G` in `+G-HsG` is different from the `G` in `jHG` or `%dG`. ]
[Question] [ *This challenge is specific to languages of the APL family. Although it might be solvable in other languages, please do not expect this to be easy as it depends on some specific concepts of this language family.* Many array oriented languages have the concept of a box (also called enclosure). A box encapsulates an array, hiding its shape. Here is an example of a boxed array: ``` ┌─┬───────┬─────┐ │0│1 2 3 4│0 1 2│ │ │ │3 4 5│ └─┴───────┴─────┘ ``` This array was generated from the J sentence `0 ; 1 2 3 4 ; i. 2 3` and contains three boxes, the first containing the scalar `0`, the second containing a vector of shape `4`, and the third containing a matrix of shape `2 3`. Some arrays of boxes look like they are plain arrays broken apart by boxes: ``` ┌─┬───────────┐ │0│1 2 3 4 │ ├─┼───────────┤ │5│ 9 10 11 12│ │6│13 14 15 16│ │7│17 18 19 20│ │8│21 22 23 24│ └─┴───────────┘ ``` The previous array was generated from the J expression `2 2 $ 0 ; 1 2 3 4 ; (,. 5 6 7 8) ; 9 + i. 4 4`. Your goal in this challenge is to take an array like that and remove the boxes separating the subarrays from one another. For instance, the previous array would be transformed into ``` 0 1 2 3 4 5 9 10 11 12 6 13 14 15 16 7 17 18 19 20 8 21 22 23 24 ``` Submit a solution as a monadic verb / function. The verb must work on arrays of arbitrary rank. You may assume that the shapes of the boxed arrays fit, that is, boxed subarrays adjacent on an axis have to have the same dimensions in all but that axis. Behaviour is undefined if they don't. This challenge is *code golf.* The submission compromising the least amount of characters wins. [Answer] # J, 73 chars ``` f=.3 :0 >".'z',~,(',"','&.>/',~":)"*1+i.#$z=.(,$~$,~1#~(#$y)-#@$)&.>y ) ``` Usage and tests: ``` a=.2 2 $ 0 ; 1 2 3 4 ; (,. 5 6 7 8) ; 9 + i. 4 4 f a 0 1 2 3 4 5 9 10 11 12 6 13 14 15 16 7 17 18 19 20 8 21 22 23 24 f a,:a NB. rank 3 test 0 1 2 3 4 5 9 10 11 12 6 13 14 15 16 7 17 18 19 20 8 21 22 23 24 0 1 2 3 4 5 9 10 11 12 6 13 14 15 16 7 17 18 19 20 8 21 22 23 24 ``` Golfing and explanation coming tomorrow. [Answer] # J, 39 ``` f=:([:;(([:(;"1@|:)(;/&> ::]))&.>)@<"1) ``` Usage and tests ``` a=.2 2 $ 0 ; 1 2 3 4 ; (,. 5 6 7 8) ; 9 + i. 4 4 f a 0 1 2 3 4 5 9 10 11 12 6 13 14 15 16 7 17 18 19 20 8 21 22 23 24 ``` ]
[Question] [ While looking at the ARM instruction set, you notice that the `ADD` instruction has the so-called ["Flexible second operand"](http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0068b/CIHEDHIF.html), which can be abused for quick multiplication. For example, the following instruction multiplies register `r1` by 17 (shifting it left by 4 bits and adding to itself): ``` ADD r1, r1, r1, LSL #4 ; LSL means "logical shift left" ``` The subtraction instruction has that feature too. So multiplication by 15 is also easy to implement: ``` RSB r1, r1, r1, LSL #4 ; RSB means "reverse subtract", i.e. subtract r1 from (r1 << 4) ``` So this is an excellent optimization opportunity! Certainly, when you write in a C program `x *= 15`, the compiler will translate that to some inefficient code, while you could replace it by `x = (x << 4) - x`, and *then* the compiler will generate better code! Quickly, you come up with the following cunning plan: 1. Write a program or a subroutine, in any language, that receives one parameter `m`, and outputs a C optimizing macro, like the following (for `m = 15`): ``` #define XYZZY15(x) (((x) << 4) - (x)) ``` or (which is the same) ``` #define XYZZY15(x) (-(x) + ((x) << 4)) ``` 2. ??? 3. Profit! Notes: * The macro's name is essential: magic requires it. * [Parentheses around `x` and the whole expression are required](https://stackoverflow.com/q/10820340/509868): ancient C arcana cannot be taken lightly. * You can assume `m` is between 2 and 65535. * The input and output can be passed through function parameters, `stdin/stdout` or in any other customary way. * In C, addition and subtraction have tighter precedence than bit shift `<<`; use parentheses to clarify order of calculations. More parentheses than necessary is OK. * It is absolutely vital that the C expression be optimal, so e.g. `x+x+x` is not acceptable, because `(x<<1)+x` is better. * Expressions `x + x` and `x << 1` are equivalent, because both require one ARM instruction to calculate. Also, `(x << 1) + (x << 2)` (multiplication by 6) requires two instructions, and cannot be improved. * You are amazed to discover that the compiler detects that `(x << 0)` is the same as `x`, so `x + (x << 0)` is an acceptable expression. However, there is no chance the compiler does any other optimizations on your expression. * Even though multiplication by 17 can be implemented in one instruction, multiplication by 17\*17 cannot be implemented in two instructions, because there is no C expression to reflect that: ``` #define XYZZY289(x) x + (x << 4) + (x + (x << 4) << 4) // 3 operations; optimal ``` In other words, the compiler doesn't do common sub-expression elimination. Maybe you will fix that bug in version 2... This is code-golf: the shortest code wins (but it must be correct, i.e. produce correct and optimal expressions for all `m`) Please also give example outputs for `m = 2, 10, 100, 14043 and 65535` (there is no requirement on the length of the expression - it can contain extra parentheses, whitespace and shift left by 0 bits, if that makes your code simpler). [Answer] # Python - ~~414~~ ~~393~~ 331 This is my entry, which finds the least possible addition/subtraction operations, and subsequently evaluates to a C expression. Not sure it is optimal as multiplication of subexpressions may offer less operations. ``` import itertools as l def w(N,s=''): for k,v in enumerate(min([t for t in l.product((1,0,-1),repeat=len(bin(N))-1)if sum([v*2**k for k,v in enumerate(t)])==N],key=lambda t:sum(abs(k)for k in t))): if v!=0:s+='{:+d}'.format(v)[0];s+='((x)<<{})'.format(k)if k>0 else'(x)' return '#define XYZZY{}(x) ({})'.format(N,s.lstrip('+')) ``` For the cases 2, 10, 100, 14043, 65535: ``` #define XYZZY2 (((x)<<1)) #define XYZZY10 (((x)<<1)+((x)<<3)) #define XYZZY100 (((x)<<2)+((x)<<5)+((x)<<6)) #define XYZZY14043 (-(x)-((x)<<2)-((x)<<5)-((x)<<8)-((x)<<11)+((x)<<14)) #define XYZZY65535(x) (-(x)+((x)<<16)) ``` The final 65535 took around 11 minutes to compute. Suggestions for improvement (also speedwise) are welcome :-). Thanks to [mbomb007](https://codegolf.stackexchange.com/users/34718/mbomb007) and [plg](https://codegolf.stackexchange.com/users/13130/plg) for golfing improvements. [Answer] # Python 508 Slightly more characters than my other answer, but this code runs in roughly one second for all cases 2, 10, 100, 14043, 65535. ``` def l(n,k=0,o=0): while 1: if k==0: for j in range(1,n): yield(j,);yield(-j,) k+=1 else: for j in range(1,n): for u in l(j,k-1,1): yield(j,)+u;yield(-j,)+u k+=1 if o:break r=lambda t:sum((1,-1)[k<0]*2**(abs(k)-1)for k in t) def w(N,s=''): g = loop(len(bin(N))) while 1: a = g.next() if r(a)==N: for k in a: s+='{:+d}'.format(k)[0];s+='((x)<<{})'.format(abs(k-1)) if abs(k)>1 else'(x)' return '#define XYZZY{}(x) ({})'.format(N,s.lstrip('+'))""") ``` ]
[Question] [ ## *Edit* I have posted a 250 lines [reference implementation for review at CR](https://codereview.stackexchange.com/questions/83233/correctness-and-understandability-of-my-pcg-reference-implementation), discussing the major class of the code. Download the [complete Visual Studio 2013, .NET 4.5 source code](http://46.38.245.27/stackoverflow/HTML2JSONConverterSource.zip) (10 kB) from my server. ## Story This is based on a real world puzzle. A colleague had a very old program. It was announced to be discontinued by the company and then it was really discontinued in 2009. Now I should use that program as well, but it is full of bugs and I refused to use it. Instead I wanted to help my colleague and converted the content into a reusable format so we could import it to any other program. The data is in a database, but the scheme is horrible because it creates new tables every now and then, so doing a SQL export was not feasible. The program also does not have an export functionality. But it has a reporting capability. Bad luck: reporting to Excel fails, because the output is larger than the 65.000 lines allowed by the only old excel format it supports. The only option left was reporting to HTML. ## Task Given * input is a HTML document * it seems to be created by Microsoft Active Report, which shouldn't really matter. But for the sake of equality, your code must not use any Active Report specific library to parse the HTML (if such a thing exists) * The reports is hierarchically structured in either 2 or 3 levels. * the HTML is horrible (IMHO), it consists of DIVs and SPANs only, each having a @style attribute specified. The *left* position of the style at a SPAN can be used to detect the indentation, which allows conclusions to get the number of levels. * there is always one SPAN which defines the key. The key is formatted in bold and ends with a colon (use whatever you want to detect it) * The key may be followed by another SPAN which defines the value. If the value is not present, it shall be considered as an empty string. * if a key reappears on the same level, that's the start of a new item you * create a valid JSON file as output * the JSON needn't be pretty-printed, just valid * non-breaking spaces can be converted to normal spaces or be Unicode 00A0 * remove the NOBR tags from the output * ignore any unneeded information like the page number (last SPAN in a DIV), HEAD and STYLE before the first DIV * use the key as the property name (remove the trailing colon and the spaces) * use the value as the property value * create an array property called `Children` for the items on the next level As far as I can tell, the HTML is technically ok. All tags are closed etc. but it's not XHTML. You needn't do any error checking on it. Side note: I don't need your code to solve a task or homework. I have already implemented a converter but to a different output format. ## Rules Code Golf. The shortest code wins. Hopefully the task is complex enough to make it hard for special golfing languages so that other languages have a chance as well. Libraries are allowed. Loophole libraries specially crafted for this task shall be downvoted. Answer with shortest code on 2015-03-14 gets accepted. ## Sample The code shall be able to process all kinds of reports the program produces, so do not hard code any keys or values. Here's an anonymized 2 page except of one of the reports. ![Screenshot of the HTML](https://i.stack.imgur.com/PCj2O.png) ``` <html> <head> <title> ActiveReports Document </title><meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8" /> </head><body leftmargin="0" topmargin="0" marginheight="0" marginwidth="0"> <style> @page{size: 11.69in 8.27in;margin-top:0.1in;margin-left:1in;margin-right:1in;margin-bottom:0in;} </style><div style="page-break-inside:avoid;page-break-after:always;"> <div style="position:relative;width:9.69in;height:8.17in;"> <span style="position:absolute;top:1.171028in;left:0.01388884in;width:1.111274in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Requirement&nbsp;Name:</nobr></span> <span style="position:absolute;top:1.171028in;left:1.139051in;width:7.860949in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Activate&nbsp;Golf</nobr></span> <span style="position:absolute;top:1.383181in;left:0.01388884in;width:0.6756048in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Description:</nobr></span> <span style="position:absolute;top:1.583181in;left:0.01388884in;width:0.2805853in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Risk:</nobr></span> <span style="position:absolute;top:1.583181in;left:0.3083631in;width:8.691637in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Average</nobr></span> <span style="position:absolute;top:1.795334in;left:0.01388884in;width:0.3974066in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Status:</nobr></span> <span style="position:absolute;top:1.795334in;left:0.4251844in;width:8.574816in;height:0.1664768in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>In&nbsp;Progress</nobr></span> <span style="position:absolute;top:2.007487in;left:0.01388884in;width:0.7040471in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Priorit&#228;t&nbsp;QA:</nobr></span> <span style="position:absolute;top:2.007487in;left:0.7318249in;width:8.268175in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Average</nobr></span> <span style="position:absolute;top:2.387853in;left:0.2138889in;width:0.8061111in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Test&nbsp;Name:</nobr></span> <span style="position:absolute;top:2.387853in;left:1.033889in;width:7.966111in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Activate&nbsp;Golf</nobr></span> <span style="position:absolute;top:2.768218in;left:0.2138889in;width:0.8061111in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Test&nbsp;Name:</nobr></span> <span style="position:absolute;top:2.768218in;left:1.033889in;width:7.966111in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Activate&nbsp;Golf&nbsp;Settings</nobr></span> <span style="position:absolute;top:3.148584in;left:0.01388884in;width:1.111274in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Requirement&nbsp;Name:</nobr></span> <span style="position:absolute;top:3.148584in;left:1.139051in;width:7.860949in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Add&nbsp;Balls</nobr></span> <span style="position:absolute;top:3.360737in;left:0.01388884in;width:0.6756048in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Description:</nobr></span> <span style="position:absolute;top:3.560737in;left:0.01388884in;width:0.2805853in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Risk:</nobr></span> <span style="position:absolute;top:3.560737in;left:0.3083631in;width:8.691637in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Low</nobr></span> <span style="position:absolute;top:3.77289in;left:0.01388884in;width:0.3974066in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Status:</nobr></span> <span style="position:absolute;top:3.77289in;left:0.4251844in;width:8.574816in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>In&nbsp;Progress</nobr></span> <span style="position:absolute;top:3.985043in;left:0.01388884in;width:0.7040471in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Priorit&#228;t&nbsp;QA:</nobr></span> <span style="position:absolute;top:3.985043in;left:0.7318249in;width:8.268175in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>High</nobr></span> <span style="position:absolute;top:4.365408in;left:0.2138889in;width:0.8061111in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Test&nbsp;Name:</nobr></span> <span style="position:absolute;top:4.365408in;left:1.033889in;width:7.966111in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Download&nbsp;Golf&nbsp;Puzzles from Internet</nobr></span> <span style="position:absolute;top:4.745774in;left:0.01388884in;width:1.111274in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Requirement&nbsp;Name:</nobr></span> <span style="position:absolute;top:4.745774in;left:1.139051in;width:7.860949in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Add&nbsp;Player</nobr></span> <span style="position:absolute;top:4.957927in;left:0.01388884in;width:0.6756048in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Description:</nobr></span> <span style="position:absolute;top:5.157927in;left:0.01388884in;width:0.2805853in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Risk:</nobr></span> <span style="position:absolute;top:5.157927in;left:0.3083631in;width:8.691637in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Average</nobr></span> <span style="position:absolute;top:5.37008in;left:0.01388884in;width:0.3974066in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Status:</nobr></span> <span style="position:absolute;top:5.37008in;left:0.4251844in;width:8.574816in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>In&nbsp;Progress</nobr></span> <span style="position:absolute;top:5.582232in;left:0.01388884in;width:0.7040471in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Priorit&#228;t&nbsp;QA:</nobr></span> <span style="position:absolute;top:5.582232in;left:0.7318249in;width:8.268175in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Average</nobr></span> <span style="position:absolute;top:5.962598in;left:0.2138889in;width:0.8061111in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Test&nbsp;Name:</nobr></span> <span style="position:absolute;top:5.962598in;left:1.033889in;width:7.966111in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Golf&nbsp;Upload&nbsp;Puzzles&nbsp;to Server</nobr></span> <span style="position:absolute;top:6.342964in;left:0.01388884in;width:1.111274in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Requirement&nbsp;Name:</nobr></span> <span style="position:absolute;top:6.342964in;left:1.139051in;width:7.860949in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>GLFD</nobr></span> <span style="position:absolute;top:6.555117in;left:0.01388884in;width:0.6756048in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Description:</nobr></span> <span style="position:absolute;top:6.755116in;left:0.01388884in;width:0.2805853in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Risk:</nobr></span> <span style="position:absolute;top:6.755116in;left:0.3083631in;width:8.691637in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>High</nobr></span> <span style="position:absolute;top:6.967269in;left:0.01388884in;width:0.3974066in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Status:</nobr></span> <span style="position:absolute;top:6.967269in;left:0.4251844in;width:8.574816in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>In&nbsp;Progress</nobr></span> <span style="position:absolute;top:7.179422in;left:0.01388884in;width:0.7040471in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Priorit&#228;t&nbsp;QA:</nobr></span> <span style="position:absolute;top:7.179422in;left:0.7318249in;width:8.268175in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Average</nobr></span> <span style="position:absolute;top:7.48389in;left:0.07638884in;width:2.548611in;height:0.6861111in;font-family:Arial;font-size:10pt;color:#000000;vertical-align:top;"><nobr>Page&nbsp;1&nbsp;of&nbsp;115</nobr></span> </div> </div><div style="page-break-inside:avoid;page-break-after:always;"> <div style="position:relative;width:9.69in;height:8.17in;"> <span style="position:absolute;top:0.7972222in;left:0.01388884in;width:1.111274in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Requirement&nbsp;Name:</nobr></span> <span style="position:absolute;top:0.7972222in;left:1.139051in;width:7.860949in;height:0.1664768in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Count dimples</nobr></span> <span style="position:absolute;top:1.009375in;left:0.01388884in;width:0.6756048in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Description:</nobr></span> <span style="position:absolute;top:1.209375in;left:0.01388884in;width:0.2805853in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Risk:</nobr></span> <span style="position:absolute;top:1.209375in;left:0.3083631in;width:8.691637in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Low</nobr></span> <span style="position:absolute;top:1.421528in;left:0.01388884in;width:0.3974066in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Status:</nobr></span> <span style="position:absolute;top:1.421528in;left:0.4251844in;width:8.574816in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Failed</nobr></span> <span style="position:absolute;top:1.633681in;left:0.01388884in;width:0.7040471in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Priorit&#228;t&nbsp;QA:</nobr></span> <span style="position:absolute;top:1.633681in;left:0.7318249in;width:8.268175in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Low</nobr></span> <span style="position:absolute;top:2.014046in;left:0.2138889in;width:0.8061111in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Test&nbsp;Name:</nobr></span> <span style="position:absolute;top:2.014046in;left:1.033889in;width:7.966111in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Add&nbsp;dimples</nobr></span> <span style="position:absolute;top:2.394412in;left:0.2138889in;width:0.8061111in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Test&nbsp;Name:</nobr></span> <span style="position:absolute;top:2.394412in;left:1.033889in;width:7.966111in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Create&nbsp;divot</nobr></span> <span style="position:absolute;top:2.774778in;left:0.2138889in;width:0.8061111in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Test&nbsp;Name:</nobr></span> <span style="position:absolute;top:2.774778in;left:1.033889in;width:7.966111in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Repair&nbsp;divot</nobr></span> <span style="position:absolute;top:3.155143in;left:0.2138889in;width:0.8061111in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Test&nbsp;Name:</nobr></span> <span style="position:absolute;top:3.155143in;left:1.033889in;width:7.966111in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Modify&nbsp;divot</nobr></span> <span style="position:absolute;top:3.535509in;left:0.01388884in;width:1.111274in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Requirement&nbsp;Name:</nobr></span> <span style="position:absolute;top:3.535509in;left:1.139051in;width:7.860949in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Use iron</nobr></span> <span style="position:absolute;top:3.747662in;left:0.01388884in;width:0.6756048in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Description:</nobr></span> <span style="position:absolute;top:3.947661in;left:0.01388884in;width:0.2805853in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Risk:</nobr></span> <span style="position:absolute;top:3.947661in;left:0.3083631in;width:8.691637in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>High</nobr></span> <span style="position:absolute;top:4.159814in;left:0.01388884in;width:0.3974066in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Status:</nobr></span> <span style="position:absolute;top:4.159814in;left:0.4251844in;width:8.574816in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>In&nbsp;Progress</nobr></span> <span style="position:absolute;top:4.371967in;left:0.01388884in;width:0.7040471in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Priorit&#228;t&nbsp;QA:</nobr></span> <span style="position:absolute;top:4.371967in;left:0.7318249in;width:8.268175in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Average</nobr></span> <span style="position:absolute;top:4.752333in;left:0.2138889in;width:0.8061111in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Test&nbsp;Name:</nobr></span> <span style="position:absolute;top:4.752333in;left:1.033889in;width:7.966111in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Go&nbsp;fairway</nobr></span> <span style="position:absolute;top:5.132699in;left:0.2138889in;width:0.8061111in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Test&nbsp;Name:</nobr></span> <span style="position:absolute;top:5.132699in;left:1.033889in;width:7.966111in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Analyze&nbsp;trajectory</nobr></span> <span style="position:absolute;top:5.513064in;left:0.2138889in;width:0.8061111in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Test&nbsp;Name:</nobr></span> <span style="position:absolute;top:5.513064in;left:1.033889in;width:7.966111in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Collect ball</nobr></span> <span style="position:absolute;top:5.89343in;left:0.2138889in;width:0.8061111in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Test&nbsp;Name:</nobr></span> <span style="position:absolute;top:5.89343in;left:1.033889in;width:7.966111in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Exchange ball</nobr></span> <span style="position:absolute;top:6.273796in;left:0.01388884in;width:1.111274in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Requirement&nbsp;Name:</nobr></span> <span style="position:absolute;top:6.273796in;left:1.139051in;width:7.860949in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>你好</nobr></span> <span style="position:absolute;top:6.485949in;left:0.01388884in;width:0.6756048in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Description:</nobr></span> <span style="position:absolute;top:6.685949in;left:0.01388884in;width:0.2805853in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Risk:</nobr></span> <span style="position:absolute;top:6.685949in;left:0.3083631in;width:8.691637in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>High</nobr></span> <span style="position:absolute;top:6.898102in;left:0.01388884in;width:0.3974066in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Status:</nobr></span> <span style="position:absolute;top:6.898102in;left:0.4251844in;width:8.574816in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>In&nbsp;Progress</nobr></span> <span style="position:absolute;top:7.110255in;left:0.01388884in;width:0.7040471in;height:0.154324in;font-family:Calibri;font-size:9pt;color:#000000;font-weight:bold;vertical-align:top;"><nobr>Priorit&#228;t&nbsp;QA:</nobr></span> <span style="position:absolute;top:7.110255in;left:0.7318249in;width:8.268175in;height:0.1664767in;font-family:Calibri;font-size:9pt;color:#000000;vertical-align:top;"><nobr>Average</nobr></span> <span style="position:absolute;top:7.48389in;left:0.07638884in;width:2.548611in;height:0.6861111in;font-family:Arial;font-size:10pt;color:#000000;vertical-align:top;"><nobr>Page&nbsp;2&nbsp;of&nbsp;115</nobr></span> </div> </div> </body> </html> ``` Expected JSON Output (handcrafted, please correct me if I added a typo): ``` { "Children": [ { "RequirementName": "Activate Golf", "Description": "", "Risk": "Average", "Status": "In Progress", "PrioritätQA": "Average", "Children": [ { "TestName": "Activate Golf" }, { "TestName": "Activate Golf Settings" } ] }, { "RequirementName": "Add Balls", "Description": "", "Risk": "Low", "Status": "In Progress", "PrioritätQA": "High", "Children": [ { "TestName": "Download Golf Puzzles from Internet" } ] }, { "RequirementName": "Add Player", "Description": "", "Risk": "Average", "Status": "In Progress", "PrioritätQA": "Average", "Children": [ { "TestName": "Golf Upload Puzzles to Server" } ] }, { "RequirementName": "GLFD", "Description": "", "Risk": "High", "Status": "In Progress", "Priorität QA": "Average", "Children": [ ] }, { "RequirementName": "Count dimples", "Description": "", "Risk": "Low", "Status": "Failed", "PrioritätQA": "Low", "Children": [ { "TestName": "Add dimples" }, { "TestName": "Create divot" }, { "TestName": "Repair divot" }, { "TestName": "Modify divot" } ] }, { "RequirementName": "Use iron", "Description": "", "Risk": "High", "Status": "In Progress", "PrioritätQA": "Average", "Children": [ { "TestName": "Go fairway" }, { "TestName": "Analyze trajectory" }, { "TestName": "Collect ball" }, { "TestName": "Exchange ball" } ] }, { "RequirementName": "你好", "Description": "", "Risk": "High", "Status": "In Progress", "PrioritätQA": "Average", "Children": [ ] } ] } ``` [Answer] # VBScript 819 (if line endings count as 1) VBScript is a Microsoft scripting language unrelated to VBA, VB.net or legacy VB6 For those of you that have never seen it: * <http://en.wikipedia.org/wiki/VBScript> * <http://www.w3schools.com/Vbscript/default.asp> VBScript is NOT designed for golfing and I am not great at golfind anyway so the best I can do is 819. If you see a way to make it shorter please comment. To run this code use: ``` cscript //nologo //u html2json.vbs < html2json.html > html2json.json ``` This code does not indent the json properly but keeping the indent level would have made it even longer. The other thing that differs from the example json is that this code doesn't produce empty Children arrays that aren't there in the html - I hope that's ok. Here is the code: ``` Set W=WScript Set S=W.Stdin W.Echo"{" Do While InStr(a,":abs")<1 a=S.Readline If a="</html>"Then W.Echo"}]}":W.Quit Wend Do If InStr(a,">Page&")<1Then a=Replace(a,"&nbsp;"," ") Do B=InStr(a,"&#")+2 If B<3Then Exit Do C=InStr(B,a,";") a=Left(a,B-3)&Chr(Mid(a,B,C-B))&Mid(a,C+1) Loop D=InStr(a,"<nobr>")+6 E=InStr(D,a,"</nobr>") V=Mid(a,D,E-D) F=InStr(a,"top:")+4 G=InStr(F,a,"in;") T=Mid(a,F,G-F) If T=U Then W.Echo X&""""&K&""":"""&V&"""":X="," K="" Else If K<>""Then W.Echo X&""""&K&""":""""":X="," K=Left(V,Len(V)-1) K=Replace(K," ","") P=InStr(a,"left:")+5 Q=InStr(P,a,"in;") L=Mid(a,P,Q-P) If L>M Then W.Echo X&"""Children"":[":X=""Else If Abs(T-U)>.3And U>0Then W.Echo"}":X="," If L<M Then W.Echo"]}":X="," If Abs(T-U)>.3Then W.Echo X&"{":X="" End If End If a=S.Readline Loop While InStr(a,">Page ")<0 U=T M=L Loop ``` [Answer] ## C# - 1716 Ok, this one was rather simple for me, but that might be the reason why it is not very short. I just golfed the reference implementation (including all parts, not only the part that is posted on Code Review): ``` namespace System{using Collections.Generic;using Globalization;using IO;using Linq;using ExCSS;using HtmlAgilityPack;using Newtonsoft.Json;class J:JsonConverter{Dictionary<string,string>P=new Dictionary<string,string>();List<J>C=new List<J>();decimal L;J V{get;set;}static void Main(string[]a){J j=new J();j.H(a[0]);File.WriteAllText(a[1],JsonConvert.SerializeObject(j,j));}public override void WriteJson(JsonWriter w,object o,JsonSerializer s){J j=(J)o;w.WriteStartObject();foreach(var p in j.P){w.WritePropertyName(p.Key);w.WriteValue(p.Value);}if(j.C.Count>0){w.WritePropertyName("Children");w.WriteStartArray();foreach(J c in j.C)s.Serialize(w,c);w.WriteEndArray();}w.WriteEndObject();}public override object ReadJson(JsonReader r,Type t,object o,JsonSerializer s){return o;}public override bool CanConvert(Type o){return o==typeof(J);}void H(string f){var h=new HtmlDocument();h.LoadHtml(File.ReadAllText(f));J v=this;foreach(var p in h.DocumentNode.Descendants().Where(x=>(x.Name=="div"&&x.Ancestors("div").Any()))){var k="";foreach(var s in p.Descendants().Where(x=>x.Name=="span")){var d=new Parser().Parse(".d{"+s.Attributes["style"].Value+"}").StyleRules[0].Declarations;var t=Net.WebUtility.HtmlDecode(s.Descendants("nobr").First().InnerText);if(!d.Any(a=>a.Name=="font-weight"&&a.Term+""=="bold")){A(ref v,k,t);k="";}else{A(ref v,k,"");k=t.Trim(':');foreach(var l in from a in d where a.Name=="left"select decimal.Parse(a.Term.ToString().Replace("in",""),new NumberFormatInfo{NumberDecimalSeparator="."})){while(v.L>l)v=v.V;if(l>v.L){J c=new J{L=l,V=v};v.C.Add(c);v=c;}}}}}}void A(ref J j,string k,string v){if(k=="")return;if(j.P.ContainsKey(k)){J s=new J{L=j.L,V=j.V};j.V.C.Add(s);j=s;}j.P.Add(k,v);}}} ``` ]
[Question] [ # Background Two strings `s` and `t` are called `k`-Abelian equivalent (shortened to `k`-equivalent in the following) for a positive integer `k` if the following conditions hold: * The length-`k-1` prefixes of `s` and `t` are equal. * The length-`k-1` suffixes of `s` and `t` are equal. * The strings `s` and `t` have the same multisets of length-`k` contiguous substrings. In other words, every string of length `k` occurs an equal number of times in `s` and `t`. Overlapping occurrences are counted as distinct. Note that `k`-equivalent strings are always `k-1`-equivalent if `k > 1`, and the third condition implies that `s` and `t` have the same length. It is also [known](http://arxiv.org/abs/1301.5104), and possibly useful, that the three conditions above are equivalent to the following one: * Every non-empty string of length `k` or `k-1` occurs an equal number of times in `s` and `t`. # An Example For example, consider the strings `s = "abbaaabb"` and `t = "aabbaabb"`. Because the strings have the same number of each character, 4 of `a` and 4 of `b`, they are `1`-equivalent. Consider then `2`-equivalence. Their first and last characters are the same (both strings begin with `a` and end with `b`), so the first two conditions are satisfied. The length-`2` substrings of `s` are `aa` (occurs twice), `ab` (twice), `ba` (once), and `bb` (twice), and those of `t` are exactly the same. This means that the strings are `2`-equivalent. However, since their second letters are different, the strings are not `3`-equivalent. # Input Two alphanumeric strings `s` and `t` of the same length `n > 0`. # Output The largest integer `k` between `1` and `n` (inclusive) such that `s` and `t` are `k`-equivalent. If no such `k` exists, the output is `0`. In the above example, the correct output would be `2`. # Rules You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. Crashing on malformed input is perfectly fine. # Test Cases ``` "abc" "def" -> 0 "abbaabbb" "aabbbaab" -> 0 "abbaaabb" "aabbbaab" -> 2 "abbaaabb" "aabbaabb" -> 2 "aaabbaabb" "aabbaaabb" -> 3 "aaabbaabb" "aaabbaabb" -> 9 "abbabaabbaababbabaababbaabbabaab" "abbabaabbaababbaabbabaababbabaab" -> 9 "yzxyxx" "yxyzxx" -> 2 "xxxxxyxxxx" "xxxxyxxxxx" -> 5 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth): ~~26~~ 22 bytes ``` lfq_TTCmmSm<>dbhkldldQ ``` Input are two strings like `"abc","def"`. Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/) ## Explanation: Quite some complicated code. But I'll start easy. First we want to create all substrings of length `k` of the string `d`. ``` Sm<>dbhkld m ld apply a function ... to all elements b in the list [0, 1, 2, ..., len(d)-1] >db take the string d starting from the position b < hk but only hk = k + 1 characters S Sort the resulting list. ``` For the string `"acbde"` and `k = 3` this results in `['abc', 'bde', 'cbd', 'de', 'e']`. Notice, that `'de'` and `'e'` are part of this list. This will be quite important in a bit. I want the substrings for each `k`, one map again. ``` mSm<>dbhkldld m ld apply a function (create all substrings of lenght k) to all elements k in the list [0, 1, 2, ..., len(d)-1] ``` For the string `"acbd"` this results in `[['a', 'b', 'c', 'd'], ['ac', 'bd', 'cb', 'd'], ['acb', 'bd', 'cbd', 'd'], ['acbd', 'bd', 'cbd', 'd']]`. I want this for both strings, another map. ``` mmSm<>dbhkldldQ m Q apply the function (see above) for all d in input() ``` `[[['a', 'b', 'c'], ['ab', 'bc', 'c'], ['abc', 'bc', 'c']], [['d', 'e', 'f'], ['de', 'ef', 'f'], ['def', 'ef', 'f']]]` for the input `"abc","def"`, and after a zip `C`, this looks `[(['a', 'b', 'c'], ['d', 'e', 'f']), (['ab', 'bc', 'c'], ['de', 'ef', 'f']), (['abc', 'bc', 'c'], ['def', 'ef', 'f'])]`. Now comes the exciting part: We are of course only interest in the `k`s, where the substrings of both words are the same. ``` lfq_TTCmmSm<>dbhkldldQ f I filter the list for elements T, where q_TT reversed(T) == T (basically T[0] == T[1]) l print the lenght of the resulting list. (= the number of times, where the substrings of length k of string 1 are equal to the substrings of length k of string 2) ``` Since we also have the suffixes of length < k in Ts, this also checks, if the suffixes are equal. The only thing, which I don't check is, if the prefixes are equal. But as it turns out, this isn't necessary. Lemma 2.3 (4<=>5) of the [linked paper](http://arxiv.org/pdf/1301.5104v1.pdf) says: If the substrings of length `k` are the same, than `pref_{k-1}(string 1) = pref_{k-1}(string 2)` is equivalent to `suff_{k-1}(string 1) = suff_{k-1}(string 2)`. Since the suffixes are equal, the prefixes are also equal. [Answer] # CJam, ~~51 49 47 41~~ 34 bytes ``` WqN/:Q0=,,{Qf{_,,\f>\)f<$}~=},+W=) ``` Just to get something started. This can surely be golfed a lot. Looking at a different algorithm too. Input goes as the two strings without quotes on separate lines. Example: ``` aaabbaabb aabbaaabb ``` Output: ``` 3 ``` [Try it online here](http://cjam.aditsu.net/) ]
[Question] [ A standard road intersection contains 4 sidewalk corners and four crosswalks connecting them. It could also have 2 diagonal walks. ``` sRRRRs iOOOOi dAAAAd eDDDDe side0----1walk ROAD|\ /|ROAD ROAD| \/ |ROAD ROAD| /\ |ROAD ROAD|/ \|ROAD side2----3walk wRRRRw aOOOOa lAAAAl kDDDDk ``` Not all 6 crosswalks are needed to let pedestrians get from any corner to any other (assuming no jaywalking). It's better for traffic and cheaper for the highway department if there are fewer crosswalks. However, it is better for pedestrians if they can get across faster. Let L be the total length of the crosswalks present in the intersection. Assume the intersection is a unit square, so the length of orthogonal walks is 1 and for diagonal walks it's sqrt(2). Let W be the average distance a pedestrian needs to walk when crossing the intersection. Each corner fills up with pedestrians evenly and each pedestrian at a corner is randomly headed for one of the 3 other corners with equal chance. When L and W are low we have an efficient intersection. Let `E = 1 / (W * L)` be the crosswalk efficiency of a particular set of crosswalks. Higher E means more efficient. ## Goal Write a program that takes in a list of present crosswalks and outputs the efficiency. Input will come from stdin in the form `01 32 21` (for example), which represents an intersection with crosswalks from corners 0 to 1, 3 to 2, and 2 to 1 (in a Z). Output to stdout. Running your program might look something like ``` $ crosswalk.mylanguage 01 23 0.0 ``` ## Scoring This is code golf. The submission with the fewest characters wins. ## Details * Pedestrians always stay on the crosswalks and always take the shortest route. * Pedestrians can change direction where the diagonals meet (and at corners). * If all corners aren't connected take W to be infinity (and E to be 0). * The input crosswalk edges are always unique and there are only up to 6. * The input or corner order doesn't matter. `01 32 21` is the same as `23 21 10`. [Answer] # Python 3 - 424 characters This uses precalculated values for W: ``` u,s=list(map(list,[map(int,x) for x in input().split()])),2**.5 q,p,o,w,e,r=sum(u,[]),(2*s+1)/3,(s+1)/3,(2*s+3)/3,(s+3)/3,(5*s+1)/6 print(.0 if len(set(q))<4 or len(q)<5 and q[0]^q[1]==q[2]^q[3]!=3 else 1/({66:p,80:p,34:w,48:w,42:e,49:e,10:5/3,17:5/3,72:r,65:r,74:o,81:o,73:p,41:(s+2)/2,64:s,18:4/3,82:(s+2)/3,50:(s+6)/6}[sum([(0,1,8,32)[q[x]^q[x+1]] for x in range(0,len(q),2)])]*sum(map(lambda a:(1,s)[a[0]^a[1]==3],u)))) ``` It can be run like this: ``` echo 32 01 31 | python3 filename.py ``` [Answer] # Python - 489 Uses all pairs shortest paths. ``` import re R=re.sub exec R("I"," in ",R("F","for ","""s,m,i=sum,map,int r=2**.5/2 n=1e309 g=[0,1,1,n,r],[1,0,n,1,r],[1,n,0,1,r],[n,1,1,0,r],[r]*4+[0] f="01021323" o=lambda v:[list(v[x:x+2])FxIrange(0,len(v),2)] v=o(f+"04142434") q=m(sorted,R("12|21","14 24",R("03|30","04 34",raw_input())).split()) r=range(5) u=[m(i,x)FxIv if x notIq] l=s(g[i(y)][i(x)]Fy,xIq) Fy,xIu:g[y][x]=n FaIr: FbIr: FcIr:g[b][c]=min(g[b][a]+g[a][c],g[b][c]) w=s(g[i(y)][i(x)]Fy,xIo(f+"0312"))/6. print 1/(w*l)""")) ``` ]
[Question] [ **This question already has answers here**: [We're no strangers to code golf, you know the rules, and so do I](/questions/6043/were-no-strangers-to-code-golf-you-know-the-rules-and-so-do-i) (73 answers) Closed 9 years ago. The challenge is programming a program that prints following lyrics of Louis Armstrong's *What A Wonderful World* with as few characters as possible. The key is obviously kind of a 'compression'. I encourage to use and enhance ideas of previous answers, but please declare if you do so! **Rules**: No information can be stored externally, everything must be contained in the code itself. Only ASCII characters allwed in the code. The text must be reproduced exactly. Output to console or text file. ``` I see trees of green, red roses, too, I see them bloom, for me and you And I think to myself What a wonderful world. I see skies of blue, and clouds of white, The bright blessed day, the dark sacred night And I think to myself What a wonderful world. The colors of the rainbow, so pretty in the sky, Are also on the faces of people going by. I see friends shaking hands, sayin', "How do you do?" They're really sayin', "I love you." I hear babies cryin'. I watch them grow. They'll learn much more than I'll ever know And I think to myself What a wonderful world Yes, I think to myself What a wonderful world ``` PS: Why I think this is different to other encoded songs: Longer text; ASCII-only; a lot of repeating text/similar text. EDIT: FEWEST of course. Ending will be 22th of June! [Answer] # Cobra - 585 Still many improvements to be made ``` class P def main i='I see ' f='s of ' w=' I think to myself\nWhat a wonderful world' a='\nAnd[w]' t=' the ' s=' sayin\', "' print "[i]trees of green, red roses, too,\n[i]them bloom, for me and you[a].\n\n[i]skie[f]blue, and cloud[f]white,\nThe bright blessed day,[t]dark sacred night[a].\n\nThe colors of[t]rainbow, so pretty in[t]sky,\n are also on[t]face[f]people going by.\n[i]friends shaking hands,[s]How do you do?\"\nThey're really[s]I love you.\"\n\nI hear babies cryin'. I watch them grow.\nThey'll learn much more than I'll ever know\nAnd[w]\n\nYes,[w]" ``` ]
[Question] [ There have been a few square root challenges lately, but I think this one is different. # Challenge Find an algorithm such that the worst case time complexity is proportional to `n^2` and the best case is proportional to `n` where `n` is the size of the algorithm input. Given a value `x`, find the approximate square root of `x` by running the chosen algorithm with some number of inputs (to be decided in code) arranged to give worst case performance; rearrange the algorithm input values to give best case performance, which will approximate the square root of the worst case run time. Psuedocode example to help explain the challenge: ``` input target is 9 // find square root of 9 // target time is then 9000 ms do { create array with 10000 elements populate array in reverse order (array[0] = 10000; array[1] = 9999; etc) time how long it takes to bubble sort array if (time to sort > 9000 ms + margin of error) { sorting took too long; decrease array size } else if (time to sort < 9000 ms - margin of error) { sorting didn't take long enough; increase array size } } while (run time is outside of 9000 ms +/- margin of error) // the number of elements it takes to sort in n^2 time is now known create array with correct number of elements fill array with zeros return the amount of time it takes to bubble sort ``` Implementing the above in C as a rough prototype takes 110 seconds to determine the square root of 9 is 3.781. # Rules * Input is read from stdin, file, hard-coded, wherever, as long as any positive integer can be used for input, and the program will approximate the square root. For hard-coded values, changing the input constant should be the only change needed to approximate another square root. * An algorithm must be used and must have worst case time complexity of `n^2` and best case time complexity of `n`. * When changing form worst case to best case run time, the number of inputs must be the same. * I'm assuming that measuring run time will actually be difficult and probably slightly inaccurate. Additionally, time complexity does not mean that run time is exactly equivalent to input size, therefore the answer only needs to be accurate to within +/- 25% of the actual square root. Bonus points for improved accuracy. * Any built in math functions are available for use, but the actual square root calculation must come from measuring the best case run time. That is, calculating the square root of the input and then searching for a best case run time equivalent to the square root is allowed, but somewhat discouraged. The spirit of the challenge is to find the square root by measuring worst case run times. * Program run time must be "reasonable," say, less than an hour. [Answer] # C(++), 93 Bytes My solution: ``` int s(int a){int b=0;for(int i=1<<15;i>0;i/=2){if((b+i)*(b+i)<=a)b+=i;else{for(int j=1;j<i;j*=2);}}return b;} ``` It is O(n) for a = 0xFFFF..., and O(n^2) for a = 0x1000... And it returns floor(sqrt(x)), which is an approximation of sqrt(x) However, If you want an algorithm that works in O(n) time, you can shave off 28 bytes. For test cases, append: ``` int main() { int a = 1024; return s(a); //returns sqrt(1024) = 32 } ``` ]
[Question] [ A dog is leashed to a pole and the owner wants to know if it can venture to the neighbour's building. You're given a map, which contains the pole (represented by `x`), the owner's buildings (represented by `1`) and the neighbour's building (represented by `2`). Empty areas are padded with dots and every line has the same length. **EDIT: I forgot to mention, neighbour is always to the right from the dog.** Every tile represents an area of one square meter. You're also given the length of the dog's leash (as meters). The pole is at the center of the tile. For input you must use the STDIN (and respectively STDOUT for output), if it's available in your language. Otherwise create a function, which takes the input as parameters and returns the answer. An example input to the STDIN would look like this. ``` 6 ............ ...11..222.. ...11..222.. ...11....... .x.11....... ............ ``` Additional newline is guaranteed after the input. The program should output `Yes` if the dog can reach the neighbour's building and otherwise `No`. ## Assumptions * There can be several buildings belonging to the owner. * There can only be one neighbour's building. * The dog can't venture outside the map or through the buildings. * The dog can't be trapped inside a building. * The length of the leash is always an integer * Distances are calculated in Euclidean metric. This is a codegolf, shortest code wins. ## Test cases Input: ``` 6 ............ ...11..222.. ...11..222.. ...11....... .x.11....... ............ ``` Output: `No` Input: ``` 7 ............ ...11..222.. ...11..222.. ...11....... .x.11....... ............ ``` Output: `Yes` Input: ``` 7 ........ ...11... ..111.22 ..111.22 .x111.22 ..111.22 ..111... ``` Output: `No` Input: ``` 8 ........ ...11... ..111.22 ..111.22 .x111.22 ..111.22 ..111... ``` Output: `Yes` [Answer] ## PHP 781 chars I know this can be smaller but I am sorry that I am confused. If I take your first two examples (answers no and yes), if diagonal moves are not allowed, answers should be no and no, surely. If diagonal moves are allowed, answers should be yes and yes. Have I misunderstood? I also took beside to be the criteria of 'reached' as the dog can then wee on the building - however changing that to on top of can easily be done changing the pass counter which currently equals leash length. Anyway, this allows for diagonal movement, non diagonal would be smaller than this. ``` <?php $a.='7 ............ ...11..222.. ...11..222.. ...11....... .x.11....... ...........';$b='No';$c=array();$d=array();function check_2($e,$f){if(($c[$e+1][$f-1]=='2')OR($c[$e+1][$f]=='2')OR($c[$e+1][$f+1]=='2')OR($c[$e][$f-1]=='2')OR($c[$e][$f]=='2')OR($c[$e][$f+1]=='2')OR($c[$e-1][$f-1]=='2')OR($c[$e-1][$f]=='2')OR($c[$e-1][$f+1]=='2')){return TRUE;;}else{return FALSE;}}str_replace("\n\r","\n",$a);$g=explode("\n",$a);$h=$g[0];unset($g[0]);$i=count($g);$j=0;foreach($g as $k){$l=str_split($k);$m=count($l)+1;unset($l[$m]);$c[$j]=$l;++$j;}$d=$c;for($n=0;$n<=$h;++$n){for($e=0;$e<$i;++$e){for($f=0;$f<$m;++$f){if($c[$e][$f]=='2'){$b='Yes';}if($c[$e][$f]=='x'){for($o=-1;$o<2;++$o){for($p=-1;$p<2;++$p){if($c[$e+$o][$f+$p]=='.'){$d[$e+$o][$f+$p]='x';}}}}}}$c=$d;}echo $b;?> ``` I am pretty sure I can make this smaller but with the confusion not sure which way to go. Anyway this is my first flood fill so I am sure it can be done more efficiently. Most of the work was getting the input into a variable and a multi dimensional array. The input it contained in the first variable $a. You can see it [here](http://codepad.org/u3iB7pMd) on codepad. I hope you like it. As a relative newbie and since this is the only answer I suppose I am officially winning here at the moment. Although I cannot imagine this will last long if someone else enters :-) ]
[Question] [ With equations that have more than one unknown, [simultaneous equations](https://en.wikipedia.org/wiki/Simultaneous_equations) can be used in solving for them. This challenge will only deal with [linear equations](https://en.wikipedia.org/wiki/System_of_linear_equations) with two unknowns, to make things as elementary as possible. The program should take two lines of input from stdin, each containing a linear equation with two unknowns (`x` and `y`). Output should be in the form `x=<x-value>, y=<y-value>`, where the angled bracketed text should be replaced by the appropriate value. Non-integer values can be outputted in either decimal point form rounded to at least 3 decimal places or until the fraction terminates (eg. `1/2` would be `0.5` not `0.500`), or simplest (improper, not mixed) fraction form (as all results will be rational). If the equations are unsolvable (ie are parallel but not equivalent), output `Unsolvable`. If the equations are equivalent and would therefore have an infinite number of solutions, output `Degenerate`. The use of external modules is not allowed. Also, any library functions that solve equations (this applies especially to Mathematica) are not allowed. Each equation in the input will be in [general form](http://www.mathsisfun.com/algebra/line-equation-general-form.html), with no whitespace. If a coefficent or the constant term is 0, the whole term will not appear, and if a coefficient is ±1, only the pronumeral will appear. Test cases: ``` Input: Input: Input: Input: 7x+4y-8=0 4x+3y+32=0 x-y=0 2x+5y-1=0 x-8y+1=0 x-4=0 x-y+5=0 2x+5y-1=0 Output: Output: Output: Output: x=1, y=1/4 (or 0.25) x=4, y=-16 Unsolvable Degenerate ``` This is once again [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. [Answer] ## Python 3, 250 I reuse the code for parsing the input for each of the "coefficients" of x, y, and "=" by putting it into a string and multiplying it the right number of times. For the "coefficient of =" case to work (absence means 0, not 1, like for x and y), the last "0" of the input has to be thrown away (and then magic takes over...). Makes heavy use of short circuiting in logic expressions, and of `False==0`. Uses Python's feature of leaving off trailing zeros of floats (finding out if the solution is an integer is still necessary). ``` exec((("R=input()[:-1];"+"*_,R=I,*_=R.split(%r);%s=R!=I and int(I in'+-'and I+'1'or I);"*3)*2)%tuple("xXyY=Cxxyy=c")) d,u,v=X*y-Y*x,C*y-c*Y,X*c-x*C print(d and"x=%s, y=%s"%(u%d and-u/d or-u//d,v%d and-v/d or-v//d)or"UDnesgoelnvearbaltee"[u==v==0::2]) ``` [Answer] ## Python 2 - 497 ``` def i(x):return-1 if x=="-"else int(x)if x else 1 def g(a,b):return g(b,a%b) if b else a r=raw_input u=r()[:-2] v=r()[:-2] t=u==v a=u.find("x") a,u=0 if a<0 else i(u[:a]),u[a+1:] b=u.find("y") b,u=0 if b<0 else i(u[:b]),u[b+1:] e=-i(u) if u else 0 c=v.find("x") c,v=0 if c<0 else i(v[:c]),v[c+1:] d=v.find("y") d,v=0 if d<0 else i(v[:d]),v[d+1:] f=-i(v) if v else 0 x,y,z=e*d-f*b,a*f-c*e,a*d-b*c m,n=g(x,z),g(y,z) print"Degenerate"if t else"x=%d/%d, y=%d/%d"%(x/m,z/m,y/n,z/n)if z else"Unsolvable" ``` [Answer] ## Python 2, 244 chars ``` import re def P():e=re.sub(r'(\d)(x|y)',r'\1*\2',raw_input()[:-2]);x=y=0.;c=eval(e);x=1;a=eval(e)-c;x,y=y,x;return a,eval(e)-c,c a,b,c=P() d,e,f=P() D=a*e-d*b X=b*f-c*e print'x=%g, y=%g'%(X/D,(c*d-a*f)/D)if D else'UDnesgoelnvearbaltee'[X==0::2] ``` Throws some `*` characters in the right place, then evaluates the LHS on various combinations of x,y in {0,1} to derive the coefficients. Then it does the standard determinant computations to find the solution. ]
[Question] [ Congratulations, you're now a network administrator! As your first task you will need to configure a firewall to stop any traffic to some blacklisted addresses. Unfortunately, the only firewall at your disposal only takes in rules in this format: `x.y.z.t/m ALLOW` There's no `DENY` keyword. If you want to exclude a specific address, you'll have to write a lot of rules to allow everything **except** that address. If you want to exclude more than one address or a whole range, then you're in luck because these `ALLOW` rules will overlap to some degree. ### The challenge You are given a list of blacklisted IPs. Write a program that will print out rules for our firewall. Also, be sensible when writing rules: don't just enumerate all 256^4 and don't print out duplicates. Code golf rules apply: **shortest code wins** *\*this problem is inspired by a real life assignment; a friend actually needed this done* ### Example To block address 0.1.2.3 you could write the following `ALLOW` rules (this is not the only solution possible, and it's certainly not the shortest): ``` 0.1.2.0 ALLOW 0.1.2.1 ALLOW 0.1.2.2 ALLOW 0.1.2.4 ALLOW ... 0.1.2.255 ALLOW 0.1.0.0/24 ALLOW 0.1.1.0/24 ALLOW 0.1.4.0/24 ALLOW ... 0.1.255.0/24 ALLOW 0.0.0.0/16 ALLOW 0.2.0.0/16 ALLOW ... 0.255.0.0/16 ALLOW 1.0.0.0/8 ALLOW ... 255.0.0.0/8 ALLOW ``` [Answer] # Python3 - 325 chars ``` import sys r=[(0,32)] for b in (int('%02x'*4%tuple(int(x) for x in y.split('.')),16) for y in sys.stdin): i=0 while i<len(r):l,q=r[i];o=2**q//2;m=l+o;h=m+o;k=l<=b<h;r[i:i+1]=[(l,q-k),(m,q-k)][0:k+1*(not l==h==b)];i+=1-k for n,m in r:print('%s/%d ALLOW'%('.'.join(str(int(('%08x'%n)[i:i+2],16)) for i in range(0,8,2)),32-m)) ``` [Answer] # Python 3: 253 characters Yay, Python! ``` from ipaddress import * import sys def e(x,a): b=[] for i in a: try: b+=i.address_exclude(ip_network(x)) except ValueError: b+=[i] return b a=[ip_network('0.0.0.0/0')] for h in sys.stdin: for i in h.split(): a=e(i,a) for i in a: print(i,'ALLOW') ``` It accepts a list of addresses on stdin, separated by any (ASCII) whitespace you like (no commas, though). You can save 12 characters by replacing the stdin loop with `for i in sys.stdin: a=e(i.strip(),a)`. The `strip()` is necessary to get rid of a trailing newline anyway, though, so I figured I'd use `split()` and another `for` loop and allow any whitespace. You can probably save a few more characters by moving the code out of that pesky function. I didn't because I figured I was already confusing myself enough. [You can also make it work for IPv6 instead by changing only one line.](https://codegolf.stackexchange.com/a/22579/13547) ## Ungolfed version: ``` #!/usr/bin/env python3 import ipaddress import sys def exclude(address, networks): new_networks = [] for network in networks: try: new_networks.extend(network.address_exclude(ipaddress.ip_network(address))) except ValueError: new_networks.append(network) except TypeError: pass return new_networks networks = [ipaddress.IPv6Network('::/0'), ipaddress.IPv4Network('0.0.0.0/0')] for line in sys.stdin: for address in line.split(): networks = exclude(line, networks) for network in networks: print(network) ``` This one has the added benefit of working for IPv4 *and* IPv6, no tweaking necessary. :) [Answer] # PHP 5.3, 465 characters ``` $r=array_map(function($v){return explode('.',$v);},$w);$l=256;$n=" ALLOW\r\n";$o='';$a=$b=$c=$d=range(0,$l-1);foreach($r as$i){unset($a[$i[0]],$b[$i[1]],$c[$i[2]],$d[$i[3]]);}for($x=0;$x<$l;$x++){for($y=0;$y<$l;$y++){for($z=0;$z<$l;$z++){for($t=0;$t<$l;$t++){$k="$x.$y.$z.$t";if(isset($a[$x])){$o.="$k/8$n";break 3;}elseif(isset($b[$y])){$o.="$k/16$n";break 2;}elseif(isset($c[$z])){$o.="$k/24$n";break;}else$o.=isset($d[$t])?"$k$n":'';}}}}file_put_contents($p,$o); ``` **Usage:** ``` $w = array('2.5.5.4', '1.2.3.4'); $p = 'data.txt'; $r=array_map(function($v){return explode('.',$v);},$w);$l=256;$n=" ALLOW\r\n";$o='';$a=$b=$c=$d=range(0,$l-1);foreach($r as$i){unset($a[$i[0]],$b[$i[1]],$c[$i[2]],$d[$i[3]]);}for($x=0;$x<$l;$x++){for($y=0;$y<$l;$y++){for($z=0;$z<$l;$z++){for($t=0;$t<$l;$t++){$k="$x.$y.$z.$t";if(isset($a[$x])){$o.="$k/8$n";break 3;}elseif(isset($b[$y])){$o.="$k/16$n";break 2;}elseif(isset($c[$z])){$o.="$k/24$n";break;}else$o.=isset($d[$t])?"$k$n":'';}}}}file_put_contents($p,$o); ``` This will write to data.txt **Uncompressed:** ``` $deny = array('2.5.5.4', '1.2.3.4'); $file = 'data.txt'; $list = array_map(function($v){return explode('.', $v);}, $deny); $l = 256; $n = " ALLOW\r\n";$o = ''; $first = $second = $third = $fourth = range(0,$l-1); foreach($list as $ip){unset($first[$ip[0]], $second[$ip[1]], $third[$ip[2]], $fourth[$ip[3]]);} for($x=0;$x<$l;$x++){ for($y=0;$y<$l;$y++){ for($z=0;$z<$l;$z++){ for($t=0;$t<$l;$t++){ if(isset($first[$x])){ $o .= "$x.0.0.0/8$n";break 3; }else{ if(isset($second[$y])){ $o.="$x.$y.0.0/16$n";break 2; }else{ if(isset($third[$z])){ $o.="$x.$y.$z.0/24$n";break 1; }else{ if(isset($fourth[$t])){ $o.="$x.$y.$z.$t$n"; } } } } } } } } file_put_contents($file, $o); ``` ]
[Question] [ This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge: **Given a specific board in the game of Othello (Reversi), find a move for Black that will capture the maximum number of White pieces.** (Obviously, this may not be the true "optimal" play for Black, but to keep things simple we are only interested in finding the move that will capture the most pieces.) If you are unfamiliar with the rules of Othello (Reversi), you may refer to: <http://en.wikipedia.org/wiki/Reversi> * Input will be provided as a file, or through stdin (your choice). * You may assume that the board will be a standard 8x8 size. * Black pieces will be indicated by `b` and White pieces will be indicated by `w`. Empty spaces will be indicated by `.` * The input may not necessarily be a valid board reachable by the rules of the game. Regardless, you must still find the optimal move following the rules of the game. * Your program must output the move by Black that will capture the most White pieces. If there is a tie, you may choose to output any (or all) of the moves. If there is no valid move, your program must indicate so by outputting `x`. * Your output can be provided as a coordinate, such as `(3,4)`, or in algebraic notation, such as `b5`. When submitting your answer, please clearly indicate your output format and specify where your coordinate system starts from. Sample input: ``` ........ ..b..... ...b.... ...wwww. ...wb... ........ ........ ........ ``` Sample output in (row,col) format, with (0,0) in the top-left corner: ``` (5,3) ``` Sample input: ``` ........ ......w. .wwwwww. .wwwwww. .wwwwww. .wwwwww. .b....b. ........ ``` Sample output in algebraic notation, with a1 in the bottom-left corner: ``` b7 ``` Sample input: ``` ........ ........ ..bbbb.. ..bwwb.. ..bwwb.. ..bbbb.. ........ ........ ``` Sample output: ``` x ``` This is code golf, so the shortest solution will be accepted. [Answer] ## Python, 184 chars ``` import os,re M=os.read(0,99) s=0 t='x' for p in range(72): c=sum(len(re.match(r'\.w+b|',M[p::d]).group()[2:])for d in(-10,-9,-8,-1,1,8,9,10)) if c>s:s=c;t='(%d,%d)'%(p/9,p%9) print t ``` Coordinates are given as (y,x) with (0,0) in the upper left. ``` $ ./othello.py < othello1 (5,3) $ ./othello.py < othello2 (1,1) $ ./othello.py < othello3 x ``` ]
[Question] [ Inspired by this on Spiked Math: [![](https://i.stack.imgur.com/adp2q.png)](http://spikedmath.com/357.html) (source: [spikedmath.com](http://spikedmath.com/comics/357-numerical-integration.png)) In this code golf, you are going to write a numerical integrator. Instead of weighting, you first plot on a graphic canvas pixel-by-pixel or plot on a 2D array, then calculate the integral by counting the colored pixels. You are implementing a function with the following arguments: * `f`: the function, in lambda or function pointer * `xmin`, `xmax`: the interval, also the familiar window settings on a typical graphic calculator * `ymin`, `ymax`: window settings for y-axis, note: it is the caller's responsibility to choose ymax, because the function can go over ymax, and the parts went over will not be counted. * `xres`, `yres`: resolution of the plot: size of the canvas or the dimensions of the 2D array Here is an explanation: To integrate `sin(x)` from 1.0 to 8.0 with y = -1.0 to 1.0, and resolution 30 \* 15, first plot ``` ++++ ++ ++++++ +++ +++++++ ++++ ++++++++ +++++ ++++++++ +++++ +++++++++ ++++++ +++++++++ +++++++ ------------- ----------- ----------- --------- -------- ------- ----- ``` Count the total number of `+`s: 83 total number of `-`s: 64 and N = 83 - 64 = 19 (the formula for N is actually ![formula](https://i.stack.imgur.com/wbehE.gif) notice `xres-1`, x never equal to `xres`, don't make this off-by-one error ) and calculate the integral: ``` N / canvas size * window area = (N / (xres * yres) ) * ((ymax - ymin) * (xmax - xmin)) = 19 / (30 * 15) * ((1 - (-1)) * (8 - 1)) ~= 0.5911 ``` Shortest code wins. Test cases: ``` | f(x) | xmin | xmax | ymin | ymax | xres | yres | S f(x) dx | | 3 | 0.0 | 10.0 | 0.0 | 2.0 | 25 | 25 | 20.0 | | 3 | 0.0 | 10.0 | 0.0 | 5.0 | 5 | 5 | 30.0 | | 3 | 0.0 | 10.0 | 0.0 | 4.0 | 5 | 5 | 32.0 | | 2x + 2 | -5.0 | 5.0 | -10.0 | 10.0 | 50 | 50 | 18.72 | | 2x + 2 | -5.0 | 5.0 | -20.0 | 20.0 | 500 | 500 | 20.1648 | | x^2 | 0.0 | 10.0 | 0.0 | 120.0 | 10 | 10 | 348.0 | | x^2 | 0.0 | 10.0 | 0.0 | 120.0 | 100 | 100 | 335.88 | | x^2 | 0.0 | 10.0 | 0.0 | 120.0 | 500 | 500 | 333.6768 | | x^2 sin(x) | -3.14 | 3.14 | -5.0 | 5.0 | 50 | 50 | 0.60288 | | x^2 sin(x) | -3.14 | 3.14 | -5.0 | 5.0 | 1500 | 1500 | 0.60288 | | sin(x^2) | 0.0 | 10.0 | -1.0 | 1.0 | 250 | 50 | 0.7808 | | sin(x^2) | 0.0 | 10.0 | -1.0 | 1.0 | 1000 | 1000 | 0.59628 | ``` [Answer] **Lua, 219 chars** Done it all in 1 step, no need for an intermediate table. Plots the function too ;) ``` function I(f,x,X,y,Y,r,R)I=io.write N=0 for k=R-1,0,-1 do for l=0,r-1 do v=f(x+l*(X-x)/r) K=y+k*(Y-y)/R c=(K<0 and K>v)and'-'or(K>0 and K<v and'+')or' 'N=c=="+"and N+1 or(c=="-"and N-1 or N)I(c)end I'\n'end return N end ``` Test code: ``` assert(I(math.sin,1.0,8.0,-1,1,30,15)==19) ``` ]
[Question] [ Given π to an arbitrary number of places, your challenge is to locate indices of π where the index (1,2,3,4...) and the string of numbers from that index carry the same value for the length of the index. That sounds complex, so let's look at an example! Indices will count from +1 upwards through natural whole integers, skipping 0 as the first index: 1, 2, 3, 4,.... up to an arbitrary whole positive number. If the number being used (instead of π) was: `123456789101112` then for each index value 1... the sequence of numbers at that index position would match with the value of the index. At position `1` the string '1' can be found ``` 123456789101112 ^ ``` At position `2` the string '2' can be found ``` 123456789101112 ^ ``` If this sequence continue to 10, you'd find that at position `10` the sequence '10' is found. ``` 123456789101112 ^ ``` However, when you reach position `11`, you find '01', not '11'. ``` 123456789101112 ^ ``` Given an input value of π of the format: `3.14159...` and taking off `3.` to give `14159...` using indices start at 1, so the first string found at index 1 is "1", the first string found at index 2 is "4", etc. Find the shortest code to locate the first 4 indices where the set of characters at that index position have the same numerical sequence as the numbers that make up the index. Shortest wins! Built-ins are allowed Examples of finding the nth digit of pi: [Find the nth decimal of pi](https://codegolf.stackexchange.com/questions/84444/find-the-nth-decimal-of-pi) The major step here is to make the comparison of the nth digit and 'n' to determine if there's a match. \*\* First Match \*\* 3.14159265 1 : finds '1' A simple psuedo-code approach might be similar to the following, except this one doesn't account for "3." or the index being off by 1: `assume input=pi to any arbitrary length supported with '3.' removed` ``` for(var index=0, maximumInputLength=input.length; index < maxmimumInputLength; index++) { var indexString = '' + i; var indexLength = indexString.length; if(indexString.substr(index, indexLength) == indexString) { // index found at index'th position } else { // index not found at index'th position } } ``` This style of solution will return '6' found in the 6th index position and '27' found in the 27th index position. Given 141 592 6 (6 is in the 7th position starting at 0). To verify if an answer is correct, you can use the above code to find the nth digit of pi and compare to the value of 'n' in your language of choice! **Thank you for the great feedback in helping me write a better first question.** **Clarifications:** * Is π given as an input - YES [Answer] # Python 2, 64 bytes ``` i=1 while i<len(P): if int(P[i:i+len(str(i))])==i:print i i+=1 ``` As you said, pi's digits are given, so I chose the variable `P` to contain the entire digit string. The full code first downloads [one billion digits of pi](https://stuff.mit.edu/afs/sipb/contrib/pi/pi-billion.txt) to a file using cURL and then reads in that file to process it. ``` "Setting up pi's digits."; exec'import os\nN,f=200000000,"pi.txt"\nif not os.path.exists(f):os.system("curl https://stuff.mit.edu/afs/sipb/contrib/pi/pi-billion.txt>"+f)\nP=open(f,"r").read()[1:N+2][:-1]' "Search through pi."; exec'i=1\nwhile i<len(P):\n\tif int(P[i:i+len(str(i))])==i:print i\n\ti+=1' ``` Though, when one knows the answer, a simple plaintext output is actually shorter (29 bytes). ``` print"1,16470,44899,79873884" ``` This series of numbers is also known to the OEIS (<http://oeis.org/A057680>). ]
[Question] [ **The Challenge** Given a string containing a random sequence of unique characters A to Z (all upper case, no duplicates), determine the cut-and-paste" sort and output the sort sequence to a specific format (detailed below). **Definition of Cut-And-Paste Sort, by Example** Example string: `AKJCFEGHDBI` This string contains 11 characters, of which `A`, `C`, `E`, `G`, `H`, and `I` form the longest "lengthy sequence" from left to right that is in alphabetic order. So we base the cut-and-paste around these key letters. If there is more than one "lengthy sequence" of equal length, the code will always favor the lengthy sequence with the biggest "stretch" across the entire string. In the case of a slightly different string than our original example, `AKGHJCFDEBI`, there are three lengthy sequences of `ACDE`, `AGHJ`, and `AGHI`, but the code will favor the sequence with the greatest stretch, which in this case is `AGHI` because the distance between `A` and `I` is greatest amongst the three as opposed to the `A` to `E` in the first sequence and the `A` to `J` in the second sequence. If there happens to be more than one lengthy sequence with the same stretch length, the first lengthy sequence in alphabetic order will be chosen, just to make it easy. The cut-and-paste sort is simply a case of plucking the appropriate letters not within the key letters and placing them back in their respective positions in alphabetic order. Then the sort from our original example would occur as follows: ``` Step 1: AKJCFEGHDBI Step 2: ABKJCFEGHDI (B gets cut and takes 8 steps to the left and gets pasted after A) Step 3: ABKJCDFEGHI (D gets cut and takes 4 steps to the left and gets pasted after C) Step 4: ABKJCDEFGHI (F gets cut and takes 1 step to the right and gets pasted after E) Step 5: ABKCDEFGHIJ (J gets cut and takes 7 steps to the right and gets pasted after I) Step 6: ABCDEFGHIJK (K gets cut and takes 8 steps to the right and gets pasted after J) ``` To make it easier for the purpose of this challenge we can rewrite this sort as: `B<<<<<<<<D<<<<F>J>>>>>>>K>>>>>>>>` where each letter represents the letter being cut, followed by a series of left or right arrows, represented by the `<` and `>` characters. When the arrows end, it is implied that the letter is pasted. Bear in mind that the number of letters being cut at any one time can be more than one, so long as the letters are sequential. So if there is a string that can have two or more letters cut at any one time, the code should favor using the larger rather than perform two or more individual cut-and-pastes as this will provide a more efficient cut-paste sort. For example: ``` AKGHJCFDEBI Lengthy sequences: ACDE AGHJ AGHI; AGHI is chosen (longest stretch) Step 1: AKGHJCFDEBI Step 2: ABKGHJCFDEI (B<<<<<<<<) Step 3: ABCKGHJFDEI (C<<<<) Step 4: ABCDEKGHJFI (DE<<<<<) Note two or more letters can be moved as long as they are side-by-side Step 5: ABCDEFKGHJI (F<<<<) Step 6: ABCDEFKGHIJ (J>) Step 7: ABCDEFGHIJK (K>>>>) End result: B<<<<<<<<C<<<<DE<<<<<F<<<<J>K>>>> ``` **Code Behavior** The code must take an alphabetic upper case string with unique letters (Please assume that this string will always be upper case and with all unique letters, i.e. no dupliates), and perform a cut-paste sort according to the above rules and provide a formatted string simliar to `B<<<<<<<<C<<<<DE<<<<<F<<<<J>K>>>>` providing the method of cutting and pasting respective letters to achieve a string in alphabetic order. **Test Cases** `AKJCFEGHDBI` Result: `B<<<<<<<<D<<<<F>J>>>>>>>K>>>>>>>>` `AKGHJCFDEBI` Result: `B<<<<<<<<C<<<<DE<<<<<F<<<<J>K>>>>` `BDEFHGI` Result: `H>` `ABC` Result: (already sorted) `CBA` Result: `B>C>>` **Rules** 1. Code Golf: Shortest code wins... 2. Code must be in the form of a piece of STDIN/STDOUT code, or a function taking the input string as a parameter and returning the output string 3. Code must be suported by a working version of the code or verified execution of test cases. 4. In the event that there are two or more with the same character count, the winner will be chosen by the most upvotes. 5. [No silly loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) [Answer] # PHP, 859 bytes not the shortest code (yet?), but for shorter output. Added line breaks for a little reading convenience. ``` function s($u,$a=''){$r=[];for($i=$k=0;$i<strlen($u);$i++)if($u[$i]>substr($a,-1))$r=array_merge($r,s(substr($u,$i+1),$a.$u[$i]));return$r?:[chr(59-strlen($a)).$a];}$w=s($a=$argv[1]);sort($w);$r=preg_split('#_+#',preg_replace("#[$w[0]]#",'_$0_',$a),-1,1);$v=substr;$x=strlen; for($i=count($r);$i--;)if(!strpos($w[0],$q=&$r[$i]))for($o=0;++$o<$x($q);)if($q[$o-1]>$c=$q[$p=$o]){for(;++$p<$x($q) & $q[$p]>$c & $q[$p]<$q[$o-1];)$c.=$q[$p];echo$c;for(;$q[$o-1]>$v($c,-1);echo'<')$q[--$p]=$q[--$o];$q=$v($q,0,$o).$c.$v($q,$p);$o-=2;} for(;$n<count($r);$n=count($r),$r=str_split(join($r),1))for($i=-1;++$i<count($r);)if(!strpos($w[0],$r[$i])){$s=array_splice($r,$i,1);for($e=0,$k=$i;$v($s[0],-1)<$r[--$k][0];)$e-=$x($r[$k]);for(;++$k<count($r) & $s[0][0]>$v($r[$k],-1);)$e+=$x($r[$k]);if($e)echo$s[0].str_repeat('><'[$e<0],abs($e));array_splice($r,$k,0,$s);$i-=$k>$i;} ``` **examples** ``` INPUT KEY OUTPUT RESULT AKJCFEGHDBI ACEGHI B<J<JK>>>>>>>>F>BD<<<<B< ABCDEFGHIJK AKGHJCFDEBI ACDEI GHJ<GHJK>>>>>F>>>B<<<K> BCDEFGHJIK BDEFHGI BDEFGI H> BDEFGHI ABC ABC _empty_ ABC CBA A B<BC> ABC PHCODER CDER H<HP>O>>P>>> CHDEOPR XTREMGOD EGO T<R<<RTX>>>>>M>D<<<< DEGMORTX (I love it) ``` Yup. It fails for `PHCODER`. It´s buggy, but it´s nice. btw: The shortest possible output for that is `O<P>>HOP>>>` (for example). ]
[Question] [ On TeX.SE the Help Centre says that the following is on topic: ``` Formats like LaTeX, ConTeXt and plain TeX Engines like pdfTeX, LuaTeX and XeTeX Distributions like TeX Live, MiKTeX, and MacTeX Related software and tools, BibTeX, MakeIndex, Lyx, etc. ``` I wanted you to write a program to tell me whether my TeX is in the on-topic types of TeX. An explicit list of the valid TeX-s is as follows: * MetaPost * PostScript * MetaFUN * TeX * LaTeX * LuaLaTeX * LuaTeX * ConTeXt * BibTeX * pdfTeX * Lyx * MakeIndex * TeX Live * XeLaTeX * XeTeX * MacTeX * MiKTeX ## Rules * You may use any language. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), to the shortest answer wins. * If you use Regex, you can just match correct ones. * You only need to match one at a time: no Lyx BibTeX * You must check **with capitalization listed here**. ## Tests ``` TeX -> True/1/<match> pTeX -> False/0/<not-match> ConTeXt -> True/1/<match> context -> False/0/<not-match> MetaFun -> False/0/<not-match> MetaFUN -> True/1/<match> ``` *P.S. Bonus points for an on-topic TeX answer!* [Answer] # JavaScript Regex, ~~99~~ ~~101~~ ~~99~~ 97 + 1 for `g` flag = *98 bytes* ``` ^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$ ``` Test it [here](http://regexr.com/3dobl). Type into the `Text` box. Alternatively, test it here. ``` var j = $("#dos"); var text; function abc(){ text = $('#uno').val(); j.val(text.match(/^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$/g) == text ? "Matches!" : "No match!"); }; ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id='uno' /><br /> <button id='tres' onclick="javascript:abc()">Test!</button><br/> <input id='dos' /> ``` Test all cases: ``` var j = $("#dos"); var tests = ["TeX", "pTeX", "ConTeXt", "context", "MetaFun", "MetaFUN", "TeX Live"]; function abc(e){ j.val(j.val() + e + ": " + (e.match(/^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$/g) == e ? "Matches!" : "No match!") + "\n"); }; function def(){ tests.forEach(abc); } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id='tres' onclick="javascript:def()">Test!</button><br/> <textarea rows=50 cols=200 id='dos'> </textarea> ``` [Answer] # Perl 5, 103 bytes 102 bytes, plus 1 for `-pe` instead of `e`. Stdin→stdout. ``` $_=/^(Meta(Post|FUN)|TeX Live|PostScript|((Xe|Lua)?(La)?|Bib|pdf|M(ac|iK))TeX|ConTeXt|Lyx|MakeIndex)$/ ``` [Answer] # Python 3.5, ~~149~~ ~~147~~ ~~137~~ 136 bytes ``` import re;lambda f:re.fullmatch('TeX Live|(La|LuaLa|Lua|Bib|pdf|XeLa|Xe|Mac|MiK)?TeX|Lyx|MakeIndex|Meta(Post|FUN)|PostScript|ConTeXt',f) ``` An anonymous function that uses a regular expression to return a `re` match object (such as `<_sre.SRE_Match object; span=(0, 5), match='LaTeX'>`) as a truthy value and `None` as a falsy value. The actual regular expression is currently **~~102~~ ~~100~~ 99 bytes** in length. [Try It Online! (Ideone)](http://ideone.com/kNIjM1) [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 122 \log\_{256}(96) \approx 100.42 \$ bytes ``` "MetaPost|PostScript|MetaFUN|?|La?|LuaLa?|Lua?|ConTeXt|Bib?|pdf?|Lyx|MakeIndex|? Live|XeLa?|Xe?|Mac?|MiK?"'?"TeX"AR'|ZisAq ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhY3q5R8U0sSA_KLS2pARHByUWZBSQ1IzC3Ur8a-xicRiEsToZR9jXN-XkhqREmNU2aSfU1BShpQuLKixjcxO9UzLyW1osZewSezLLUmIhWkIyLVHiiVDCQyve2V1O2VgFqVHIPUa6Iyix0LIS6AOmTBcqjJEC4A) ``` "..."'?"TeX"AR'|ZisAq # Implicit input "..." # Push the string AR # Replace... '? # ...the character '?'... "TeX" # ...with the string "TeX" Zi # Split the resulting string... '| # By the character '|' sAq # Is the input in this list? # Implicit output ``` ]
[Question] [ # Challenge Your submission should consist of 2 or more programs each written in distinct languages. They can be arbitrarily numbered from 1 to `k`. Each program `p`, given a natural number `n` should print the *next* `n` prime numbers (initially, the *next* prime is the 0-th prime, 2) on a single line, followed by a single blank newline, followed by a program fragment, which, when appended to the `p+1 mod k`th program, produces the program which does precisely the same thing, but with the *next* prime being the `n+1`th prime number. # Details * Your programs may accept its input as a function argument, or from standard input, or the closest equivalent in your languages. * Your programs may not read data from any external source other than to read `n` from standard input. If this data is required by your program, it must be included in the source code fragment generated by the previous program. * Your programs may not compute *any* prime numbers less than the *next* prime number. * The prime numbers may be separated by any delimiter other than a newline. * You may not use any language primitives or libraries for prime number generation - you must write the algorithm yourself. * You *may* use standard libraries for things other than prime generation. * Two languages which differ only in their versions are *not* said to be distinct languages. * Two languages whose semantics largely overlap (for example, C and C++) are *not* said to be distinct. * Your programs may do whatever they like for undefined inputs. * Your programs are required to support generating prime numbers up to 2^32-1. You may assume whatever you need about the runtime environment to ensure this is the case (i.e. you can assume your C program will be run on a machine where `int` has at least 32 bits). If this assumptions is non-trivial it should be stated explicitly. * If running your program involves a non-trivial compilation step it should be stated how to do it, so others can reproduce it. # Input/Output ``` next in out 0 10 2,3,5,7,11,13,17,19,23,29 25 13 101,103,107,109,113,127,131,137,139,149,151,157,163 7 4 19,23,29,31 ``` # Scoring Because disk space is very expensive, your programs should be as small as possible. Because more is obviously better, your submission should consist of as many programs as possible. The score of your submission is the average byte count of your programs divided by the number of distinct languages used. Lowest score wins. [Answer] # Java + Python 2, Score = (302 + 218) / 2 / 2 = 130 Here is a brief explanation on how this works: * **Choose** a program and pick a positive integer, `n`; for Java, pass `n` as a command line argument; for Python, pass `n` through stdin. + The program will then print a list of `n` primes followed by 2 newlines and then a snippet. * **Append** this to a fresh copy of the program which was not chosen. * **Choose** a new `n` and pass it to this modified program + The program will then print a list of `n` primes followed by 2 newlines and then a snippet. * **Append** this to a fresh copy of the program which was originally chosen. * **Rinse, repeat**. --- ## Golfed ### Java, 302 bytes Netbeans is able to compile this even with the `A` class missing, I haven't been able to figure out how. But once I do, I will add the flags to the byte count. ``` public class P{static int i=2;public static void main(String[]a){int l=2,n=Integer.parseInt(a[0]),x;String s="";try{new A().a();}catch(Exception e){}while(n>0){if(i>1){boolean b=false;for(x=2;x<i;x++){if(i%x==0 && i!=2)b=true;}if(!b){s+=s==""?i:","+i;l=i;n--;}i++;}}System.out.print(s+"\n\n+"+(l-1));}} ``` ### Python 2, 218 bytes ``` n=int(input()) s=[] i=-1 while n: if i>1: for x in range(2,i): if i%x==0and i!=2:break else:s+=[i];n-=1 i+=1 if n==0:print",".join(str(y)for y in s)+"\n\nclass A{void a(){P.i="+str(s[-1]+1)+";}}" if i<0:i=2 ``` --- ## Un-Golfed ### Java ``` public class PPCG { public static int i = 2; public static void main(String[] args){ int n = Integer.parseInt(args[0]); int last = 2; String s = ""; try{ new A().a(); }catch(Exception e){} while(n>0){ if(i>1){ boolean broken=false; for(int x=2;x<i;x++){ if(i%x==0 && i!=2){ broken=true; } } if(!broken){ s += s==""?i:","+i; last = i; n-=1; } i+=1; } } System.out.println(s+"\n\n+"+(last-1)); } } ``` ### Python 2 ``` n=int(input()) s=[] i=-1 while n: if i>1: for x in range(2,i): if i%x==0 and i!=2: break else: s+=[i] n -= 1 i+=1 if n==0: print ",".join(str(y) for y in s)+"\n\nclass A{public static void a(){PPCG.i="+str(s[-1]-1)+";}}" if i<0: i = 2 ``` **Update** * **-17** [16-12-13] Misc golfing ]
[Question] [ ## Objective You have two knights on a standard chessboard labelled 1-8 and A-H, one knight is located at 1C and the other at 2G. You have to write a program in the language of your choosing that accepts a set of coordinates from `stdin`, like 2C, and then calculates which of the two knights you have to move in order to capture the enemy pawn at the provided coordinates with the least amount of moves assuming it is standing still. The program must also output which are these moves that the knight has to make. ## Example Usage ``` # echo 1C|./faster Move Knight: 1C Moves: ``` Also ``` # echo 3B|./faster Move Knight: 1C Moves: 1C -> 3B ``` One more ``` # echo 5A|./faster Move Knight: 1C Moves: 1C -> 3B Moves: 3B -> 5A ``` Output shall be exactly as shown. ## Useful Resources [Knight's Tour](https://en.wikipedia.org/wiki/Knight%27s_tour) ## Bonuses You get -50 Bytes if your program is expandable and works with N knights. [Answer] # Mathematica ~~1183~~ 483 bytes (or 190) bytes ## Approach 1 240-50 (bonus) = 190 bytes The knight's tour can be represented as a graph. So the issue becomes simply to find the shortest path from each knight to the pawn. Mathematica offers both `KnightTourGraph` and `FindShortestPath` as built-in functions. ``` w@p_:=Characters@p/.{r_,s_}:>(ToCharacterCode[s][[1]]-65)*8+ToExpression@r z@v_:=ToString@(v~Mod~8/.{0->8})<>FromCharacterCode[Quotient[v-1,8]+65] p_~h~k_:=Row[SortBy[(z/@FindShortestPath[8~KnightTourGraph~8,#,w@p])&/@w/@k,Length][[1]],"->"] ``` **Examples** ``` h["5A",{"1C","2G"}] ``` > > 1C -> 3B -> 5A > > > ``` h["8G",{"1C","2G"}] ``` > > 2G -> 3E -> 5D -> 7E -> 8G > > > --- ## Approach 2 (533-50 (bonus)= 483 bytes) Here the knight's tour graph is constructed without using `KnightTourGraph`. ``` s@v_:= Sort[{v,#}]/.{{a_, b_}:>UndirectedEdge[a,b]}&/@( If[If[#4==1,Greater,Less][Mod[v-1,8]+1,#1]&&If[#5==1,Greater,Less][Quotient[v-1,8]+1,#2],v+#3,Nothing]&@@@{{1,2,-17,1,1},{8,2,-15,0,1},{2,1,-10,1,1},{7,1,-6,0,1},{2,8,6,1,0},{7,8,10,0,0},{1,7,15,1,0},{8,7,17,0,0}}) w@p_:=Characters[p]/.{r_,q_}:>(ToCharacterCode[q][[1]]-65)*8+ToExpression@r z@v_:=ToString@(Mod[v,8]/.{0 -> 8})<>FromCharacterCode[Quotient[v-1,8]+65] p_~f~k_:=Row[SortBy[(z/@FindShortestPath[Graph[Range@64,Union@Flatten[s/@Range@64]],#,w@p])&/@w/@k,Length][[1]],"->"] ``` --- ## Explanation Below are two views of the chessboard. On the left, each chessboard position corresponds to vertex bearing an integer name. On the right, the positions have been labelled according to the convention suggested by the OP. In both figures, White sits on the right, Black sits on the left. [![chessboards](https://i.stack.imgur.com/oZ7Ji.png)](https://i.stack.imgur.com/oZ7Ji.png) Legal moves of a knight are paths along a knight tour graph. The function, `s`, generates all 512 moves (as if each square allowed for 8 knight moves), eliminates inverses, and then weeds out the moves that would land off the board. There are 168 edges on the graph. `edges` consists of a list of elements of the form, `UndirectedEdge[a,b]`. For instance, the edge, `UndirectedEdge[1,11]`corresponds to the idea that a knight at vertex 1, that is, at "A1" in standard notation, may jump to vertex 11, or "B3", and vice-versa. `toVertex` takes a position (see right board) and returns a vertex (see left board). For instance `toVertex["3H"]` returns `59`. `toChessPosition` does the opposing conversion, namely from a vertex to a chess position. `vertexNames` is a list of replacements: `{1->"1A",2->"2A"...64->"8H"}`. This is only needed for the right chessboard figure shown above. `numberedKnightsTour`is the graph displayed above on the left. `chessKnightsTour`is the graph displayed above on the right. The graphs are constructed using the above-defined vertices and edges. `findShortestPath` receives the position of the pawn and a list of positions of the knights and finds the shortest path along the graph from a knight to the pawn. ``` s@v_:= Sort[{v,#}]/.{{a_, b_}:>UndirectedEdge[a,b]}&/@( If[If[#4==1,Greater,Less][Mod[v-1,8]+1,#1]&&If[#5==1,Greater,Less] edges=Union@Flatten[s/@Range@64]; toVertex[p_]:=Characters[p]/.{rank_,file_}:> (ToCharacterCode[file][[1]]-65)*8+ToExpression[rank] toChessPosition[v_]:=ToString@(Mod[v,8]/.{0->8})<>FromCharacterCode[Quotient[v-1,8]+65] vertexNames=Thread[Range@64->(toChessPosition[#]&/@Range[64])]; numberedKnightsTour=Graph[Range@64,edges,VertexLabels->"Name",GraphLayout->"SpringEmbedding"]; vertexNames=Thread[Range[64]->(toChessPosition[#]&/@Range[64])]; chessKnightsTour=Graph[Range@64,edges,ImageSize->Large,VertexLabels-> vertexNames,GraphLayout->"SpringEmbedding"]; GraphicsGrid[{{numberedKnightsTour,chessKnightsTour}},PlotLabel->"For each board below, \nWhite sits at Right, Black at Left\nNumbers refers to rank, letters refer to file",ImageSize->Large] findShortestPath[pawn_,knights_]:=Row[SortBy[(toChessPosition/@FindShortestPath[chessKnightsTour,#,toVertex@pawn])&/@toVertex/@knights,Length][[1]],"->"] ``` --- ]
[Question] [ ## Introduction [![enter image description here](https://i.stack.imgur.com/3NOI8.png)](https://i.stack.imgur.com/3NOI8.png)Today is my birthday, Yes my parents spend a lot time at home during the cold December [**holidays**](https://codegolf.stackexchange.com/questions/57277/its-my-birthday-d) as many [**others**](https://codegolf.stackexchange.com/questions/57597/the-great-british-cake-off?lq=1). So I also want my cake. But I have a problem: I just sent the invitations today so I'm not sure how many friends will come. Also I don't want to order a big cake because I have been on a diet since last year and don't want to keep temptation leftovers in the fridge. ## Challenge Write a full program to output the cake design so my baker prepares just *enough* cake for everyone. Input Integer `1 <= n <= 999`. Worst case I eat my cake [**alone**](https://www.youtube.com/watch?v=ikO4vBwNHWk). * Each slice will have a unique label number `1 .. n` sequenced left to right, then top to bottom. * Write in the middle line and align center the best way you can. * Slice size is a square of 3x3 (this is why upper limit is 999). * `*` indicate where to cut each slice. ## Output n = 1 => Side = RoundUP(sqrt(1)) = 1 ``` ***** * * * 1 * * * ***** ``` n = 3 => Side = RoundUP(sqrt(3)) = 2 ``` ********* * * * * 1 * 2 * * * * ********* * * * 3 * * * ***** ``` n = 5 => Side = RoundUP(sqrt(5)) = 3 ``` ************* * * * * * 1 * 2 * 3 * * * * * ************* * * * * 4 * 5 * * * * ********* ``` n = 10 => Side = RoundUP(sqrt(10)) = 4 ``` ***************** * * * * * * 1 * 2 * 3 * 4 * * * * * * ***************** * * * * * * 5 * 6 * 7 * 8 * * * * * * ***************** * * * * 9 * 10* * * * ********* ``` ## Winning Shortest code in bytes wins. [Answer] # Python 2, ~~241~~ ~~239~~ 237 bytes ``` i=input() s=int(round(i**.5+.5)) q="*"*5;p="* *" v=lambda x,y:"\x1b[%d;%dH".join(["",q,p,"*{}*",p,q])%tuple(i for j in zip(range(x*4+1,x*4+6),[y*4+5]*5)for i in j) print"".join([v(j/s,j%s).format(`j+1`.center(3," "))for j in range(i)]) ``` Lots of ANSI goodness... Defines a function for drawing a box at a position on the screen. Then calls it with the relevant positions that are in the cake. Finally adds the numbers using `str.format()` and `str.center` NOTE: If your terminal isn't big enough to display everything at once, it will get 'cropped' and you won't be able to see anything past the last row. ]
[Question] [ **This question already has answers here**: [Topographic Strings](/questions/6600/topographic-strings) (17 answers) Closed 8 years ago. Write a program or function that takes in a string through STDIN or function parameters, tokenizes it by parenthesis, and outputs the tokens on different lines. If the string contains a parentheses error, the program/function must output a falsey value or error message. ### Examples: **Input:** `abc(def)ghi` **Output:** ``` abc ghi def ``` **Input:** `abc(def(ghi))jklm(n)op((q))rs` **Output:** ``` abc jklm op rs def n ghi q ``` **Input:** `blah(blah)(blah` **Output:** ``` Error ``` ### Notes: * The falsey value or error message must be generated by program, and the program must terminate successfully. A built in error message due to a crash does not count. * This is code golf. I will accept the shortest answer in bytes one month from today (July 30th). * No standard loopholes. [Answer] # Cobra - 238 ``` def f(s='') x,y,l=0,0,for n in (r=s.count('('))get' '.repeat(s.length-2*r) try for c in s,branch c on c'(',y+=1 on c')',y-=1 else,l[y]=l[y][:x]+'[c]'+l[y][x+=1:] assert y==0 catch print'Error' success,print l.join('\n') ``` ]
[Question] [ You should write a program or function which given a string as input outputs or returns a string or list of the lowercase letters in the order they find their uppercase pair. The input is a string consisting of the characters `[a-zA-Z] space` and `newline` representing a torus (rectangular grid with wrap around for rows and columns) with some of the letters `a-z` and for every lowercase letter exactly one of its uppercase equal. Every lowercase letter has a field of view equal to `ord(letter)-97` grid steps i.e. `a=0, b=1, ... , z=25` where `0` means you can only see your own cell. Steps (and field of view) are possible in all 8 directions. At every step: * if a lowercase letter sees its uppercase pair (e.g. `C` for `c`) it will go straight to it * if a lowercase letter doesn't see its uppercase pair it will move to the bottom right neighbor cell wrapping around if necessary. There can be multiple letters at the same position. They don't block each other. You should output or return the lowercase letters in the same order they reach their uppercase pair. If multiple letters reach their pair at the same step they should be outputted in alphabetical order. If a letter newer reaches its pair it shouldn't be outputted at all. ## Input * A string received in any reasonable way. * Contains only letters `[a-zA-Z]` (at most one from each character; at least one pair of letters), spaces and newlines. * Input will form a proper rectangle, i.e. there will be the same number of characters between every newline. * Trailing newline is optional. ## Output * A list of lowercase letters in the order they reach their pair. * Output can be in any reasonable data-structure (string, list, array etc.) and can be outputted or returned. * Trailing newline is optional. ## Examples Input is all the rows between `Input:` and `Visualization:`. In visualization `*` marks all cells visited by letters. Other valid visualizations are possible as when a letter sees its pair often multiple shortest paths are possible. *Space only lines are empty below. Check correct inputs [here](http://pastebin.com/raw.php?i=ApSLKQi5).* ``` Input: D d Aa Visualization: * D* * d Aa * * Output: da Step numbers: 2 5 Input: W B A b a w Visualization: ** * W * B *A b * * * * a w * * ** * Output: wb Step numbers: 3 6 Input: A a Visualization: * ***** ** **** *** A** **** * ***** *****a ****** Output: a Step numbers: 39 Input: i f d DI F Visualization: i f * d * * * * ** ***DI**F Output: idf Step numbers: 4 6 6 Input: g a G W j w A J Visualization: * * * * * * * * * * * * * * * * * * * g * a * * * * * * * * * * * * * * * * * * ***G * *****W * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * j * * * * * w * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * A * ***J * * * * * * * * * * * * * * * * * * Output: gwj Step numbers: 6 11 28 ``` This is code-golf so the shortest entry wins. [Answer] # Ruby ~~319 313 310 304 287~~ 283 ``` F=->s{l=s.split ?\n b=[] t={} [*0...m=l.size].product([*0...n=l[0].size]).map{|y,x|c=l[y][x] c!=' '&&c>?Z?b<<[c,y,x]:t[c.downcase]=[y,x]} b.map{|q|c,y,x=q u,i=t[c] (m*n).times{|w|e=([u-(y+w)%m,i-(x+w)%n].map &:abs).max e>c.ord-97||q<<w+e} q[3]&&[q[3],q[0]]}.compact.sort.map{|a,b|b}} ``` This is a function that takes as input a string (without trailing newline) and returns an array of the lowercase letters in the correct order. Here's a version you can run online with tests: <http://ideone.com/5jiwLq> I've made a lot of modifications to the code. The history of modifications is available [here](https://github.com/clupascu/codegolf/commits/master/finding-pairs-for-letters/finding-pairs-for-letters-golfed.rb). Here's the indented and annotated version to make it easier to see what's going on (also available [online](http://ideone.com/9lJXVm)): ``` F=->s{ l=s.split ?\n m=l.size n=l[0].size # Make an array with lowercase letters and their coords (`b`) # Make a hash that for each target (uppercase letter) holds # its coordinates b=[] t={} [*0...m].product([*0...n]).map{|y,x| c=l[y][x] c!=' '&&(c>?Z?b<<[c,y,x]:t[c.downcase]=[y,x]) } # `l` is a function that, given an array of the form # [lowercase_letter, y-coord, x-coord] will append to that array # the number of steps required for the letter to reach its # uppercase correspondent l=->q{ c,y,x=q u,i=t[c] d=c.ord-97 (m*n).times{|w| e=([u-y,i-x].map &:abs).max e<=d&&q<<w+e y=(y+1)%m x=(x+1)%n } } # apply function `l` to each of the lowercase letters... b.map &l # ...then sort accordingly and return the array b.map{|x|[x[3],x[0]]}.select{|a,b|a}.sort.map{|a,b|b} } ``` ]
[Question] [ I recently moved to an apartment overlooking the inner ring-road of town, and every day, a beautiful scene unfolds. The traffic lights are apparently so confusing (mostly because the Dutch are used to complex intersections, and this one is too simple for them to wrap their heads around), that the intersection invariably winds up as something that must have been the inspiration for a [certain game which I shall call Evening Commute](http://en.wikipedia.org/wiki/Rush_Hour_(board_game)) for copyright reasons which I will undoubtedly have circumvented by my clever renaming... Please help my fellow confused Dutchmen, and make sure the red car makes it through the maze during Rush Hour! **Explanation of the game** The goal is to have the red car go **to the right** of a 6x6 grid (all the way off to the right), while only going straight forward or backward in the lengthwise direction of the car (which is 2 grid points long). For simplicity, the red car is *always* on the 3rd row. Of course, there are obstacles: other cars and trucks, with length two. They can be placed horizontally and vertically, and can only move in their lengthwise direction. They cannot pass through other cars. All cars move at 1 grid point per move. The game is won when the red car can move off the grid at the right side of the board. **Explanation of the challenge** * Input: a valid game board, which is a 6x6 string with dots `.` for empty tiles, `R`'s for the red (target) car on row 3, hex numbers 0 through B for cars (length 2), and hex numbers C through F for trucks (length 3). You need not worry about invalid boards; we are dealing with a carnage-free intersection. Example input: ``` ...... 11..22 RRC... ..C..3 ..C..3 ..66.. ``` As can be seen, numbers can be skipped; furthermore, there may be only trucks or only cars. * Output: a sequence of moves. Each move is identified as XY, with X the identifier of the vehicle, and Y the move, which is one of `v^<>`, or down, up, left and right respectively for those not familiar with a certain programming language. The move `Rx` means 'move the red car off the board' and will always indicate the end of the sequence (and only appear at the end, of course!). Since the output is fairly unambigious, any easily human readable sequence of moves will do (newlines, leading spaces are allowed; even a single undelimited string will do; however, you **are not allowed** to use underhanded tricks on the output). A solution to above problem may be, for example, `6<6<CvRx`. In- and output is, if I made the challenge correctly, case-independent, and newlines can be assumed to be convenient to your language (no need for `\r\n` hell) **Scoring** The **number of bytes** (code-golf-style) plus the sum of the **number of moves** it takes you for each of the following test cases (I tried to calibrate the minimum number of moves to be competitive). Your program should be fully capable of solving any other test case I may throw at it, and hard-coding test cases will give you a penalty of `2^64`, but if that's favourable, you might want to rethink your strategy. ``` 11...C D..E.C DRRE.C D..E.. 2...33 2.FFF. 112.33 442..C DRR..C DEEE.C D..566 77.588 C.1DDD C.12.. CRR2.. 3344.E .....E 5566.E C11.2. C34.2D C34RRD EEE5.D ..6577 88699. ``` ...next code-golf, somebody should make me a Rush Hour image recognition system. [Answer] ## Javascript (ES6), ~~1216~~ ~~1206~~ 1131 + 180 => 1311 bytes ``` a=>{a=a.replace(/\s/g,'');b=[];d={};e=[];f=[];g=[];h='.';[].concat.apply([],a.split('.').filter(k=>k).map(k=>k.match(/([^.])(\1*)/g)||k)).forEach(k=>k.length>1?(b.push(k[0]),(k.length<3?g:f).push(k[0])):(!e.includes(k)&&e.push(k),d[k]=d[k]?d[k]+1:1));Object.keys(d).forEach(k=>(d[k]<3?g:f).push(k));j=(l,m,n)=>l.substr(0,m)+n+l.substr(m+n.length);o=(p,q)=>~q.indexOf(p);I=(s,r,c)=>s.charAt(r*6+c)||'@';t=(s,r,c,F,G)=>{k=0;while(I(s,r+k*F,c+k*G)==h)k++;return k};u={};w=[];x={};x=(y,z,A)=>u[y]===[][0]?(u[y]=z,x[y]=A,w.push(y)):0;C=B=>{var z=u[B];return (!z?'':C(z))+x[B]};D=(B,r,c,q,E,F,G,n)=>{r+=E*F;c+=E*G;H=I(B,r,c);if(!o(H,q))return;L=o(H,f)?3:o(H,g)?2:[][0];J=B;for(i=0;i<n;i++){r-=F;c-=G;J=j(J,r*6+c,H);J=j(J,(r+L*F)*6+c+L*G,h);x(J,B,H+(!~F?'v':F?'^':!~G?'>':'<'));B=J}};x(a,null,'');K=!1;while(w.length) {B=w.splice(0,1)[0];if(I(B,2,5)=='R'&&!K){K=!0;break}for(r=0;r<6;r++){for(c=0;c<6;c++){if(I(B,r,c)!=h)continue;nU=t(B,r,c,-1,0);nD=t(B,r,c,1,0);nL=t(B,r,c,0,-1);nR=t(B,r,c,0,1);D(B,r,c,e,nU,-1,0,nU+nD-1);D(B,r,c,e,nD,1,0,nU+nD-1);D(B,r,c,b,nL,0,-1,nL+nR-1);D(B,r,c,b,nR,0,1,nL+nR-1)}}}return C(B).replace(/(R.)+$/,'Rx')} ``` I followed the algorithm and example from [here](https://stackoverflow.com/a/2880060/2006429). Rewriting the algorithm and input in the example to output moves cost a lot of bytes. I'm planning on rewriting the answer using an algorithm specifically designed for outputting moves instead of outputting board states. Ungolfed: ``` func = inp => { inp = inp.replace(/\s/g, ''); HORZS = []; tVERTS = {}; VERTS = []; LONGS = []; SHORTS = []; EMPTY = '.'; [].concat.apply([], inp.split('.').filter(k => k).map(k => k.match(/([^.])(\1*)/g) || k)).forEach(k => k.length > 1 ? ( HORZS.push(k[0]), (k.length < 3 ? SHORTS : LONGS).push(k[0]) ) : ( !VERTS.includes(k) && VERTS.push(k), tVERTS[k] = tVERTS[k] ? tVERTS[k] + 1 : 1 ) ); Object.keys(tVERTS).forEach(k => (tVERTS[k] < 3 ? SHORTS : LONGS).push(k)); setCharAt = (str, index, character) => str.substr(0, index) + character + str.substr(index + character.length); isType = (entity, type) => ~type.indexOf(entity); at = (state, r, c) => state.charAt(r * 6 + c) || '@'; countSpaces = (state, r, c, dr, dc) => { k = 0; while (at(state, r + k * dr, c + k * dc) == EMPTY) k++; return k; }; pred = {}; queue = []; moves = {}; propose = (next, prev, move) => pred[next] === [][0] ? (pred[next] = prev, moves[next] = move, queue.push(next)) : 0; trace = current => { var prev = pred[current]; return (!prev ? '' : trace(prev)) + moves[current]; }; slide = (current, r, c, type, distance, dr, dc, n) => { r += distance * dr; c += distance * dc; car = at(current, r, c); if (!isType(car, type)) return; L = isType(car, LONGS) ? 3 : isType(car, SHORTS) ? 2 : [][0]; sb = current; for (i = 0; i < n; i++) { r -= dr; c -= dc; sb = setCharAt(sb, r * 6 + c, car); sb = setCharAt(sb, (r + L * dr) * 6 + c + L * dc, EMPTY); propose(sb, current, car + (!~dr ? 'v' : dr ? '^' : !~dc ? '>' : '<')); current = sb; } }; propose(inp, null, ''); solved = !1; while (queue.length) { current = queue.splice(0, 1)[0]; if (at(current, 2, 5) == 'R' && !solved) { solved = !0; break; } for (r = 0; r < 6; r++) { for (c = 0; c < 6; c++) { if (at(current, r, c) != EMPTY) continue; nU = countSpaces(current, r, c, -1, 0); nD = countSpaces(current, r, c, 1, 0); nL = countSpaces(current, r, c, 0, -1); nR = countSpaces(current, r, c, 0, 1); slide(current, r, c, VERTS, nU, -1, 0, nU + nD - 1); slide(current, r, c, VERTS, nD, 1, 0, nU + nD - 1); slide(current, r, c, HORZS, nL, 0, -1, nL + nR - 1); slide(current, r, c, HORZS, nR, 0, 1, nL + nR - 1); } } } return trace(current).replace(/(R.)+$/, 'Rx'); } ``` Example usage and output: ``` func(`...... 11..22 RRC... ..C..3 ..C..3 ..66..`); // ==> "6<6<CvRx" func(`11...C D..E.C DRRE.C D..E.. 2...33 2.FFF.`); // ==> "1>D^2^Cv3<3<3<CvCvEvF<F<EvRx" func(`112.33 442..C DRR..C DEEE.C D..566 77.588`); // ==> "3<C^R>R>2vE>E>2v2v2v1>4>D^D^R<R<E<E<E<5^5^5^Cv6<Cv8<Cv3>5^Rx" func(`C.1DDD C.12.. CRR2.. 3344.E .....E 5566.E`); // ==> "4>3>CvCvD>2^Rx" func(`C11.2. C34.2D C34RRD EEE5.D ..6577 88699.`); // ==> "D^9>5vE>E>E>E>Cv1<4^R<3v3vR<5^5^5^5^R>R>E<E<Dv7<Dv9<DvRx" ``` ]
[Question] [ **your task is...** Given a string **x** and a positive integer **y**, to determine whether there is a positive integer **b** and an injective mapping from the distinct characters in **x** to the digits of base **b** which permit us to interpret **x** as an integer equal to **y**. **details:**    If there is more than one base which works, you **don't** have to output **all of them**, just one.    The answer should be a function for those languages that support it, otherwise, code snippet    Your program should accept 0-9 and (a-z **or** A-Z) which are 36 characters. You don't have to care about kanji or snowman.    (e.g. 6 doesn't have to mean 6, it's just a symbol. basically you get a number in unknown base with unknown symbols and you have to substitute them to get **y**) **for example:**    `(foo,4)` returns either **2** or **3** because * f=1, o=0 -> 1002=410 * f=0, o=1 -> 0113=410    `(10,10)` any integer greater than 4 but not 9 because * 1=2, 0=0 -> 205=1010 * 1=1, 0=4 -> 146=1010 * 1=1, 0=3 -> 137=1010 * 1=1, 0=2 -> 128=1010 * 1=1, 0=0 -> 1010=1010 * 1=0, 0=10 -> 0111=1010 * above base 10, 1=0, 0=10 -> 01x=1010 for every `x > 10`    `(611,1)` returns **0** which means there is no possible base for `611` meaning 110 **bonus:**    You have to output every possible base, not just one. I know it can be infinite,    indicate it somehow. `2,3,...` for example.    Answers with bonus gain a **0.7 multiplier**. [Answer] ## Mathematica, 183 bytes \* 0.7 = 128.1 ``` f[s_,n_]:=(For[i=2,1>0,++i,d=(l=Length)@(g=IntegerDigits)[n,i];Which[Count[c=Characters@s,c[[-1]]]>1&&d==1,Return@0,l@c>=d&&And@@Unequal@@@(t=Thread)@Union@t@{g[n,i,l@c],c},Print@i]]) ``` Less golf ``` f[s_, n_] := ( For[i = 2, 1 > 0, ++i, d = (l = Length)@(g = IntegerDigits)[n, i]; Which[ Count[c = Characters@s, c[[-1]]] > 1 && d == 1, Return@0, l@c >= d && And @@ Unequal @@@ (t = Thread)@ Union@ t@ {g[n, i, l@c], c}, Print@i ] ] ) ``` I don't actually recommend running this, because quick and infinite output is a bit tricky to abort in Mathematica sometimes. To get only the first result, change `Print` to `Result` (which is even a character longer). If you're using the version as is, a final `0` output will indicate that no further bases will be found (similar to the returning case). The first part of the `Which` simply aborts the loop when no base can possibly be found (it might be possible to shorten this). The second loop is the interesting check. These are the steps taken: * Convert `n` to digits in the current base (Mathematica can handle arbitrarily large bases.) * Zip those digits up with the characters, basically creating the mapping at each position. * `Union` throws out duplicates - these are uninteresting because they just point to a consistent mapping. * Transpose the mapping, so I get a list of digits and a list of characters. * If there are no duplicates in either, we have an injective mapping and print the base. ]
[Question] [ I just want to do some benchmarking of different programming languages. So here is a tip: You can use as many characters as you want. In the end there is only the time your program needed. So, here is the Task: # Task After searching for a good task that would require a lot of computation, I came up with the problem `Is a word in a given Type-1 grammar?` For people not knowing what this is: [Formal Grammar](http://en.wikipedia.org/wiki/Formal_grammar)  [Chomsky-Hierarchy](http://en.wikipedia.org/wiki/Chomsky_hierarchy) Maybe there is a better algorithm but I came only up with brute forcing. So, write a code that brute forces the Grammars as fast as possible. # Rules * Parallel execution is allowed * Delete your cache after every tested word * Add your complete compiler command for optimized result * You can use any algorithm and language you want, as long as the job gets done. * Add to your answer what files are read/how to set the files that should be read. # I Guarantee * Input is always well formatted * Variables are always capital letters, Terminals always small ones * Words only consist of Terminals * No empty Word # Input For equal footing we need to define what the input looks like. The input is a file. I write multiple grammars and words in one file. The structure can be described with following Pseudocode: ``` foreach(Grammar G) do write('{'); foreach (Variable V in G) do write(T + ','); od deleteLast(); write('}'); linebreak(); write('{'); foreach (Terminal T in G) do write(V + ','); od deleteLast(); write('}'); linebreak(); write('{'); foreach(Production P in G) do write(P + ','); od write('}'); linebreak; write(StartSymbol(G)); linebreak; foreach(Word W for G) do write(W + ','); od deleteLast(); linebreak; od deleteLastLinebreak(); ``` [An Example](http://pastebin.com/XXNABpvm) # Output The output has to be put in a file as well. The formatting of the output does not matter. It should be recognizable which result belongs to which word. [An Example](http://pastebin.com/S0QNMaEC) # Example Here is an example written in C# by myself. [Main Class](http://pastebin.com/ThKDFbkv) [Data Classes](http://pastebin.com/vqfty6W2) # Test System The system the code will run on is following: * Arch Linux * RunTime you need (if available; Please add in answer) * Intel i7-4700MQ 3.4GHz * 16GB RAM # How do I test After the code is compiled I'll run a bash script that runs your program a certain amount of times and calculates the average and median run time. Good Luck and may the best code win. ~~My Benchmark: Not completed after 8-9 hours of runtime.~~ My Benchmark (after changing some words): * mean: 39.5157 * median: 39.448687194 PS: [Here](http://pastebin.com/LQ4fKeCz) is the originally planned input, which took ages with my program. Grammars are slightly changed in the new input and words are way shorter. [Answer] As the code is rather long, it can be found here (Java 8): <http://pastebin.com/Q5Buuqfx> How I did it: Instead of brute-force creating the possible word combinations and then try to find a match I instead did the reverse and tried to collapse the target word to find the starting point. As a result the path the algorithm has to traverse is much less branched, and the words from the example can all be verified in about 35 ms (on my machine). As a side-effect of the reverse-search I do not need the first two lines of each task (variables, terminals). In addition I utilize the Java 8 streaming technology, which allows to easily activate parallel processing with just a single change in one line of code. Usage: `java Grammar <inputFile>` **Edit:** Did some code cleanup and further speed tests and it ironically turned out, that the algorithm is so fast, that setting up the parallel stream takes longer than the actual task. I now use a single-CPU `stream()` instead and the complete example input set is processed in ~35 ms on my machine instead of ~80 ms if I use `parallelStream()`. **Edit2:** Further testing reveals some strange effects with parallelStream and certain types of Collections. A TreeSet seems to work best in both single and parallel processing. I did some tests on your extended input set and it seems to work fine, except for the task with the looping rules (CD->DC,DC->CD). Detecting and removing those would cause the search to verify instantly. ]
[Question] [ The [Routh-Hurwitz](https://en.wikipedia.org/wiki/Routh%E2%80%93Hurwitz_stability_criterion) is a criteria which serves to prove or disprove the stability of an electric control system. # Idea Given a system which has an equation of the form `P(s)/Q(s)` where `P(s)` and `Q(s)` are polynomials of any degree, it is said to be stable if all the roots of the polynomial `Q(s)` are in the left half of the complex plane, which means the real part of the root is negative. For polynomials of degree less than or equal to 2, it is trivial to determine the roots and notice whether or not the system is stable. For polynomials `Q(s)` of higher degrees, the [Routh–Hurwitz theorem](https://en.wikipedia.org/wiki/Routh%E2%80%93Hurwitz_theorem) can be useful to determine whether the system is Hurwitz-stable or not. # Process One of the methods to apply this theorem for any degree is described [on Wikipedia](https://en.wikipedia.org/wiki/Routh%E2%80%93Hurwitz_stability_criterion#Higher-order_example) that consists of performing operations on rows of a table, then counting the number of sign changes in the first column of the table. It goes as follows: * Fill the first two rows with the coefficients of the polynomial, in the following pattern: 1st row consists of the even coefficients `s^n`, `s^n-2`, ..., `s^2`, `s^0`; 2nd row consists of the odd coefficients `s^n-1`, `s^n-3`, ..., `s^3`, `s^1`; * Keep calculating the following rows by calculating the determinant of the matrix (last 2 rows of the first column, last 2 rows of the next column) divided by (the value of the first column on the row above); it is detailed in [this part](https://en.wikipedia.org/wiki/Routh%E2%80%93Hurwitz_stability_criterion#Higher-order_example) of the Wikipedia article. * If you encounter a row full of zeros, set it to the derivative of the polynomial that the row above it represents. Depending on the row it is on, the number on each cell represents a coefficient. It is illustrated in the example later. * If you encounter a zero with other non-zero values, the system is not stable: you can stop there. (You could continue but you'll get the same result). A zero on the first column would mean a root of real value 0, which renders the system unstable. * Otherwise, continue until the end. Then, if not all the values in the first column are of the same sign, the system is not stable. # Examples Here are some examples of that process: ``` # Polynomial: 1 3 6 12 8.00 s^4 1 6 8 s^3 3 12 0 s^2 2 8 0 s^1--0-0--0-- < Row of zero - replace it by: s^1 4 0 0 < Derivative 2*s^2 + 8*s^0 = 4*s^1 (between each 2 columns the power of s is lowered by 2) s^0 8 0 0 < Continue normally # Sign Changes: 0 (equivalent to no root in the right half plane) # Stable: Yes ``` Another one: ``` s^2 1 -2 s^1 1 0 s^0 -2 0 # Sign Changes: 1 (equivalent to 1 root in the right half plane) # Stable: No ``` # Rules * The program will keep reading polynomials from standard input until a blank line, and output `0`/`1` for stable/non-stable respectively for each polynomial on a new line. * The program can read the polynomial coefficients in any form. It could be `1 3 6 12 8` for the first example (it suits this problem better, but it doesn't really matter in the end). * It has to handle cases where `0` in the first column, or `0` in the following columns, or a row full of `0` is encountered properly. (Note: just in case, no need to see how many roots are in rhp/lhp/jw axis). * It can short-circuit the process at any time if a condition is met, there is no need to show the RH table in the end. * You do not have to use this method. Any method which will determine whether or not a system is Hurwitz-stable can do the job. * It doesn't matter which language you chose to do it with, as long as it's not done in one single built-in function call. I did mine in Python, I'll post it soon. * This is a code golf. The shortest code wins. Here's a sample input/output (given in the above mentioned way) to test your program with: ``` #input: 1 12 6 10 10 6 14 1 1 -2 1 2 1 2 1 3 1 3 16 1 2 3 6 2 1 1 2 14 88 200 800 1 2 3 6 2 1 1 3 6 12 8 1 4 5 2 4 16 20 8 #output: 0 0 1 0 0 0 0 1 0 ``` If you need more clarifications, let me know, I'll do my best to clarify. [Answer] ## Haskell - 264 bytes ``` p(a:b:s)=(a,b):p s p[a]=[(a,0)] p[]=[] s((a:w),m@(b:v))=a:s(m,m%zipWith(\c d->(b*c-a*d)/b)w v) s((a:_),_)=[a] m%(0:v)|all(==0)v=fst$foldr(\b(d,p)->(b*p:d,2+p))([],0)m m%v=v q(a:s)|all((>0).(a*))s="1\n" q _="0\n" main=interact$(>>=q.s.unzip.p.map read.words).lines ``` Running the sample inputs: ``` & runhaskell 11847-Stability.hs 1 12 6 10 10 6 14 1 1 -2 1 2 1 2 1 3 1 3 16 1 2 3 6 2 1 1 2 14 88 200 800 1 2 3 6 2 1 1 3 6 12 8 1 4 5 2 4 16 20 8 0 0 1 0 0 0 0 1 0 ``` (The output is interleaved with the input if you type it one line at a time, as per spec. If you bulk paste, you see all the output after the input.) [Answer] # Python (645 bytes) That's what I managed to do (and golf): ``` from decimal import* R=xrange def s(p): d=len(p) if 0 in p:return 0 elif sum(1 for c in p if c>0) not in (0,d):return 0 p=p+[0] if d%2 else p[:] r=[[0 for j in R(len(p)//2)] for i in R(d)] r[:2]=[[v for v in p[i::2]] for i in (0,1)] for i in R(2,len(r)): a,h,b = 1,0,0 for k in R(len(r[i])-1): v=(r[i-1][0]*r[i-2][k+1]-r[i-2][0]*r[i-1][k+1])/r[i-1][0] r[i][k],a,h,b=v,a and v==0,h or v==0,b or (h and v!=0) if a:r[i]=[v*max(0,d-i-2*k) for k,v in enumerate(r[i-1])] elif b:return False return sum(1 for v in r if v[0]>0) in (0,d) while 1: r=raw_input() if not r:break print 1 if s([Decimal(x) for x in r.split()]) else 0 ``` It takes as input the coefficients of the polynomials in decreasing order (highest power of s to lowest 0). ]
[Question] [ This is an interesting one. I have written a short program in objective-c to encode a string into a brainf\_ck string, this is what it looks like: ``` NSString *input; // set this to your input string NSMutableString *output = [[NSMutableString alloc] init]; int currentPosition = 0; for (int i = 0; i<[input length]; i++) { int charPos = [input characterAtIndex:i]; int amountToGo = charPos-currentPosition; if (amountToGo > 0) { for (int b = 0; b<amountToGo; b++) { [output appendString:@"+"]; } } else { int posVal = abs(amountToGo); for (int b = 0; b<posVal; b++) { [output appendString:@"-"]; } } currentPosition += amountToGo; [output appendString:@"."]; } NSLog(@"%@", output); [output release]; ``` Now I could ask you to optimize that code. Or, I could ask you to optimize the bf code it produces? **EXAMPLE:** Output of 'Hello World!' from my code (**365** chars) > > ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.-------------------------------------------------------------------------------.+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++.+++.------.--------.-------------------------------------------------------------------. > > > **EXAMPLE 2:** Now, looking at that code, I could probably shorten it by putting reset to zeros in, for a start... (**290** chars - **75** improvement) > > ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.[-]++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++.+++.------.--------.[-]+++++++++++++++++++++++++++++++++. > > > But this takes it a step further... output of 'Hello World!' from some sample code I found [on the internet](http://www.iamcal.com/misc/bf_debug/): (**111** chars, **179** on last, **254** on original!) > > ++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>. > > > Now, I don't know how that loop works, but it does. My question is this: 1. Explain how the loop in the last example works. 2. Write some code that can turn *any* string into highly optimized brainf\_ck, like the last example. [Answer] I can give question number 1. a go: ``` ++++++++++ ``` The first series of +'s defines first memory cell (cell0) to be a loop counter to 10. ``` [>+++++++>++++++++++>+++>+<<<<-] ``` Above is the loop that executes 10 times. The loop adds 7 to cell1, 10 to cell2, 3 to cell3 and 1 to cell4 for each iteration. After 10 iterations we have the following in the first 5 memory cells: 0, 70, 100, 21, 10 ``` >++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>. ``` Above is kind of self explanatory, it just moves the memory pointer to the value that is closest to what is needed, does some minor inc's and dec's and outputs. ]
[Question] [ In this challenge you will receive a list of positive integers \$W\$ called a *word*, and a square symmetric matrix \$M\$. Your task is to determine if the word can be turned into the empty list by applying a series of valid moves. The valid moves are: 1. If two consecutive values in the list are equal you may remove them from the list. e.g. `[2,6,6,2,1]` to `[2,2,1]` 2. For any positive integer \$n\$ you may insert two \$n\$s at any place in the list. e.g. `[1,2,3]` to `[1,3,3,2,3]` 3. For two positive integers \$i\$ and \$j\$, if \$M\_{i,j} = l\$ (i.e. the value of \$M\$ at the \$i\$th row and \$j\$th column) and there is a contiguous substring of length \$l\$ alternating between \$i\$ and \$j\$, you may replace all the \$i\$s with \$j\$s and vice versa within that substring. e.g. `[1,2,1,2]` to `[2,1,2,2]` **if and only if** \$M\_{i,j} = 3\$ Values in the matrix will be on the range \$[2,\infty]\$. ∞ of course represents that there is no valid application of rule 3 for that pair. you may use 0 or -1 in place of ∞. In addition the input will always satisfy the following properties: * \$M\$ will always be square. * \$M\$ will always be a symmetric matrix. * The diagonal of \$M\$ will always be entirely 2. * The maximum value of \$W\$ will not exceed the number of rows/columns of \$M\$ You should take \$M\$ and \$W\$ in any reasonable format, you should output one of two distinct values if the word can be reduced to the empty word and the other value if not. Use zero indexing for your word if you wish. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The goal is to minimize the size of your source code as measured in bytes. # Worked examples Here are some examples with working for the solution. You do not have to output any working just the end result. 1. \$W\$ = `[3,2,3,3,1,2,3]` any value of \$M\$: Each rule changes the number of symbols by a multiple of 2, however \$W\$ has an odd number of symbols, therefor by parity we can never reach the empty word so this case is ***False*** 2. \$W\$ = `[1,3]`, \$M\_{1,3}\$ is even: Similar to the last case we observe that both 1 and 3 appear an odd number of times. Each rule can only change the count of 1s and 3s by an even amount, but in our desired end state we have 0 of each, an even amount. Therefor by parity we can never reach this case is ***False*** 3. \$W\$ = `[1,3]`, any value of \$M\$: In this case we consider 4 values: * \$a\_1\$, the number of 1s at even indexes * \$b\_1\$, the number of 1s at odd indexes * \$a\_3\$, the number of 3s at even indexes * \$b\_3\$, the number of 3s at odd indexesWe note that rules 1 and 2 do not change the values of \$a\_n-b\_n\$. Rule 3 changes both them by the value of \$M\_{1,3}\$. Since each begins at 1 and the goal is 0 it would require \$M\_{1,3}\$ to equal 1. This is forbidden, so this case is ***False***. 4. \$W\$ = `[2,1,3,2]`, any value of \$M\$: This is a conjugate of `[1,3]`, which by 3. we know is irreducible. Conjugates always have the same order, thus its order must be greater than 1. ***False*** 5. \$W\$ = `[1,2,1,2]`, \$M\_{1,2} = 3\$: We can apply rule 3 to the last 3 symbols of the word get `[1,1,2,1]`, from here we can apply rule 1 to get `[2,1]`. We can use the argument in 3 to show `[2,1]` is irreducible thus \$W\$ is irreducible. ***False*** 6. \$W\$ = `[1,4,1,4]`, \$M\_{1,4}\$ = 2: `[1,4,1,4]` `[4,1,1,4]` (rule 3) `[4,4]` (rule 1) `[]` (rule 1) ***True*** ]
[Question] [ This originally came from [Give the best Chaitin incompleteness bound](https://codegolf.stackexchange.com/questions/266035/give-the-best-chaitin-incompleteness-bound), but I realized that there was a fragment of this problem which still potentially gives a good coding challenge. ## First Order Logic With Equality First, I will need to fix an encoding of first order formulas ('For all x there exists y such that ...'). Since the standard symbols for the mathematical operations are not in ASCII, I will denote "for all" as `@`, "there exists" as `#`, "not" as `!`, "and" as `&`, "or" as `|`, "equals" as `=` and "implies" as `>`. A variable consists of `v` followed by an alphanumeric sequence. A function symbol is of the form `f`, followed by some nonnegative number of `_`'s, followed by an alphanumeric sequence. The number of underscores indicates the number of inputs to the function. A predicate symbol is of the from `P` followed by some number of underscores, followed by an alphanumeric name. To make actually putting this into a computer program a little easier, say that everything is in prefix notation, like Lisp. Following the suggestion of Wheat Wizard, you are free to choose whatever symbols are to be used for 'for all', 'exists', 'is a variable', etc. so long as there are no collisions between variables and functions, between functions of different arity, et cetera. The input of the statement can also be a parse tree or ragged list. For example, the statement that addition is commutative can be written down as follows: `(@ vx0 (@ vx1 (= (f__plus vx0 vx1) (f__plus vx1 vx0))))` ## The Problem Write a program that inputs two formulae in first order logic with equality along with a proposed proof of the second statement from the first, and then outputs 1 if the proof is correct, and 0 otherwise. Give an example of the program running on the proof of some simple theorem. Shortest program per language wins. I don't really care how you encode the notion of a proof so long as it is computably equivalent to the standard notions. # Technical Details ## Sentence Formation The following is essentially transcribed from Wikipedia, rephrased to match the format above. A term is either a variable name, which is a `v` followed by a sequence of letters or numbers, or a expression of the form `(f_..._A t1 ... tn)`, where the `ti`'s are terms, `f_..._A` is a function name, and where the number of underscores equals the number of arguments. Given a predicate `P_..._A`, then `(P_..._A t1 ... tn)` is a formula when the arity of the predicate matches the number of terms. Given two terms `t1` and `t2`, then `(= t1 t2)` is a formula. Given any formula `p`, `(! p)` is a formula. Given another formula `q`, so are `(> p q)`, `(& p q)`, and `(| p q)`. Finally, given a variable `vX` and a formula `p`, `(@ vX p)` and `(# vX p)` are formulas. All formulae are produced in this manner. A sentence is a formula where every occurrence of a variable is bound, i.e. within the scope of a quantifier (`@` or `#`). ## Defining Proof There's multiple ways to formalize a proof. One method is as follows. Given a formula `phi` and a formula `psi`, a proof of `psi` from `phi` is a list of pairs of sentences and the rule by which they were introduced. The first sentence must be `phi` and the last must be `psi`. There are two ways a new sentence can be produced. If there are formulae `p` and `q` such that two previously introduced sentences are `(> p q)` and `p`, then you can introduce `q` by modus ponens. Alternatively, the new sentences can be from one of the following axiom schemes (taken from the Wikipedia page on Hilbert Systems): 1. `(> p p)` (self-implication) 2. `(> p (> q p))` (simplification) 3. `(> (> p (> q r)) (> (> p q) (> p r))` (the Frege axiom) 4. `(> (> (! p) (! q)) (> q p))` (contrapositive) 5. `(> p (> q (& p q)))` (introduction of the conjunction) 6. `(> (& p q) p)` (left elimination) 7. `(> (& p q) q)` (right elimination) 8. `(> p (| p q))` (left introduction of the disjunction) 9. `(> q (| p q))` (right introduction) 10. `(> (> p r) (> (> q r) (> (| p q) r)))` (elimination) 11. `(> (@ vx p) p[vx:=t])`, where `p[vx:=t]` replaces every *free* instance of `vx` in `p` with the term `t`. (substitution) 12. `(> (@ vx (> p q)) (> (@ vx p) (@ vx q)))` (moving universal quantification past the implication) 13. `(> p (@ vx p))` if `vx` is not free in `p`. 14. `(@ vx (> p (# vy p[vx:=vy])))` (introduction of the existential) 15. `(> (@ vx p q) (> (# x p) q))` if `vx` is not free in `q`. 16. `(= vx vx)` (reflexivity) 17. `(> (= vx vy) (> p[vz:=vx] p[vz:=vy]))` (substitution by equals) 18. If `p` is an axiom, so is `(@ vx p)` (and so is `(@ vx (@ vy p))` ,etc.). (generalization) `p`, `q`, and `r` are arbitrary formulae, and `vx`, `vy`, and `vz` are arbitrary variables. Note that if you change up what is demanded of the proof, then it's possible to cut down on the number of axioms. For example, the operations `&`, `|`, and `#` can be expressed in terms of the other operations. Then, if you compute the replacement of the input formulae with the formulae with these operations removed, one can eliminate axioms 5 - 10, 14, and 15. It's possible to compute a proof of the original type from a proof of this reduced type, and vice versa. For an example of a proof of this type, see below. ``` 0 (@ vx (P_p vx)) A14 vx vx (P_p vx) 1 (@ vx (> (P_p vx) (# vx (P_p vx)))) A12 vx (P_p vx) (# vx (P_p vx)) 2 (> (@ vx (> (P_p vx) (# vx (P_p vx)))) (> (@ vx (P_p vx)) (@ vx (# vx (P_p vx))))) MP 2 1 3 (> (@ vx (P_p vx)) (@ vx (# vx (P_p vx)))) MP 3 0 4 (@ vx (# vx (P_p vx))) GA11 vy vx (# vx (P_p vx)) 5 (@ vy (> (@ vx (# vx (P_p vx))) (# vx (P_p vx)))) A12 vy (@ vx (# vx (P_p vx))) (# vx (P_p vx)) 6 (> (@ vy (> (@ vx (# vx (P_p vx))) (# vx (P_p vx)))) (> (@ vy (@ vx (# vx (P_p vx)))) (@ vy (# vx (P_p vx))))) MP 6 5 7 (> (@ vy (@ vx (# vx (P_p vx)))) (@ vy (# vx (P_p vx)))) A13 vy (@ vx (# vx (P_p vx))) 8 (> (@ vx (# vx (P_p vx))) (@ vy (@ vx (# vx (P_p vx))))) MP 8 4 9 (@ vy (@ vx (# vx (P_p vx)))) MP 7 9 10 (@ vy (# vx (P_p vx))) ``` Between each two lines is indicated the rule by which the next line is produced, where `A` is an axiom, `MP` is modus ponens, and `GA` indicates a single instance of generalization (`GGGA` would indicate three generalizations on the axiom `A`). ]
[Question] [ This was originally a pure mathematics question, but I think I've got the best chance for an answer here. ## The Challenge For concreteness, consider Peano Arithmetic (PA). For some language *L* of your choosing, construct a computer program of length at most *N* bits in *L* such that: 1. If it terminates, it outputs a number that PA proves cannot be outputted by a program in *L* of length at most *N*. 2. If PA proves any specific number cannot be outputted by a program of length at most *N*, then the program terminates. Carefully engineering *L* to make constructing the program easier is encouraged. Smallest *N* wins. ## Motivation Essentially, the program runs through proofs in PA until it finds one that some specific number cannot be outputted by a program of length *N* until it finds such a proof, then outputs that specific number. I don't actually know of any explicit previously constructed program that satisfies the above conditions. The upshot of such a program is Chaitin's incompleteness theorem: Given any computable axiom system (e.g. PA, ZFC, etc.), there exists a *N* (which equals the size of the computer program describing the axiom system plus an explicit constant) such that that axiom system cannot prove any output has Kolmogorov complexity (the length of the minimal program which outputs said output) larger than *N*. This is a pretty disturbing result! ## Stupid Technical Requirements 1. There shouldn't be any funny business involved in showing your program satisfies the two conditions above. More precisely, they should be provable in PA. (If you know what Robinson's is, then it has to be provable in that.) 2. The language *L* has to be simulatable by a computer program. 3. The usage of PA is purely for definiteness - your construction should generalize, holding *L* fixed, to ZFC (for example). This isn't quite a precisely well defined requirement, but I have had some difficulty in constructing a pathological language where the single-byte program `A` satisfies the above requirements, so I don't think this requirement can be violated accidentally. 4. Technically, it might be possible that the best *N* is achieved by a shorter program. In this case, I want the best *N*. Practically speaking, these are probably going to be the same. ## Simplifying Notes 1. Don't do this in Python! For a typical programming language, formalizing the language within the language of PA is going to be tough going. 2. PA itself has an infinite number of axioms. Naively, this would mean that you would have to make a subroutine to generate these axioms, but PA has a extension called ACA\_0 of the same strength which has a finite axiomatization. These finite number of axioms can then be lumped together into a single axiom, so you only have to deal with a single sentence. Note that any statement of PA which is provable in ACA\_0 is provable in PA, so this allows satisfying condition 2. of the challenge. 3. A potential way to test your program would be to replace PA with something inconsistent. Then, it should eventually terminate, having constructed a proof of large Kolmogorov complexity from the inconsistency. ]
[Question] [ ## What is Crazyhouse Chess? [Crazyhouse Chess](https://en.wikipedia.org/wiki/Crazyhouse) is a chess variant that is basically normal chess except you can place a piece you previously captured back on the board instead of a regular turn. ## Bot interface Only JavaScript bots are allowed. A bot is a JavaScript function that takes 3 arguments (board, side, bank) and returns a move. The function should also have a property `n` for the name of the bot. The board argument is an array of 64 characters, each representing a square on the chess board. If the character is uppercase, it represents a white piece. ``` '-' - empty square 'K', 'k' - king 'N', 'n' - knight 'R', 'r' - rook 'Q', 'q' - queen 'B', 'b' - bishop 'P', 'p' - pawn ``` The side argument is a number (1 - you are playing white, 2 - you are playing black) The bank argument is a dictionary: `{"p": 0, "n": 0, "b": 0, "r": 0, "q": 0}` The numbers represent the count of pieces you have. ### Move return format A move is an array with two elements. If the move is a normal move, then the array contains the from square and to square. If the move is a piece place, the first argument is the piece char (always lowercase) and the second argument is the destination square. Example bot: ``` var bot = (board, side, bank) => { const move = (side == 1) ? [52, 36 /* e2e4 */] : [12, 28 /* e7e5 */] return move; } bot.n = "BotName" ``` Note: If a bot returns an invalid move, it counts as a resignation - the bot loses the game. ## Chess simplifications 1. En passant is not allowed. 2. Castling is not allowed 3. Leaving the king in check is allowed, the objective of the game is to capture the king, not checkmate ## The controller If you find any bugs feel free to point them out. ``` var abot = (board, side, bank) => { const move = (side == 1) ? [52, 36 /* e2e4 */] : [12, 28 /* e7e5 */]; // side 1 = white 2 = black return move; } abot.n = "TestBot"; var bots = [abot, abot] var rating = new Array(bots.length).fill(0); function pair() { var ret = [] for (var x = 0; x < bots.length; x++) { for (var y = x + 1; y < bots.length; y++) { ret.push([x, y]) } } return ret; } const startpos = [ 'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R', ]; function rank(sq) { if (sq < 0 || sq > 63) return -1; return 8 - Math.floor(sq / 8); } function file(sq) { if (sq < 0 || sq > 63) return "-"; return "abcdefgh"[sq % 8]; } function piece_color(piece) { if (piece == '-') return 0; if (piece == piece.toUpperCase()) return 1; // white return 2; // black } const knight_moves = [ 17, 15, 10, 6, -17, -15, -10, -6 ]; const king_moves = [ 1, 8, 9, 7, -1, -8, -9, -7 ]; const pawn_cap = [ 9, 7 ]; const rook_moves = [ 8, 1, -8, -1 ]; const bishop_moves = [ 9, 7, -9, -7 ]; function canrookmove(board, sq1, sq2) { var sq; if (file(sq1) == file(sq2)) { const f = file(sq1); for (const move of rook_moves) { sq = sq1; while (true) { sq += move; if (file(sq) != f || piece_color(board[sq]) == piece_color(board[sq1])) break; if (sq == sq2) return true; if (board[sq] != '-') break; } } } else if (rank(sq1) == rank(sq2)) { const r = rank(sq1); for (const move of rook_moves) { sq = sq1; while (true) { sq += move; if (rank(sq) != r || piece_color(board[sq]) == piece_color(board[sq1])) break; if (sq == sq2) return true; if (board[sq] != '-') break; } } } return false; } function canbishopmove(board, sq1, sq2) { var sq; for (const move of bishop_moves) { sq = sq1; while (true) { sq += move; if (piece_color(board[sq]) == piece_color(board[sq1])) break; if (sq == sq2) return true; if (board[sq] != '-' || rank(sq) == 1 || rank(sq) == 8 || file(sq) == 'a' || file(sq) == 'h' /* edge of the board */) break; } } } // return: 0 - draw; 1 - white won; 2 - black won // the game is automatically a draw after 200 moves function play(w, b) { var board = [...startpos]; var moves = 0; var wbank = {'p': 0, 'n': 0, 'b': 0, 'r': 0, 'q': 0}; var bbank = {'p': 0, 'n': 0, 'b': 0, 'r': 0, 'q': 0}; while (true) { var move = bots[w](board, 1, wbank); if (!checkm(board, move, 1, wbank)) return 2; if (typeof move[0] == "string") { wbank[move[0]]--; board[move[1]] = move[0].toUpperCase(); } else { if (board[move[1]] == 'k') return 1; if (board[move[1]] != '-') wbank[board[move[1]]]++; board[move[1]] = board[move[0]]; board[move[0]] = '-'; } move = bots[b](board, 2, bbank); if (!checkm(board, move, 2, bbank)) return 1; if (typeof move[0] == "string") { bbank[move[0]]--; board[move[1]] = move[0]; } else { if (board[move[1]] == 'K') return 2; if (board[move[1]] != '-') wbank[board[move[1]].toUpperCase()]++; board[move[1]] = board[move[0]]; board[move[0]] = '-'; } if (++moves == 200) return 0; } } function play_wrapper(white, black) { const result = play(white, black); console.log(bots[white].n, 'vs', bots[black].n, '-', ['draw', `white (${bots[white].n})`, `black (${bots[black].n})`][result]) if (result == 1) { rating[white] += 3; rating[black] -= 1; } else if (result == 2) { rating[black] += 3; rating[white] -= 1; } } function run() { const games = pair(); var result; for (const game of games) { play_wrapper(game[0], game[1]); play_wrapper(game[1], game[0]); } console.log("Ratings:") for (var i = 0; i < bots.length; i++) { console.log(bots[i].n, rating[i]) } } run(); // check legality of a move function checkm(board, move, side, bank) { if (typeof move[0] == "string") { if (move[1] > 63 || !("pnbrq".includes(move[0]))) return false; if (move[0] == 'p' && [1, 8].includes(rank(move[1]))) return false; // pawns can't be placed on rank 1 and 8 if (board[move[1]] != '-') return false; if (bank[move[0]] == 0) return false; } else { if (move[0] > 63 || move[1] > 63 || piece_color(board[move[1]]) == side || piece_color(board[move[0]]) != side) return false; switch (board[move[0]]) { case '-': return false; case 'N': case 'n': return knight_moves.includes(move[1] - move[0]); case 'K': case 'k': return king_moves.includes(move[1] - move[0]); case 'P': if ((move[1] - move[0]) >= 0) return false; if ((move[0] - move[1]) % 8 != 0) { // capture if (board[move[1]] == '-') return false; return pawn_cap.includes(move[0] - move[1]) } else { if (board[move[1]] != '-') return false; if ((move[0] - move[1]) / 8 == 2) return (rank(move[0]) == 2); return ((move[0] - move[1]) / 8) == 1; } case 'p': if ((move[0] - move[1]) >= 0) return false; if ((move[1] - move[0]) % 8 != 0) { // capture if (board[move[1]] == '-') return false; return pawn_cap.includes(move[1] - move[0]) } else { if (board[move[1]] != '-') return false; if ((move[1] - move[0]) / 8 == 2) return (rank(move[0]) == 7); return ((move[1] - move[0]) / 8) == 1; } case 'R': case 'r': return canrookmove(board, move[0], move[1]); case 'B': case 'b': return canbishopmove(board, move[0], move[1]); case 'Q': case 'q': return canrookmove(board, move[0], move[1]) || canbishopmove(board, move[0], move[1]); default: return false; } } return true; } ``` ## Edit Edit: Updated controller and added support for bot names ]
[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/226212/edit). Closed 2 years ago. [Improve this question](/posts/226212/edit) The goal is simple. Write a program that outputs itself encoded as a QR code. A QR code is a way to encode data in a black and white image, similar to a 2D image. An example implementation can be found [here.](https://github.com/zxing/zxing/tree/master/core/src/main/java/com/google/zxing/qrcode/encoder) The QR code is displayed as text, where each pixel is either a "#" for a black pixel, or a space for a white pixel, and pixels are separated by spaces, like so: ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` Quine rules (no reading source code) apply. This is code golf, so shortest program wins! ]
[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 3 years ago. [Improve this question](/posts/206233/edit) **Input** Name of a [stackexchange site](https://stackexchange.com/sites) or any way to uniquely identify the site. **Output** The hour of the day that had the largest number of answers posted over the previous 24 hours. E.g. 14:00-15:00 GMT. You can take the input and give output in any easily human readable format. Your code can access the Internet but only the site's API. Previous 24 hours should be from the start of the current hour. Out of politeness, please don't test your code on [stackoverflow](https://stackoverflow.com/) where the number of queries may need to be high. ]
[Question] [ Given required values for an expression with 2 variables, output a short expression which fulfill these values # Input You may take the input in any reasonable format, e.g. `f(x,y)=z`, `{(x, y): z}`, `[[[x,y],z]]`, but please write what format is your input is taken in # Output Your output needs the be a valid infix expression for two variables, and it has to output the correct value when rounding the output to three digits after the comma, but the current value isn't rounded during calculation. The following symbols/operators are allowed: ## symbols ``` x - the first input variables y - the second input variables pi - 3.1415 (4 digit precision) e - 2.7182 (4 digit precision) every possible numeric constant (1, 0.12, 42, 13.241) ``` ## operators ``` + sum of two values, in the format a+b - difference of two values, in the format a-b * multiplication of two values, in the format a*b / division of two values, in the format a/b ^ power of two values, in the format a^b || absolute value, in the format |a| () parentheses, in the format (a) floor the floor of a value, in the format floor(a) ceil the ceil of a value, in the format ceil(a) ``` if I forgot anything that you think is important tell me in the comments please. # Example Testcases other expressions are okay if they result in the correct values ``` f(0.12, 0.423) = 3.142 f(0.89, 0.90) = 3.142 | \/ pi (3.1415 gets rounded to 3 digits after the comma - 3.142) f(0.12, 0.423) = 0.543 f(0.89,0.9)=1.79 | \/ x+y ``` # Score Your score is the average length of expression for the following input: <https://pastebin.com/tfuBjpc6> , where each batch of inputs (a different function) is separated by a newline. You can transform the format to any format your program accept. Good luck! [Answer] # C++ (gcc), score: 39.2533 Interpolate `x`s or `y`s and `f`s with [lagrange interpolation](https://en.wikipedia.org/wiki/Lagrange_polynomial). ``` #include <iostream> #include <string> #include <cstdio> #include <cstring> #include <sstream> #include <iomanip> #include <cstdlib> #include <cmath> #include <set> using namespace std; string ml(const string& a,const string& b) { if(a.size()<b.size()) return a; return b; }; string prt(double x,int g,int d=0) { char buf[100],buf2[100]; sprintf(buf,"%%+.%dlf",g); sprintf(buf2,buf,x); string s=buf2; while(s.size()&&s.back()=='0') s.pop_back(); if(s.size()&&s.back()=='.') s.pop_back(); if(s=="-0") s="+0"; if(s=="+3.1415") s="+pi"; if(s=="-3.1415") s="-pi"; if(s=="+2.7182") s="+e"; if(s=="-2.7182") s="-e"; return s; }; int main() { double tl=0; int tc=0; while(1) { double x[5],y[5],f[5]; int bad=0; char s[2][20]; for(int j=0,k;j<5;++j) { if(scanf("%s %s",s[0],s[1])==EOF) { bad=1; break; } s[0][strlen(s[0])-1]=0; sscanf(s[0]+2,"%lf",x+j); for(k=0;s[1][k]!=')';++k) ; s[1][k]=0;sscanf(s[1],"%lf",y+j); sscanf(s[1]+k+2,"%lf",f+j); } if(bad) break; set<double> dx,dy; for(int j=0;j<5;++j) dx.insert(x[j]),dy.insert(y[j]); string ans; ans.resize(2000); auto work=[&](double*d,char s) { double md=0; stringstream ss; double p[5]; memset(p,0,sizeof p); for(int j=0;j<5;++j) { double w=f[j]; md=max(md,fabs(d[j])); for(int k=0;k<5;++k) if(j!=k) w/=d[j]-d[k]; double q[5]; memset(q,0,sizeof q); q[0]=w; for(int k=0;k<5;++k) if(j!=k) for(int s=4;s>=0;--s) q[s]=(s?q[s-1]:0)-q[s]*d[k]; for(int k=0;k<5;++k) p[k]+=q[k]; } for(int j=0;j<5;++j) { double prec=1.0/10000/pow(md,j); int u=0; while(prec<1) prec*=10,++u; string w=prt(p[j],u); if(w=="+0") continue; ss<<w; if(j) ss<<"*"<<s; if(j>=2) ss<<"^"<<j; } string o=ss.str(); if(o.size()&&o[0]=='+') o.erase(o.begin()); if(!o.size()) o="0"; if(o.size()<ans.size()) ans=o; }; if(dx.size()==5) work(x,'x'); if(dy.size()==5) work(y,'y'); tl+=ans.size(); ++tc; cout<<ans<<"\n"; } cerr<<setprecision(4)<<fixed; cerr<<tl/tc<<"\n"; } ``` The output looks like: ``` -265.3786-74.29574*x+344.81918*x^2+225.130398*x^3+36.610661*x^4 35.1581-3.27602*y+0.113946*y^2+0.412073*y^3-0.080117*y^4 -14.961 0.3769+0.50931*x-0.172598*x^2-0.0317501*x^3+0.0113617*x^4 -9.3762-1.54567*y+9.224426*y^2+5.413074*y^3+0.8106773*y^4 -3.7267-3.1155*x+0.011054*x^2-0.002775*x^3-0.0010706*x^4 1 4 31.8856+38.31442*x-0.94623*x^2-24.221891*x^3-8.086617*x^4 0.4856+0.08145*y+0.084768*y^2+0.0113*y^3+0.0001758*y^4 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 798 bytes, score: 3.323226 or 16.521740 There are two versions of the code. The less cheaty version will output an expression in form of `x * y * 0 + z`, while the more cheaty version will output an expression in form of `z`. Obviously creating a "real" solution would bump the score down, but given that it's just a tiny gain and as far as I can tell it's a NP-complete problem, it's simply not worth doing it (some edge cases where you tell a 7-long number that's for instance `x+1`, then you lose a few points, but it's not significant this much). ``` cheaty/ Average length: 11618 / 3496: 3.323226 less cheaty/ Average length: 57760 / 3496: 16.521740 ``` The code: ``` float round(float x) { float v = (int)(x * 1000 + .5); return (float)v / 1000; } char * find_constants(float f) { float x = round(f); static char buf[16]; if(x == 3.142) return "pi"; if(x == 2.718) return "e"; sprintf(buf, "%.3g", f); return buf; } int main(void) { float x, y, z; long total_len = 0, amount = 0; while(scanf("%f %f %f", &x, &y, &z) == 3) { #ifdef LESS_CHEATY total_len += strlen(find_constants(x))+strlen(find_constants(y))+strlen(find_constants(z))+4; // printf("%s*%s*0+%s\n", find_constants(x), find_constants(y), find_constants(z)); #else total_len += strlen(find_constants(z)); // printf("%s\n", find_constants(z)); #endif amount++; } printf("Average length: %d / %d: %f\n", total_len, amount, (float)total_len / (float)amount); } ``` [Try me online!](https://tio.run/##jL1br3zbddz3rP4UDRkSSEu9Ne@XCHowAgN5yJvzEiSBwJA8MgGaMkhathXosyuzfjXm2n/ZDhCCOOfsuVf37l5rXsaoUVXjl5@/@@Uv//mfXz/99u9/8cf37//@P/3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bVcj@Kira0nIFde8rG08S5HXofX01Li00SxBeVmFJf4Ykoa9NRQV0IYAmNl3qJyvt/jnkwdomN1ky/l9TeaPb13G6ZwAjVjzOw0igF9Qa@jJPheOUETojMDK21NJwGllHA8dH3ImTVTjm79rVModGBw5K55Q086owE5zVkmqqxvhf@Bw "C (gcc) – Try It Online") ]
[Question] [ You're tasked with writing an algorithm to efficiently estimate cost of solving an [Eni-Puzzle](http://www.enipuzzles.com/buy/eni-braille-puzzle-with-bold-colors) from a scrambled state as follows: You're given m lists of containing n elements each(representing the rows of the puzzle). The elements are numbers between 0 and n-1 inclusive (representing the colors of tiles). There are exactly m occurrences of each integers across all m lists (one for each list). For example: ``` m=3, n=4 : [[3, 0, 3, 1], [[1, 3, 0, 1], [1, 0, 2, 2], or [0, 2, 3, 1], [3, 0, 1, 2]] [0, 3, 2, 2]] ``` You can manipulate these lists in two ways: 1: Swapping two elements between circularly adjacent indices in (non circularly) adjacent lists. Cost=1. Ex: ``` m=3, n=4 : Legal: Swap((0,0)(1,1)) Swap((1,0)(2,3)) (circularly adjacent) Illegal: Swap((0,0)(0,1)) (same list) Swap((0,0)(2,1)) (lists are not adjacent) Swap((0,0)(1,0)) (indices are not circularly adjacent (they're the same) Swap((0,0)(1,2)) (indices are not circularly adjacent) ``` 2. Circularly shifting one of the lists (Cost=number of shifts) Your algorithm must efficiently calculate minimum cost required to manipulate the lists such that the resulting lists are all rotations of each other (meaning the puzzle can be fully solved from this state using only rotation moves) i.e.: ``` [[0, 1, 2, 3] [[2, 1, 0, 3] [3, 0, 1, 2] and [0, 3, 2, 1] [1, 2, 3, 0]] [3, 2, 1, 0]] ``` ...are both valid final states. Instead of lists, you may use any data structure(s) of your choice to represent the puzzle, so long as the cost of simulating a valid move (sliding or rotating) on the puzzle with this representation is O(n\*m). The setup cost of initializing this data structure can be disregarded. A winning solution will compute the cost in the lowest asymptotic runtime in terms of m and n. Execution time will be assessed as a tie breaker. ]
[Question] [ Write the shortest program possible such that when you combine the first character and every Nth character after it into a new program, the output is N. This must work for N = 1, 2, ..., 16. Another way to say it is, if you *remove* all the characters from your program *except for* the first one and every Nth one after that, the output of the remaining code should be N. # Example If your code was ``` ABCDEFGHIJKLMNOP ``` N = 1 results in `ABCDEFGHIJKLMNOP`. Running this should output 1. N = 2 results in `ACEGIKMO`. Running this should output 2. N = 3 results in `ADGJMP`. Running this should output 3. N = 4 results in `AEIM`. Running this should output 4. N = 5 results in `AFKP`. Running this should output 5. N = 6 results in `AGM`. Running this should output 6. N = 7 results in `AHO`. Running this should output 7. N = 8 results in `AI`. Running this should output 8. N = 9 results in `AJ`. Running this should output 9. N = 10 results in `AK`. Running this should output 10. N = 11 results in `AL`. Running this should output 11. N = 12 results in `AM`. Running this should output 12. N = 13 results in `AN`. Running this should output 13. N = 14 results in `AO`. Running this should output 14. N = 15 results in `AP`. Running this should output 15. N = 16 results in `A`. Running this should output 16. # Details * All characters are allowed, ASCII and non-ASCII. (Newlines and unprintable ASCII are allowed as well. Note that carriage return and line feed count as distinct characters.) * Your score is the length *in characters* of your unaltered program (15 in example). The lowest score wins. * A score below 16 is clearly impossible because then at least two of the altered programs would be identical. * Output may be to a file or stdout or anything else reasonable. However, the output of the 16 different programs must all go to the same place (e.g. it's not ok if `AO` goes to stdout but `A` goes to a file). There is no input. * The output must be in decimal, not hex. The actual output should only contain the 1 or 2 characters that make up the number from 1 to 16, nothing else. (Things like Matlab's `ans =` are ok.) * Your program does not have to work for N = 17 or above. [Answer] # Befunge 93 - Five million seven-hundred sixty-five thousand and seven-hundred and seventy six characters I demand to be taken seriously... ``` v &(720 720 - 80) X SPACE """""""""""""""" &(720 720 - 80) X SPACE 1234567890123456 &(720 720 - 80) X SPACE """""""""1111111 &(720 720 - 80) X SPACE ,,,,,,,,,""""""" &(720 720 - 80) X SPACE @@@@@@@@@,,,,,,, &(720 720 - 80) X SPACE ,,,,,,, &(720 720 - 80) X SPACE @@@@@@@ &(720 720 - 80) X SPACE ``` 3 reasons why. 1st reason: a befunge script is always 80x25, so no matter what, there had to be **something** that got reduced on the lines with code. 2nd reason: why that something is about 5.5 million spaces is because 720 720 is the smallest common multiple of 1 to 16... Means there will be no wrap around mess when we're skipping characters. 3rd reason: wow, this is pretty absurd. [Answer] # Python - ~~1201~~ 1137 (generator: ~~241~~ 218) - Long live the hashes! **Strategy:** I tried to start every line with as many hashes as the desired output `n`. Then all other versions will skip this line completely. The main difficulty, however, was to append the correct number of hashes so that the next run will hit the beginning of the next line exactly. Furthermore, interferences with other versions might occur, e.g. version 16 jumping right into the `print` command of line 5 and so on. So this was a lot of trial and error combined with a helper script for rapid testing. **Statistics:** * Characters: ~~1201~~ 1137 * Hashes: ~~1066~~ 1002 (88.1 %) * Non-hashes: 135 (11.9 %) **Code:** ``` # print 1##### #p#r#i#n#t# #2###################### ##p##r##i##n##t## ##3### ###p###r###i###n###t### ###4 ####p####r####i####n####t#### ####5######### #####p#####r#####i#####n#####t##### #####6########## ######p######r######i######n######t###### ######7########### #######p#######r#######i#######n#######t####### #######8### ########p########r########i########n########t######## ########9## #########p#########r#########i#########n#########t######### #########1#########0## ##########p##########r##########i##########n##########t########## ##########1##########1## ###########p###########r###########i###########n###########t########### ###########1###########2## ############p############r############i############n############t############ ############1############3## #############p#############r#############i#############n#############t############# #############1#############4## ##############p##############r##############i##############n##############t############## ##############1##############5## ###############p###############r###############i###############n###############t############### ###############1###############6 ``` **Test script:** ``` with open('printn.py', 'r') as f: c = f.read() for n in range(1, 17): print "n =", n, "yields", exec c[::n] ``` **Output:** ``` n = 1 yields 1 n = 2 yields 2 n = 3 yields 3 n = 4 yields 4 n = 5 yields 5 n = 6 yields 6 n = 7 yields 7 n = 8 yields 8 n = 9 yields 9 n = 10 yields 10 n = 11 yields 11 n = 12 yields 12 n = 13 yields 13 n = 14 yields 14 n = 15 yields 15 n = 16 yields 16 ``` --- **Update: A generating script!** I thought about my solution and that there must be a pattern to generate it algorithmically. So here we go: ``` lines = ['#'] for i in range(1, 17): lines.append(('#' * (i - 1)).join('\nprint ' + `i`)) fail = True while fail: while ''.join(lines)[::i].find('print ' + `i`) < 0: lines[i] = '#' + lines[i] fail = False for n in range(1, 17): try: exec ''.join(lines)[::n] except: lines[i] = '#' + lines[i] fail = True break print ''.join(lines) ``` It builds the program line by line: 1. Start with a hash. 2. Append a new line `i` with the `print i` command and `i - 1` hashes in between each two neighboring characters. 3. While the "i-version" (every i-th character) of the current program does not contain the command `print i` (due to misalignment) or any `n`-version with `n in range(1, 17)` throws an exception, add another hash to the previous line. It actually returned a shorter program than I found manually this morning. (So I updated my solution above.) Furthermore, I'm pretty sure there is no shorter implementation following this pattern. But you never know! **Golfed version - ~~241~~ 218:** ``` h='#';L=[h];I=range(1,17);J=''.join for i in I: p='print '+`i`;L+=[(h*(i-1)).join('\n'+p)] while 1: while J(L)[::i].find(p)<0:L[i]=h+L[i] try: for n in I:exec J(L)[::n] break except:L[i]=h+L[i] print J(L) ``` Note that there might be a shorter generator, e.g. by hard-coding the required number of succeeding hashes for each line. But this one computes them itself and could be used for any N > 16. [Answer] # 209 characters (Various languages) I just tried to keep things simple and avoid putting anything in positions with a lot of prime factors. The advantage is an ability to run in many scripting languages. It should work in any language that is not deliberately perverse and has the following features: * Integer literals * Basic arithmetic operators +, - (subtraction and negation), \*, / * Prints the evaluation of a bare expression * Has a single character that begins a line comment For example, ## Python 2 command-line interpreter (though not from a file): ``` + 1 # 4 / 23 # # 5 # 9 # 7 6 * # # - 5 2 * - ## 2 6 #2 * 2 6 4 ``` ## MATLAB (simply replace '#' with '%'): ``` 1 % 4 / 23 % % 5 % 9 % 7 6 * % % - 5 2 * - %% 2 6 %2 * 2 6 4 ``` N.B. There should be 17 spaces preceding the first '1'. You guys know a lot of languages, so please help me list more that it could run in ( : ### EDIT: Added unary + at position 0 for Python to avoid the line being indented. [Answer] ## APL, 49 ``` ⌊⊃⍟○7⍟⍟1|/2111118 9⍝×-1 ×○3×4_5_× 1_ _⍝_⍝ __2 ``` **Altered programs** ``` 1 ⌊⊃⍟○7⍟⍟1|/2111118 9⍝×-1 ×○3×4_5_× 1_ _⍝_⍝ __2 2 ⌊⍟7⍟|21189×1×345× 1 ⍝⍝_2 3 ⌊○⍟/119-××5 1 ⍝ 2 4 ⌊7|18××4×1 ⍝2 5 ⌊⍟21×○5 6 ⌊⍟19×51⍝2 7 ⌊11-4 ⍝ 8 ⌊|8×× 2 9 ⌊/9×1 10 ⌊2×5 11 ⌊11 ⍝ 12 ⌊1×12 13 ⌊13 14 ⌊14⍝ 15 ⌊15 16 ⌊8×2 ``` **Explaination** I'll start from the bottom as it would make explaining easier There are two language feature of APL to keep in mind. One, APL has no operator precedence, statements are always evaluated right to left. Two, many APL functions behave quite differently depending if it is given one argument on its right (monadic) or two arguments on its left *and* right (dyadic). Monadic `⌊` is round down (floor function), Dyadic `×` is obviously multiplication, `⍝` comments out rest of the line This should make these obvious: ``` 16 ⌊8×2 15 ⌊15 14 ⌊14⍝ 13 ⌊13 12 ⌊1×12 11 ⌊11 ⍝ 10 ⌊2×5 ``` **9: `⌊/9×1`** `/` is Reduce. Basically it takes the function of the left and the array on the right, insert the function between every pair of elements of the array and evaluate. (This is called "fold" in some languages) Here, the right argument is a scalar so `/` does nothing. **8: `⌊|8×× 2`** Monadic `×` is the [signum function](http://en.wikipedia.org/wiki/Sign_function) and monadic `|` is the absolute value function So, `× 2` evaluates to `1` and `|8×1` is of course `8` **7: `⌊11-4 ⍝`** should be obvious **6: `⌊⍟19×51⍝2`** Monadic `⍟` is natural log So, `⍟19×51` evaluates to `ln(19×51) = 6.87626...`, and `⌊` rounds it down to `6` **5: `⌊⍟21×○5`** Monadic `○` multiplies its argument by π `⍟21×○5` is `ln(21×5π) = 5.79869...` **4: `⌊7|18××4×1 ⍝2`** Dyadic `|` is the mod function `×4×1` evaluates to `1`, and `7|18×1` is `18 mod 7 = 4` **3: `⌊○⍟/119-××5 1 ⍝ 2`** Space-separated values is an array. Note that in APL, when most scalar functions are give array arguments, it is an implicit map. Dyadic `⍟` is log So `××5 1`, is signum of signum on 5 and 1, which gives `1 1`, `119-1 1` is `¯118 ¯118` (`¯` is just the minus sign. APL has to distinguish between negative numbers and subtraction), and `⍟/¯118 ¯118` is log-118(-118) = 1 **2: `⌊⍟7⍟|21189×1×345× 1 ⍝⍝_2`** You can work it out yourself **1: `⌊⊃⍟○7⍟⍟1|/2111118 9⍝×-1 ×○3×4_5_× 1_ _⍝_⍝ __2`** This one consist of a more complicated use of `/`. If `n` is a number, `F` is a function, and `A` is an array, then `nF/A` takes each group of `n` consecutive entries of `A` and apply `F/`. For example, `2×/1 2 3` takes each pair of consecutive entries (which are `1 2` and `2 3`) and apply `×/` to each group to give `2 6` So, `1|/2111118 9` just returns `2111118 9` (as it applies `|/` to scalars). Then, `⍟○7⍟⍟` applies ln, then log7 to those numbers, then multiplies them by π and ln again. The numbers that come out the other side are `1.46424... 0.23972...` Here, `⊃` is just used to select the first element of an array. [Answer] # CJam, 89 bytes ``` GiiAHH(5A5(7ii)ii;(;(-i((i(-i)i)ii)i()i((i(i(iiii(iii(iiiii(iiiii(i-i(iiiiiii(ii(ii(-ii- ``` This approach doesn't use any kind of comments. `i` casts to integer, so it is a noop here. It could be replaced by whitespace, but the letters seem more readable to me... [Try it online](http://cjam.aditsu.net) by executing the following *Code*: ``` G,{) "GiiAHH(5A5(7ii)ii;(;(-i((i(-i)i)ii)i()i((i(i(iiiii(iii(iiiii(iiiii(i-i(iiiiiii(ii(ii(-ii-" %_~}%N* ``` ### Example run ``` $ cat nth-char.cjam G,{)"GiiAHH(5A5(7ii)ii;(;(-i((i(-i)i)ii)i()i((i(i(i iii(iii(iiiii(iiiii(i-i(iiiiiii(ii(ii(-ii-"%_~}%N*N $ cjam nth-char.cjam GiiAHH(5A5(7ii)ii;(;(-i((i(-i)i)ii)i()i((i(i(i iii(iii(iiiii(iiiii(i-i(iiiiiii(ii(ii(-ii- 1 GiH(A(i)i((i((iii)(i((( i(i(ii(ii(-(iii(ii(i- 2 GA(5ii(-(-ii(((iii(i(i(iii(((i 3 GHAii((ii(((iii(i-iii(- 4 GH(i(iii(i(i(i(ii- 5 G(i((i((i(((i(( 6 G5)-ii(iii(i( 7 GAi(i(iiiii- 8 G5(-(i(ii( 9 G((i((((i 10 G7ii(i(i- 11 Gi((i(i( 12 Gi((ii( 13 G)i(i(( 14 Giii(i 15 Giiiii 16 ``` [Answer] # GolfScript, 61 bytes ``` 1})_#;#;;00123358_(_};}_}_}} _}_(__6 _})4_)_+)__(__}__;_}___6 ``` This takes advantage of comments (`#`) and the undocumented "super-comments" (everything following an unmatched `}` it is silently ignored). `_` is a noop. It could be replaced by whitespace, but the underscores seem more readable to me... [Try it online.](http://golfscript.apphb.com/?c=MTYseykiMX0pXyM7Izs7MDAxMjMzNThfKF99O31ffV99fSBffV8oX182Cl99KTRfKV8rKV9fKF9ffV9fO199X19fNiJcJS5%2BfSVuKg%3D%3D "Web GolfScript") # Example run ``` $ cat nth-char.gs 16,{)"1})_#;#;;00123358_(_};}_}_}} _}_(__6 _})4_)_+)__(__}__;_}___6"\%.~}%n* $ golfscript nth-char.gs 1})_#;#;;00123358_(_};}_}_}} _}_(__6 _})4_)_+)__(__}__;_}___6 1 1)##;0238(}}}} }(_ }4)+_(__;}_6 2 1_#025(;}}}_ )))(};_6 3 1#;28}} ( 4+(_}6 4 1;05}_}64)__6 5 1#2(}} )(;6 6 1;3; 6)_} 7 1;8}(4(} 8 10(} ); 9 10}}4_6 10 11}_+_ 11 12} (6 12 13})_ 13 13 )} 14 15})6 15 18(( 16 ``` [Answer] # [Zsh](https://www.zsh.org/), 249 bytes ``` b y e 2y y yyyy e bye 1 e e e e 9 1 1 11 1 13 4 5 6 b b b y y y e 6 8 1 0 b b y e e 7b y e 1 5 2 b b yy e 3 4 ``` [Verify all slices online!](https://ato.pxeger.com/run?1=ZVBRTgIxEP3ed4pJaLIQA3EAEUk23oALGD_cOsgmuCUgmko4iT-bEA_lUfxz2q77w2v7ZtqZ15nM1_lzv27Otsi_D2-r4fznt4SHgDD26niF3kovxBAS9YWAO2iCbo4MsG5OFjxRwjTQTaAZLlF2JxaJbxKZ4gqaeftfwnWnS4RWlWQSu1DclsHz_wGmrg2ML3rQ6j7mEWGCaTuAbQ5bmKNd8Il6tJNX9y60kafnqn6hWj42VS1YuR0tqX_k0YhnpwH1kbkiz5GFQJUCpmeVlhp1V4WxD9UjMh02DS0Zh0zs2pG5xyDVbZpk_wA) Every sliced program is of the form: ``` [...junk] bye N [junk...] ``` For example, for \$ N = 8 \$: ``` b2y1e 11 6 bye 8 y e 2 be4 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwUKNpaUlaboWNxWTjCoNU7kUDA25zLi4kipTFSy4uLgqubgUUrmMuJJSTbggCldqcqUmZ-QrqNhD-AsWQGgA) The only code that matters is the `bye 8`, which exits the program with the exit code of 8. The rest of the junk is just ignored by zsh, because it's all invalid commands. (Everything after the first valid `bye` also doesn't matter, because it never gets executed). --- To optimise this answer, we want to interleave the programs `bye 1`, `b y e 2`, `b y e 3`, etc., so that: * every program starts at an offset that is a multiple of its corresponding value of \$ N \$ * none of the programs "overlap", putting different characters in the same place, which will break the code * the total length is minimised (of course) This problem boils down to searching over the permutations of \$ [1, 16] \$, and then inserting each program in the chosen order at the first valid offset in the output code. I tried various strategies to solve these constraints, including some obvious orderings picked by hand, and a greedy breadth-first search, but the most successful was a crude "Monte Carlo" method: 1. shuffle the range into a particular order 2. arrange the programs in that order 3. if this solution was shorter than the previous iteration, then save it as the current shortest possibility 4. repeat ad nauseam Here's my optimiser code, in Python: ``` import re, random, time def valid(code, n): match = pattern.search(''.join(code)) return match and match[1] == str(n) pattern = re.compile(r"^\s*bye\s+(\d+)\s*$", re.MULTILINE) # for repeatability seed = int(time.time() * 1e6) print(f"{seed=}") random.seed(seed) ns = list(range(1, 17)) # it's pretty much guaranteed we'll find a solution shorter than this fake one result = "dummy" * 100 while True: code = ["\n"] * 1000 random.shuffle(ns) used = set() for n in ns: used.add(n) out = code.copy() insert = f"bye {n}" offset = 0 out[offset:offset + len(insert) * n:n] = insert while not all(valid(out[::i], i) for i in used): offset += n if offset >= 250: # too long break out = code.copy() out[offset:offset + len(insert) * n:n] = insert # hack to propogate break else: code = out continue break else: candidate = "".join(code).rstrip("\n") if len(candidate) < len(result): result = candidate print("------") print("length:", len(result)) print(result) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=pVRLbtswEN10pVMM5AKmYkewC_QDoy7QRRcB0naTrmIXYKyhxYYiBZJKagQ5STbZtIfqNXqBDkX5IzddlQtCmjd8M_NmyIef9caXRj8-_mi8OH3z69lvWdXGerA4Bst1YaoxeFlhkhQo4IYrWbCVKQjV2SwBWhX3qxLmUHPv0ercIberkg2H-TcjdeucZa2nRd9Y3R0g7vh1OV3CfA7OW6azJOloiNBivjJVLRUym35duJOrDS7ciC2KUUZ_z9NxcPn45fzi7Pzs04cMkmQAwliy1sg9v5JK-k3iEAtik9qzUEgeNpbBCUzxVZbUNgAivQtu8_s0S2LVefhnYaOctCMCJZ1nBK6RTccwfU1FUTzphw5qqsxvoGqornXDycmHoLc4VAqEpEo5OKMaL40GV5K-aMGXXNMmHQh-jWA0JhZdozzFSoumqjZpSHIySZLbkkSAC9tglDxoSl6X6UKny-g0iQp3uZeNECSbdlH4xrUSOPQsGoJKmiQB7SLj1ivnRRHasLWZJqQT4lEv6g3bI1I7tAEUKfUF7vR9uj8lBMUibHJIdBnNsw4dgULNIk1oh57pZdunYNidi6Vr44ErxeL8Ba7ZTC7HILO2FBlKCeln-2oO8hjNQffsUmyhd3N48XLSPxXWALwxoIxe_wVdWeTX_TD_FOl_Kh9AyVfXlAeNl6nNmns8io3KYT_1bjAo5JFZe6kb3Bn3PH2OFc2PLEIkmsH04ALnlu6nrFmYuIMZEG0lu1MZvG0NcY6PmrEb7p17D44XMT1tV5o9hRH12pczuvcHQZ7y7KAegt8lTX-Qld8YWcD7i8_tw0ZaxbevewK3T-Ef) (but due to ATO's timeout and non-streaming nature, this is probably better run on your actual computer) ]
[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/128651/edit). Closed 6 years ago. [Improve this question](/posts/128651/edit) If you've come here, you probably know what [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") is, and that's what I'm going to assume. ## Story (I guess) Keyboards are input devices we use all the time. They existed before mice and touch screen, etc. Their fundamentals have not changed: when you press a key down, a signal is sent to the computer. When you release it, another signal is sent. So here's the **challenge**: calculate the minimum number of signals(length of a signal does not matter) depending on the input string. ## Example: Input: ``` test ``` Output: ``` 8 ``` > > Explanation: > All keys have to be pressed down and released > > > Input2: ``` TEst ``` Output2: ``` 10 ``` > > Explanation: > Shift has to be pressed, then T, down, up, E, down, up, then release shift, then s down, up, then t down, up, totalling up to 10. > > > ## Rules Any language is accepted. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. Programs with incorrect outputs will be disqualified. ## Happy golfing! # Edit: The keyboard layout used should be this: <http://dry.sailingissues.com/keyboard-US-International.png> Only characters in this keyboard layout will be used (+lowercase letters). Using Caps-Lock is ok, since it DOES have an advantage: numbers remain numbers while letters become uppercase. ]
[Question] [ I'll start off by saying I [checked](https://codegolf.meta.stackexchange.com/questions/12392/can-i-ask-about-improving-golfing-on-some-code) and [checked again](https://codegolf.meta.stackexchange.com/a/1724/38550) that this question should be on topic. I will also clearly state that this is a [tips](/questions/tagged/tips "show questions tagged 'tips'") question about further golfing a certain set of code **not** a challenge. --- I recently answered the following challenge: [Scramble words while preserving their outlines](https://codegolf.stackexchange.com/q/119891/38550): > > It is well known that a text can still be read while the innards of its words have been scrambled, as long as their first and last letters plus their overall outlines remain constant. Given a printable Ascii+Newline text, scramble each word according to these rules: > > > 1. Scrambling must be (pseudo) random. > 2. A word is a sequence of the Latin characters, A through Z. > 3. Only initial letters will ever be uppercase. > 4. The first and last letters must stay untouched. > 5. When scrambling, only letters within one of the following groups may exchange places: > > > 1. `acemnorsuvwxz` > 2. `bdfhkl` > 3. `gpqy` > 4. `it` > 5. `j` (stays in place) > > > [My answer](https://codegolf.stackexchange.com/a/120253/38550) is in C# and coming in, currently, at 394 bytes: ``` namespace System{using Text.RegularExpressions;using Linq;s=>Regex.Replace(s,@"[A-Za-z](([acemnorsu-xz])|([bdfhkl])|([gpqy])|([it]))*?[a-z]?\b",m=>{var a=m.Value.ToCharArray();for(int i=1,j;++i<6;){var c=m.Groups[i].Captures;var n=c.Cast<Capture>().Select(p=>p.Index-m.Index).ToList();foreach(Capture p in c){a[j=n[new Random().Next(n.Count)]]=p.Value[0];n.Remove(j);}}return new string(a);});} ``` I think there's room for golfing in the Linq statement and `foreach` loop at least. Can this code be further golfed down? [Answer] As I am using `linq` in my program, I can change `ToCharArray` to `ToArray` to save 4 bytes. I can also change the `namespace` around to be either `System.Linq` or `System.Text.RegularExpressions` to save a further 6 bytes by removing the `using` for it: ``` namespace System.Text.RegularExpressions ``` As @MartinEnder♦︎ points out in the comments I can save 10 bytes by re-ordering the groups in the regex and changing `[A-Za-z]` to `\p{L}`: ``` \p{L}(([gpqy])|(i|t)|(j)|([bdf-l])|([a-z]))*?[a-z]?\b ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/119515/edit). Closed 6 years ago. [Improve this question](/posts/119515/edit) Today I installed [MonoGame](http://www.monogame.net) and ran the test application, which creates a basic colored window. I was surprised to see that the process was using 32.2 MiB of memory, and I thought it could be improved. [![enter image description here](https://i.stack.imgur.com/5XhyD.png)](https://i.stack.imgur.com/5XhyD.png) Your challenge is to write a program that creates a 640 by 480 window displaying only black pixels. Whatever program uses the least physical memory to do so wins. You may use any operating system released after the year 2000. [Answer] # C, 96KiB Never seen `restricted-memory` but i guess code length doesn't matter here. RAM usage was taken from gnome-system-monitor (i hope it's accurate). ``` #include <stdlib.h> #include <stdio.h> #include <xcb/xcb.h> int main () { xcb_connection_t *c; xcb_screen_t *screen; xcb_drawable_t win; xcb_generic_event_t *e; uint32_t values[2]; char string[] = " "; c = xcb_connect (NULL, NULL); screen = xcb_setup_roots_iterator (xcb_get_setup (c)).data; win = screen->root; win = xcb_generate_id(c); values[0] = screen->black_pixel; values[1] = XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_KEY_PRESS; xcb_create_window (c,XCB_COPY_FROM_PARENT,win,screen->root, 0, 0,640,480,10,XCB_WINDOW_CLASS_INPUT_OUTPUT,screen->root_visual,XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK, values); xcb_map_window (c, win); xcb_flush (c); while ((e = xcb_wait_for_event (c))) { switch (e->response_type & ~0x80) { case XCB_EXPOSE: xcb_flush (c); break; } free (e); } return 0; } ``` This code works on pretty much every linux with a running xserver. To compile add `-lxcb` for the xcb libs. ]
[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/111129/edit). Closed 6 years ago. [Improve this question](/posts/111129/edit) ![](https://upload.wikimedia.org/wikipedia/en/b/b7/Missingno.png) I think is about time to do another Pokemon challenge! Even if Pokémon Go is not as mainstream as it used to be... ### The task. Just draw a [MISSINGNO](https://en.wikipedia.org/wiki/MissingNo). MISSINGNO is an unofficial Pokémon species found in the video games Pokémon Red and Blue. [IGN](https://en.wikipedia.org/wiki/IGN) has noted MISSINGNO appearance in Pokémon Red and Blue as one of the most famous video game glitches. ### How MISSINGNO looks like? This Pokémon is a 3 tiles wide 7 tiles high image of random pixels. Each tile is 8x8 pixels. Considering `x` as horizontal coordinate which increases from left to right, `y` as vertical coordinate which increases from top to bottom and `[x, y]` as coordinate system, the tiles `[0, 0]`, `[0, 1]` and `[0, 2]` are blank. The original MISSINGNO appears in Game Boy color roughly as the screenshot below: [![](https://i.stack.imgur.com/OLhN8.png)](https://i.stack.imgur.com/OLhN8.png) (source: [nocookie.net](https://vignette2.wikia.nocookie.net/mcleodgaming/images/d/d8/MissingNo..png/revision/latest?cb=20131108185400)) ### Your MISSINGNO. Your MISSINGNO shoudn't be exactly as the one in the screenshots above, but it should follow this pattern: * Should be formed of 21 tiles, 3 tiles wide 7 tiles high. * Every tile should have at least 9 colors, more than 9 colors is alowed, less is forbidden. * Every tile should have the same pixels in width and in heigth: this is, every tile should be a square. * Every tile should be of the same size, but they can be of any arbitrary size as long as they can show at least 9 colors (a MISSINGNO of 21 tiles of 3x3 pixels is as valid as one with 21 1000x1000 pixels tiles). * Tiles `[0, 0]`, `[0, 1]` and `[0, 2]` should be transparent (alpha 0), look at *How MISSINGNO looks like?* to know the coordinates system. * Transparent means transparent. So any color is acceptable as long as it is completely transparent (alpha 0). * The opaque tiles shall be completely opaques, no transparent or semi-transparent pixels allowed. * Repeated opaque tiles are forbidden. * As long as the tiles follows the rules above, they can be anything: either procedural random pixels tiles or (as an example) pictures from google image search are alowed. ### Your output. Your output should be a image in any format your language supports. * The size of the image should be `3 * tile width` wide and `7 * tile height` high with no additional pixels alowed. So if you're using 3x3 tiles the image size should be: 9 pixels width and 21 pixels high, with 42x42 tiles the image size should be: 126 pixels width and 294 pixels high. * The ouptut image should be different every program call. Look at *Your MISSINGNO* to know about the size of the tiles. * The task is to generate the MISSINGNO image, not to show it. So as long as the image is generated the program is valid (but please, upload your results! all of us want to enjoy them!). ### Your program. It can accept a single integer value, this value will be the size of the MISSINGNO tiles. * You can assume that the input will be always possitive and equal to or greater than 3. Look at *Your MISSINGNO* to know about the size of the tiles. * If no input is provided, the default value is 8. --- This is code golf, so the shortest code in bytes win! [Answer] # JavaScript ES6 + HTML, 148 146 143 137 + 24 22 = 172 170 167 159 bytes HTML ``` <canvas id=c></canvas> ``` JavaScript ``` d=c.getContext`2d`;for(x=0;x<9;x++)for(y=0;y<21;y++)if(x>2||y>8)d.fillStyle='#'+(Math.random()*0xFFF<<0).toString(16),d.fillRect(x,y,1,1) ``` Saved 8 bytes thanks to ETHproductions. The image in the snippet has been scaled by 10 pixels to be more visible. ``` var d = c.getContext`2d`; for(var x = 0; x < 90; x+=10) { for(var y = 0; y < 210; y+=10) { if (x > 20 || y > 80) { d.fillStyle = '#'+(Math.random()*0xFFF<<0).toString(16); d.fillRect(x, y, 10, 10); } } } ``` ``` <canvas id="c" width="90" height="210"></canvas> ``` ]
[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/95254/edit). Closed 7 years ago. [Improve this question](/posts/95254/edit) ## Challenge Given a fraction with a surd (an irrational number) as the denominator, output the rationalised fraction. ## Rationalising the Denominator To rationalise the denominator, what you have to do is take the fraction and make one which is equal which does not have an irrational number in the denominator. Generally, the method is as follows: > > Say the inputted fraction is: > > > > ``` > (a + x * sqrt(b)) / (c + y * sqrt(d)) > > ``` > > To rationalise the denominator, you need to multiply the numerator and the denominator by the conjugate of `c + y * sqrt(d)` (`c - y * sqrt(d)`): > > > > ``` > (a + x * sqrt(b)) / (c + y * sqrt(d)) * (c - y * sqrt(d)) / (c - y * sqrt(d)) > > ``` > > To get: > > > > ``` > ((a + x * sqrt(b))(c - y * sqrt(d))) / (c^2 + y * d) > > ``` > > Which you should then simplify completely > > > ## Example **Input:** ``` (4 + 3 * sqrt(2))/(3 - sqrt(5)) ``` **Method:** ``` (4 + 3 * sqrt(2))/(3 - sqrt(5)) * (3 + sqrt(5))/(3 + sqrt(5)) ((4 + 3 * sqrt(2))(3 + sqrt(5)))/(9 - 5) (12 + 4 * sqrt(5) + 9 * sqrt(2) + 3 * sqrt(10))/(4) ``` **Output:** ``` (12 + 4 * sqrt(5) + 9 * sqrt(2) + 3 * sqrt(10))/(4) ``` --- **Input:** ``` 3 / sqrt(13) ``` **Method:** ``` 3 / sqrt(13) * sqrt(13) / sqrt(13) (3 * sqrt(13)) / 13 ``` **Output:** ``` (3 * sqrt(13)) / 13 ``` --- **Input:** ``` 1 / (sqrt(5) + sqrt(8)) ``` **Method:** ``` 1/ (sqrt(5) + sqrt(8)) * (sqrt(5) - sqrt(8)) / (sqrt(5) - sqrt(8)) (sqrt(5) - sqrt(8)) / (sqrt(5) + sqrt(8))(sqrt(5) - sqrt(8)) (sqrt(5) - sqrt(8)) / (5 - 8) (sqrt(5) - sqrt(8)) / -3 ``` **Output:** ``` (sqrt(5) - sqrt(8)) / -3 ``` --- **Input:** ``` 2 / (3 * sqrt(20) + sqrt(50) + sqrt(2)) ``` **Method:** ``` 2 / (3 * sqrt(20) + sqrt(50) + sqrt(2)) * (63 * sqrt(20) - sqrt(50) - sqrt(2)) / (3 * sqrt(20) - sqrt(50) - sqrt(2)) 2(3 * sqrt(20) - sqrt(50) - sqrt(2)) / (108) (3 * sqrt(20) - sqrt(50) - sqrt(2)) / (54) (3 * 2 * sqrt(5) - 5 * sqrt(2) - sqrt(2)) / (54) (6 * sqrt(5) - 6 * sqrt(2)) / (54) ``` **Output:** ``` (6 * sqrt(5) - 6 * sqrt(2)) / (54) ``` *If you want, you can simplify this further to:* ``` (6 * (sqrt(5) - sqrt(2))) / (54) ``` or: ``` (sqrt(5) - sqrt(2)) / (9) ``` ## Rules All input will be in its simplest form. For example, the surd `7*sqrt(12)` will be simplified to `14*sqrt(3)` in the input. Your program only needs to support addition, subtraction, multiplication, division, square roots and brackets (including expansion of multiplied brackets). Your input and output may be in any form that you wish as long as it is a fraction and, when pasted into Wolfram Alpha, the input equals the output. There will never be variables in the input, nor will there be the square roots of negative numbers. There will only ever be one fraction in the input. There will always be an irrational number in the denominator. Except `b` and `y` may not always be present. Your output must be simplified. This refers to both the simplification of the algebraic expressions and also putting the lowest possible number in the square root. For example: ``` sqrt(72) ``` Which can be simplified like so: ``` sqrt(72) = sqrt(9 * 8) = sqrt(9) * sqrt(8) = 3 * sqrt(8) = 3 * sqrt(4 * 2) = 3 * sqrt(4) * sqrt(2) = 3 * 2 * sqrt(2) = 6 * sqrt(2) ``` Built-in functions and libraries to rationalise fractions are disallowed. Similarly, internet access is disallowed. ## Winning The shortest code in bytes wins. ]
[Question] [ As part of a city planning project, you've gotten the assignment of creating a program or function that will display the city skyline, given some input from the architects. The project is only in the startup phase, so a very rough sketch is sufficient. The easiest approach is of course to simply draw the skyline in ASCII-art. All buildings will be by the river, thus they are all aligned. The architects will give the height of each building as input, and your code should display the skyline. The input from the architects will either be an integer or a half-integer. If the number is an integer, the building will have a flat roof, while a half-integer will result in a pitched roof. A zero will just be flat ground. The walls of a building are 3 characters apart, while a zero will be a single character wide. Adjacent buildings share walls. For details and clarifications regarding the output, please have a look at the examples below: ``` N = 3 ___ | | | | |___| N = 3.5 _ / \ | | | | |___| N = 6 ___ | | | | | | | | | | |___| n = 0 _ ``` Example input: `3 3.5 0 2` ``` _ ___ / \ | | | ___ | | | | | |___|___|_|___| ``` Example input: `0 0 2.5 3 0 4 1` ``` ___ _ ___ | | / \| | | | | | | | |___ __|___|___|_|___|___| ``` [Louisville](https://i.stack.imgur.com/eePKt.jpg), `0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1` ``` ___ ___ | | | | ___ _ ___ ___ ___| | | | | | / \ | | | | | | | | | | | ___ | | | |___| |___| | | | | | | | |___| | | | | | | | |___| | | |___ _|___|___|___|_|___|___|___|___|___|___|___|___|_|___|___| ``` The ASCII-characters used are: newline, space, and `/\_|` (code points 10, 32, 47, 92, 95, 124). **Rules:** * It's optional to make a program that only take integers as input, by multiplying all numbers by two. So, instead of taking `3 3.5 2`, your program may take `6 7 4`. If the second input format is chosen, an input of 6 should result in a 3 story building, 7 should be a 3 story building with pitched roofs etc. * The output should be exactly as described above, but trailing spaces and newlines are OK. * The exact format of the input is optional. Whatever is best in your language. * The result must be displayed on the screen, so that the architects can have a look at it. * You can assume there will be at least one integer given, and that only valid input will be given. **This is codegolf, so the shortest code in bytes win.** [Answer] # Python 2, ~~199~~ ~~193~~ ~~188~~ 185 bytes ``` a=map(int,raw_input().split()) l=max(a)+1|1 while~l:print''.join((x%2*'/ _\\ '[x<l::2]*(x<=l<x+4)or'_ '[x|1!=l>1]*3)[x<1:x+2]+'| '[x<=l>=y]*(x+y>0)for x,y in zip([0]+a,a+[0]))[1:];l-=2 ``` This is a full program that accepts integers as input. [Example input](http://ideone.com/M2uYzL). [Answer] # MATLAB, ~~219 209~~ 203 bytes ``` i=input('');x=1;c=0;m(1:4*numel(i))='_';for a=i;b=fix(a);m(1:b,x)='|';s=95;if a~=b;m(b+2,x+2)=95;s='/ \';end;m(b+1,x+(1:3))=s;x=x+(a>0)*3+1;m(1:b,x)='|';x=x+(a<1&c>0);c=a;end;disp(flipud(m(:,1:x-(a<1)))) ``` This unfortunately doesn't work on **Octave**. Not entirely sure why, seems to be something to do with the disp/flipud bit that breaks. Also, there is currently no definition of what a 0.5 height building looks like, nor any mention of them, so in this code I assume that they are disallowed. The following is the code in a slightly more readable way: ``` i=input(''); %e.g. [0 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1 0 0 1 0] x=1; c=0; m(1:4*numel(i))='_'; for a=i; b=fix(a); m(1:b,x)='|'; s=95; if a~=b; m(b+2,x+2)=95; s='/ \'; end; m(b+1,x+(1:3))=s; x=x+(a>0)*3+1; m(1:b,x)='|'; x=x+(a<1&c>0); c=a; end; disp(flipud(m(:,1:x-(a<1)))) ``` --- First we take an input as an array, and do some variable initialisation. ``` i=input(''); %e.g. [0 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1] x=1; c=0; ``` Because the zero height buildings are a pain - they basically end up with a width which is dependent on what they are next to (though what is printed doesn't change), we simplify things by drawing enough ground for all of the buildings. We assume each building will be 4 characters wide (because adjacent buildings merge together) - zero height ones aren't, but the excess will be trimmed later. ``` m(1:4*numel(i))='_'; ``` Now we draw out each building in turn. ``` for a=i ``` First we get the integer part of the height as this will determine how many '|' we need. ``` b=fix(a); ``` Now draw in the wall for this building - if there are two adjacent buildings, the wall for this new one will be in the same column as the wall from the last one. ``` m(1:b,x)='|'; ``` Check to see if this is a half height building. If it is, then the roof will be different. For the half heights, the roof is going to be `/ \` whereas full height ones it will be `___` (Matlab will implicitly replicate this from a single underscore, so save a couple of bytes there). There is an extra bit of roof one row higher for the half height buildings, so that is added as well. ``` s=95; if a~=b; m(b+2,x+2)=95; s='/ \'; end; ``` Draw in the roof ``` m(b+1,x+(1:3))=s; ``` Now move to the start of the next building and draw in the shared wall (if the wall is too short at this point, it will be made larger when the next building is drawn). Note that zero height buildings are 1 wide, normal buildings are 4 wide, so we simplify what would otherwise be an if-else by treating (a>0) as a decimal number not a Boolean. ``` x=x+(a>0)*3+1; m(1:b,x)='|'; ``` Next comes a bit of hackery to work with zero height buildings. Basically what this says is if this building was zero height, and the one before that wasn't, it means the place of the next building needs incrementing by 1 because a zero height building sandwiched between two other buildings is effectively twice as wide - this accounts for the extra wall which is normally shared with an adjacent building. We also keep track of this building height for doing this check next time. ``` x=x+(a<1&c>0); c=a; end; ``` Once done, flip the building matrix to be the correct way up, and display it. Note that we also trim off any excess ground here as well. ``` disp(flipud(m(:,1:x-(a<1)))) ``` --- So, when we run this script, we are asked for our input, for example: ``` [0 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1 0 0 1 0] ``` It then generates the building and displays the result. For the above input, the following is generated: ``` ___ ___ | | | | ___ _ ___ ___ ___| | | | | | / \ | | | | | | | | | | | ___ | | | |___| |___| | | | | | | | |___| | | | | | | | |___| | | |___ ___ __|___|___|___|_|___|___|___|___|___|___|___|___|_|___|___|__|___|_ ``` [Answer] ## Kotlin, ~~447~~ 442 bytes ``` val a={s:String->val f=s.split(" ").map{it.toFloat()}.toFloatArray();val m=(f.max()!!+1).toInt();for(d in m downTo 0){var l=0f;for(c in f){val h=c.toInt();print(if(h==d&&d!=0)if(h<l-0.5)"|" else{" "}+if(c>h)"/ \\" else "___" else if(h<d)if(d<l-0.5)"|" else{" "}+if(h==0)" " else if((c+0.5).toInt()==d)" _ " else " " else{if(h==0)if(l<1)" " else "| " else "| "}.replace(' ',if(d==0)'_' else ' '));l=c;};if(d<l-0.5)print("|");println();}} ``` ## Ungolfed version: ``` val ungolfed: (String) -> Unit = { s -> val floats = s.split(" ").map { it.toFloat() }.toFloatArray() val maxH = (floats.max()!! + 1).toInt() for (drawHeight in maxH downTo 0) { var lastBuildingH = 0f for (f in floats) { val buildingH = f.toInt() if (drawHeight == 0) { // Baseline if (buildingH == 0) if (lastBuildingH.toInt() == 0) print("__") else print("|_") else print("|___") } else if (buildingH == drawHeight) { // Ceiling if (buildingH < lastBuildingH - 0.5) print("|") else print(" ") if (f > buildingH) print("/ \\") else print("___") } else if (buildingH < drawHeight) { // Above building if (drawHeight < lastBuildingH - 0.5) print("|") else print(" ") if (buildingH == 0) print(" ") else { if ((f + 0.5).toInt() == drawHeight) print(" _ ") else print(" ") } } else { if (buildingH == 0) print("| ") else print("| ") } lastBuildingH = f; } if (drawHeight < lastBuildingH - 0.5) print("|") println() } } ``` [Answer] ## Python 2, ~~357~~ ~~306~~ ~~299~~ ~~294~~ ~~287~~ ~~281~~ 276 bytes ``` def s(l): d=len(l)+1;l=[0]+l+[0];h=(max(l)+3)/2;o='' for i in range(d*h): a=l[i%d+1];c=l[i%d];b=2*(h-1-i/d);o+="|"if(a>b+1)+(c>b+1)else" "*(a+c>0);o+=" _/__ _\\"[a-b+1::3]if b*(1>=abs(a-b))else" "*(1+2*(a>0)) if b==0:o=o.replace(" ","_") if i%d==d-1:print o[:-1];o='' ``` This uses the "doubled" encoding, to be passed to the function as a list. Edit: Shaved bytes by redoing part of the big conditional as an array selector, and switching to the doubled encoding. Shaved more bytes by rearranging the conditional even more and converting more logic to arithmetic. EDIT: [xsot's is better](https://codegolf.stackexchange.com/a/65293/47050) ### Explanation: ``` d=len(l)+1;l=[0]+l+[0];m=max(l);h=m/2+m%2+1;o='' ``` `d` is 1 more than the length of the array, because we're going to add zeros on each end of the list from the second element up to the zero we added on the end. `h` is the height of the drawing. (We have to divide by 2 in this calculation because we are using the doubled representation, which we use specifically to avoid having to cast floats to ints all over the place. We also add 1 before dividing so odd heights--pointy buildings--get a little more clearance than the regular kind.) `o` is the output string. ``` for i in range(d*h): ``` A standard trick for collapsing a double for loop into a single for loop. Once we do: ``` a=l[i%d+1];c=l[i%d];b=2*(h-1-i/d) ``` we have now accomplished the same as: ``` for b in range(2*h-2,-2,-2): for j in range(d): a=l[j+1];c=l[j] ``` but in a way which nets us ten bytes saved (including whitespace on the following lines). ``` o+="|"if(a>b+1)+(c>b+1)else" "*(a+c>0) ``` Stick a wall in any time the height of either the current building or the previous building is taller than the current line, as long as there is at least one building boundary here. It's the equivalent of the following conditional: ``` o+=("|" if a>b+1 or c>b+1 else " ") if a or c else "" ``` where b is the current scan height, a is the current building height, and c is the previous building height. The latter part of the conditional prevents putting walls between ground spaces. ``` o+=" _/__ _\\"[a-b+1::3]if b*(1>=abs(a-b))else" "*(1+2*(a>0)) ``` This is the part that draws the correct roof, selecting roof parts by comparing the building's height with the current scan height. If a roof doesn't go here, it prints an appropriate number of spaces (3 when it's an actual building, e.g., a>0, otherwise 1). Note that when we're at ground level, it never attempts to draw a roof, which means 0.5 size buildings don't get pointy roofs. Oh well. ``` if b==0:o=o.replace(" ","_") ``` When we're at ground level, we want underscores instead of spaces. We just replace them all in at once here. ``` if i%d==d-1:print o[:-1];o='' ``` Just before we start processing the next line, print the current one and clear the output line. We chop off the last character because it is the "\_" corresponding to the ground space we added by appending a zero at the beginning of the function. (We appended that zero so we would not have to add a special case to insert a right wall, if it exists, which would add far more code than we added by adding the 0 and chopping off the "\_".) [Answer] # Python 3 ## ~~725 bytes~~ ## 608 bytes Golfed code: ``` import sys,math; m,l,w,s,bh,ls,ins,r,a="| |","___","|"," ",0,[],[],range,sys.argv[1:] def ru(n):return math.ceil(n) def bl(h,n): if(n>ru(h)):return(s*5,s)[h==0] if(h==0):return"_" if(n==0):return w+l+w if(n<h-1):return m return(" _ "," / \ ")[n==ru(h)-1]if(h%1)else(s+l+s,m)[n==h-1] for arg in a: f=ru(float(arg)) if(bh<f):bh=f for i in r(bh,-1,-1): ln="" for bld in a:ln+=bl(float(bld),i) ls.append(ln) for i in r(len(ls[-1])-1): if(ls[-1][i]==ls[-1][i+1]==w):ins.append(i-len(ins)) for ln in ls: for i in ins:ln=(ln[:i]+ln[i+1:],ln[:i+1]+ln[i+2:])[ln[i]==w] print(ln) ``` Here's the ungolfed code. There are some comments but the basic idea is to create buildings with double walls, so the bottom line looks like: ``` _|___||___|_|___||___| ``` Then to get indexes of those double walls and remove those columns so we get: ``` _|___|___|_|___|___| ``` Code: ``` import sys import numbers import math mid="| |"; l="___"; w="|"; s=" "; def printList(lst): for it in lst: print(it); # h = height of building # l = line numeber starting at 0 def buildingline(h,n): #if (h==0): # return " " if(n>math.ceil(h)) else " "; if(n>math.ceil(h)): return s if(h == 0) else s*5; if(h==0): return "_"; if(n==0): return w+l+w; if(n<h-1): return mid; if(h.is_integer()): return mid if(n==h-1) else s+l+s; else: return " / \ " if (n==math.ceil(h)-1) else " _ "; # max height bh=0; for arg in sys.argv[1:]: f = math.ceil(float(arg)); if(bh<f):bh=f; # lines for printing lines = [] for i in range(bh,-1,-1): line=""; for bld in sys.argv[1:]: bld=float(bld); line += buildingline(bld,i); #lh = bld; lines.append(line); #for line in lines: # print(line); #printList(lines); # column merging #find indexes for merging (if there are | | next to each other) indexes = []; for i in range(len(lines[-1])-1): if (lines[-1][i]=='|' and lines[-1][i+1] == '|'): indexes.append(i-len(indexes)); #printList(indexes); #index counter for line in lines: newLine = line; for i in indexes: if newLine[i] == '|' : newLine=newLine[:i+1] + newLine[i+2:]; else : newLine = newLine[:i] + newLine[i+1:]; print(newLine); ``` Time to do some golfing! [Answer] ## PHP, ~~307~~ ~~297~~ 293 bytes ``` <?$r=str_pad("",$p=((max($argv)+1)>>1)*$w=4*$argc,str_pad("\n",$w," ",0));for(;++$i<$argc&&$r[$p++]=_;$m=$n)if($n=$argv[$i]){$q=$p+=!$m;eval($x='$r[$q-1]=$r[$q]=$r[$q+1]=_;');for($h=$n>>1;$h--;$q-=$w)$r[$q-2]=$r[$q+2]="|";$n&1?($r[$q-1]="/")&($r[$q-$w]=_)&$r[$q+1]="\\":eval($x);$p+=3;}echo$r; ``` Takes arguments\*2 from command line. save to file, run with `php <filename> <parameters>`. **breakdown** ``` // initialize result $r=str_pad("", // nested str_pad is 3 bytes shorter than a loop $p= // cursor=(max height-1)*(max width)=(start of last line) ((max($argv)+1)>>1) // max height-1 * $w=4*$argc // we need at least 4*($argc-1)-1, +1 for newline , // one line str_pad("\n",$w," ",0) // (`str_pad("",$w-1)."\n"` is one byte shorter, ); // but requires `$w+1`) // draw skyline for(; ++$i<$argc // loop through arguments &&$r[$p++]=_ // 0. draw empty ground and go one forward ; $m=$n // 7. remember value ) if($n=$argv[$i]) // if there is a house { $q= // 2. copy $p to $q $p+=!$m; // 1. go one forward if there was no house before this // offset all further positions by -2 (overwrite empty ground, share walls) eval($x= // 3. draw floor '$r[$q-1]=$r[$q]=$r[$q+1]=_;' ); for($h=$n>>1;$h--;$q-=$w) // 4. draw walls $r[$q-2]=$r[$q+2]="|"; $n&1 // 5. draw roof ?($r[$q-1]="/")&($r[$q-$w]=_)&$r[$q+1]="\\" :eval($x) // (eval saved 7 bytes) ; // (ternary saved 6 bytes over `if`) $p+=3; // 6. go three forward (5-2) } // output echo$r; ``` [Answer] # C++, ungolfed (or maybe ungolfable) Assuming there are less than 100 elements and each element is less than 100. `s` is the number of buildings (required in input). ``` #include <iostream> using namespace std; int main() { float a[100]; int i,j,s; cin>>s; for(i=0;i<s;++i) cin>>a[i]; for(i=100;i>=1;--i) { for(j=0;j<s;++j) { if((a[j]>=i)||(a[j-1]>=i)) cout<<"|"; else cout<<" "; if(i==1) cout<<"___"; else if(a[j]+1==i) cout<<"___"; else if(a[j]+1.5==i) cout<<" _ "; else if(a[j]+0.5==i) cout<<"/ \\"; else cout<<" "; } if(a[s-1]>=i) cout<<"|"; cout<<endl; } } ``` ]
[Question] [ **Input:** Two integers. Preferably decimal integers, but other forms of numbers can be used. These can be given to the code in standard input, as arguments to the program or function, or as a list. **Output:** Their sum. Use the same format for output integers as input integers. For example, the input `5 16` would lead to the output `21`. **Restrictions:** No standard loopholes please. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), answer in lowest amount of bytes wins. **Notes:** This should be fairly trivial, however I'm interested to see how it can be implemented. The answer can be a complete program or a function, but please identify which one it is. **Test cases:** ``` 1 2 -> 3 14 15 -> 29 7 9 -> 16 -1 8 -> 7 8 -9 -> -1 -8 -9 -> -17 ``` Or as CSV: ``` a,b,c 1,2,3 14,15,29 7,9,16 -1,8,7 8,-9,-1 -8,-9,-17 ``` # Leaderboard ``` var QUESTION_ID=84260,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Minecraft 1.10, 221 characters (non-competing) See, this is what we have to deal with when we make Minecraft maps. Aside: There's no way to take a string input in Minecraft, so I'm cheating a bit by making you input the numbers into the program itself. (It's somewhat justifiable because quite a few maps, like Lorgon111's Minecraft Bingo, require you to copy and paste commands into chat in order to input a number.) Thank you abrightmoore for the [Block Labels](http://www.brightmoore.net/mcedit-filters-1/blocklabels) MCEdit filter. [![a](https://i.stack.imgur.com/ucoxq.png)](https://i.stack.imgur.com/ucoxq.png) ``` scoreboard objectives add a dummy scoreboard players set m a 6 scoreboard players set n a 8 scoreboard players operation r a += m a scoreboard players operation r a += n a tellraw @a {"score":{"name":"r","objective":"a"}} ``` Non-competing due to difficulties in input, and I have no idea how to count bytes in this thing (the blytes system is flawed for command blocks). [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 1 byte ``` + ``` [Try it online!](http://jelly.tryitonline.net/#code=Kw&input=&args=NQ+MTY) Also works in 05AB1E, Actually, APL, BQN, Brachylog, Braingolf, Chocolate, ,,, (Commata), dc, Deorst, Factor, Fig\*\*, Forth, Halfwit\*, HBL\*, Implicit, J, Julia, K, kdb+, Keg, Ly, MathGolf, MATL, Pyke, Q, Racket, Scheme, Swift, Thunno\*\*, Thunno 2, and Vyxal. \* Language uses a half-byte code page, and therefore `+` counts as 0.5 bytes. \*\* In Fig and Thunno, this is \$\log\_{256}(96)\approx\$ 0.823 bytes. [Answer] # [Binary lambda calculus](https://en.wikipedia.org/wiki/Binary_lambda_calculus), 4.125 bytes Input and output as [Church numerals](https://en.wikipedia.org/wiki/Church_encoding). ``` 00000000 01011111 01100101 11101101 0 ``` In [lambda calculus](https://en.wikipedia.org/wiki/Lambda_calculus), it is λ*m*. λ*n*. λ*f*. λ*x*. *m* *f* (*n* *f* *x*). [De Bruijn index](https://en.wikipedia.org/wiki/De_Bruijn_index): λ λ λ λ 4 2 (3 2 1) --- [Lambda calculus](https://en.wikipedia.org/wiki/Lambda_calculus) is a concise way of describing a mapping (function). For example, this task can be written as λ*x*. λ*y*. *x* + *y* The thing to note is, that this is not a lambda (function) which takes two arguments. This is actually a nested lambda. However, it behaves like a lambda which takes two arguments, so it can be informally described as such. Every lambda formally only takes one argument. For example, if we apply this lambda to 3 and 4: > > (λ*x*. λ*y*. *x* + *y*) 3 4 ≡ (λ*y*. 3 + *y*) 4 ≡ 3 + 4 = 7 > > > So, the first lambda actually returns another lambda. --- [Church numerals](https://en.wikipedia.org/wiki/Church_encoding) is a way of doing away with the extra signs, leaving with only lambda symbols and variables. Each number in the Church system is actually a lambda that specifies how many times the function is applied to an item. Let the function be *f* and the item be *x*. So, the number 1 would correspond to λ*f*. λ*x*. *f* *x*, which means apply *f* to *x* exactly once. The number 3, for example, would be λ*f*. λ*x*. *f* (*f* (*f* *x*)), which means apply *f* to *x* exactly three times. --- Therefore, to add two [Church numerals](https://en.wikipedia.org/wiki/Church_encoding) (say, *m* and *n*) together, it is the same as applying *f* to *x*, *m* + *n* times. We can observe that this is the same as first applying *f* to *x*, *n* times, and then applying *f* to the resulting item *m* times. For example, *2* would mean `f(f(x))` and *3* would mean `f(f(f(x)))`, so *2* + *3* would be `f(f(f(f(f(x)))))`. To apply *f* to *x*, *n* times, we have *n* *f* *x*. You can view *m* and *n* as functions taking two arguments, informally. Then, we apply *f* again to this resulting item, *m* times: *m* *f* (*n* *f* *x*). Then, we add back the boilerplate to obtain λ*m*. λ*n*. λ*f*. λ*x*. *m* *f* (*n* *f* *x*). --- Now, we have to convert it to [De Bruijn index](https://en.wikipedia.org/wiki/De_Bruijn_index). Firstly, we count the "relative distance" between each variable to the lambda declaration. For example, the *m* would have a distance of 4, because it is declared 4 lambdas "ago". Similarly, the *n* would have a distance of 3, the *f* would have a distance of 2, and the *x* would have a distance of 1. So, we write it as this intermediate form: λ*m*. λ*n*. λ*f*. λ*x*. 4 2 (3 2 1) Then, we remove the variable declarations, leaving us with: λ λ λ λ 4 2 (3 2 1) --- Now, we convert it to [binary lambda calculus](https://en.wikipedia.org/wiki/Binary_lambda_calculus). The rules are: * λ becomes `00`. * *m* *n* (grouping) becomes `01 m n`. * numbers *i* becomes `1` *i* times + `0`, for example 4 becomes `11110`. λ λ λ λ 4 2 (3 2 1) ≡ λ λ λ λ `11110` `110` (`1110` `110` `10`) ≡ λ λ λ λ `11110` `110` `0101 111011010` ≡ λ λ λ λ `0101` `111101100101111011010` ≡ `00` `00` `00` `00` `0101` `111101100101 111011010` ≡ `000000000101111101100101111011010` [Answer] ## [Stack Cats](https://github.com/m-ender/stackcats), 8 + 4 = 12 bytes ``` ]_:]_!<X ``` Run with the `-mn` flags. [Try it online!](http://stackcats.tryitonline.net/#code=XV86XV8hPFg&input=NTcgLTE4OA&args=LW1u) Golfing in Stack Cats is *highly* counterintuitive, so this program above was found with a few days of brute forcing. For comparison, a more intuitive, human-written solution using the `*(...)>` template is two bytes longer ``` *(>-_:[:)> ``` with the `-ln` flags instead (see the bottom of this post for an explanation). ### Explanation Here's a primer on Stack Cats: * Stack Cats is a reversible esoteric language where the mirror of a snippet undoes the effect of the original snippet. Programs must also be mirror images of itself — necessarily, this means that even-length programs are either no-ops or infinite loops, and all non-trivial terminating programs are of odd length (and are essentially a conjugation of the central operator). * Since half the program is always implied, one half can be left out with the `-m` or `-l` flag. Here the `-m` flag is used, so the half program above actually expands to `]_:]_!<X>!_[:_[`. * As its name suggests, Stack Cats is stack-based, with the stacks being bottomless with zeroes (i.e. operations on an otherwise empty stack return 0). Stack Cats actually uses a tape of stacks, e.g. `<` and `>` move one stack left and one stack right respectively. * Zeroes at the bottom of the stack are swallowed/removed. * All input is pushed to an initial input stack, with the first input at the top and an extra -1 below the last input. Output is done at the end, using the contents of the current stack (with an optional -1 at the bottom being ignored). `-n` denotes numeric I/O. And here's a trace of the expanded full program, `]_:]_!<X>!_[:_[`: ``` Initial state (* denotes current stack): ... [] [-1 b a]* [] [] ... ] Move one stack right, taking the top element with you ... [] [-1 b] [a]* [] ... _ Reversible subtraction, performing [x y] -> [x x-y] (uses an implicit zero here) ... [] [-1 b] [-a]* [] ... : Swap top two ... [] [-1 b] [-a 0]* [] ... ] Move one stack right, taking the top element with you ... [] [-1 b] [-a] []* ... _ Reversible subtraction (0-0, so no-op here) ! Bit flip top element, x -> -x-1 ... [] [-1 b] [-a] [-1]* ... < Move one stack left ... [] [-1 b] [-a]* [-1] ... X Swap the stack to the left and right ... [] [-1] [-a]* [-1 b] ... > Move one stack right ... [] [-1] [-a] [-1 b]* ... ! Bit flip ... [] [-1] [-a] [-1 -b-1]* ... _ Reversible subtraction ... [] [-1] [-a] [-1 b]* ... [ Move one stack left, taking the top element with you ... [] [-1] [-a b]* [-1] ... : Swap top two ... [] [-1] [b -a]* [-1] ... _ Reversible subtraction ... [] [-1] [b a+b]* [-1] ... [ Move one stack left, taking the top element with you ... [] [-1 a+b]* [b] [-1] ... ``` `a+b` is then outputted, with the base -1 ignored. Note that the trickiest part about this solution is that the output stack must have a `-1` at the bottom, otherwise an output stack of just `[-1]` would ignore the base -1, and an output stack of `[0]` would cause the base zero to be swallowed (but an output stack of `[2]`, for example, would output `2` just fine). --- Just for fun, here's the full list of related solutions of the same length found (list might not be complete): ``` ]_:]^!<X ]_:]_!<X ]_:]!^<X ]_:!]^<X [_:[^!>X [_:[_!>X [_:[!^>X [_:![^>X ``` The `*(>-_:[:)>` solution is longer, but is more intuitive to write since it uses the `*(...)>` template. This template expands to `<(...)*(...)>` when used with the `-l` flag, which means: ``` < Move one stack left (...) Loop - enter if the top is positive and exit when the top is next positive again Since the stack to the left is initially empty, this is a no-op (top is 0) * XOR with 1 - top of stack is now 1 (...) Another loop, this time actually run > Move one stack right ``` As such, the `*(...)>` template means that the first loop is skipped but the second is executed. This allows more straightforward programming to take place, since we don't need to worry about the effects of the loop in the other half of the program. In this case, the inside of the loop is: ``` > Move one stack right, to the input stack - Negate top, [-1 b a] -> [-1 b -a] _ Reversible subtraction, [-1 b -a] -> [-1 b a+b] : Swap top two, [-1 b a+b] -> [-1 a+b b] [ Move one stack left, taking top of stack with you (removing the top b) : Swap top two, putting the 1 on this stack on top again ``` The final `>` in the template then moves us back to the input stack, where `a+b` is outputted. [Answer] ## Common Lisp, 15 bytes ``` (+(read)(read)) ``` [Answer] # [Dominoes](http://store.steampowered.com/app/286160/), 38,000 bytes or 37 tiles This is created in [*Tabletop Simulator*](http://store.steampowered.com/app/286160/). Here is a [video](https://www.youtube.com/watch?v=LYCAiD80oZU&feature=youtu.be) and here is the [file](http://steamcommunity.com/sharedfiles/filedetails/?id=883290024). It is a standard half-adder, composed of an `and` gate for the `2^1` place value and an `xor` gate for the `2^0` place value. [![enter image description here](https://i.stack.imgur.com/TUQerm.jpg)](https://www.youtube.com/watch?v=LYCAiD80oZU&feature=youtu.be) ## Details * **I/O** + **Start** - This is included for clarity (not counted towards total) and is what 'calls' or 'executes' the function. Should be 'pressed' after input is given **[Yellow]**. + **Input A** - This is included for clarity (not counted towards total) and is 'pressed' to indicated a `1` and unpressed for `0` **[Green]**. + **Input B** - This is included for clarity (not counted towards total) and is 'pressed' to indicated a `1` and unpressed for `0` **[Blue]**. + **Output** - This is counted towards total. These dominoes declare the sum. The left is `2^1` and the right is `2^0` **[Black]**. * **Pressing** + To give input or start the chain, spawn the metal marble + Set the lift strength to `100%` + Lift the marble above the desired domino + Drop the marble [Answer] # [Brain-flak](http://github.com/DJMcMayhem/Brain-Flak), 6 bytes ``` ({}{}) ``` [Try it online!](http://brain-flak.tryitonline.net/#code=KHt9e30p&input=MyA1) Brain-flak is a really interesting language with two major restrictions on it. 1. The only valid characters are brackets, i.e. any of these characters: ``` (){}[]<> ``` 2. Every single set of brackets must be entirely matched, otherwise the program is invalid. A set of brackets with nothing between them is called a "nilad". A nilad creates a certain numerical value, and all of these nilads next to each other are added up. A set of brackets with something between them is called a "monad". A monad is a function that takes an numerical argument. So the brackets inside a monad are evaluated, and that is the argument to the monad. Here is a more concrete example. The `()` *nilad* equals 1. So the following brain-flak code: ``` ()()() ``` Is evaluated to 3. The `()` *monad* pushes the value inside of it on the global stack. So the following ``` (()()()) ``` pushes a 3. The `{}` nilad pops the value on top of the stack. Since consecutive nilads are always added, a string of `{}` sums all of the top elements on the stack. So my code is essentially: ``` push(pop() + pop()) ``` [Answer] # Minecraft 1.10.x, ~~924~~ 512 bytes Thanks to @[quat](https://codegolf.stackexchange.com/users/34793/quat) for reducing the blytecount by 48 points and the bytecount by 412. Alright, so, I took some of the ideas from [this answer](https://codegolf.stackexchange.com/a/84342/44713) and made a version of my own, except that this one is capable of accepting non-negative input. A version may be found [here](https://www.dropbox.com/s/6v20ca187bjdpw5/Input%20Ready.nbt?dl=1) in structure block format. [![group](https://i.stack.imgur.com/tUA1C.png)](https://i.stack.imgur.com/tUA1C.png) (new version looks kinda boring tbh) Similar commands as the other answer: ``` scoreboard objectives add a dummy execute @e[type=Pig] ~ ~ ~ scoreboard players add m a 1 execute @e[type=Cow] ~ ~ ~ scoreboard players add n a 1 scoreboard players operation n a += m a tellraw @a {"score":{"name":"n","objective":"a"}} ``` To input numbers, spawn in a number of cows and pigs. Cows will represent value "n" and pigs will represent value "m". The command block system will progressively kill the cows and pigs and assign values as necessary. This answer assumes that you are in a world with no naturally occurring cows or pigs and that the values stored in "n" and "m" are cleared on each run. [Answer] ## [Retina](https://github.com/m-ender/retina), 42 bytes ``` \d+ $* T`1p`-_` |-1+ +`.\b. ^(-)?.* $1$.& ``` [Try it online!](http://retina.tryitonline.net/#code=XGQrCiQqClRgMXBgLV9gIHwtMSsKK2AuXGIuCgpeKC0pPy4qCiQxJC4m&input=LTUgMTY) ### Explanation Adding numbers in unary is the easiest thing in the world, but once you introduce negative numbers, things get fiddly... ``` \d+ $* ``` We start by converting the numbers to unary. This is done by matching each number with `\d+` and replacing it with `$*`. This is a Retina-specific substitution feature. The full syntax is `count$*character` and inserts `count` copies of `character`. Both of those can be omitted where `count` defaults to `$&` (i.e. the match itself) and `character` defaults to `1`. So for each input `n` we get `n` ones, and we still have potential minus signs in there, as well as the space separator. E.g. input `8 -5` gives: ``` 11111111 -11111 ``` Now in order to deal with negative numbers it's easiest to use a separate `-1` digit. We'll use `-` for that purpose. ``` T`1p`-_` |-1+ ``` This stage does two things. It gets rid of the space, the leading minus signs, and turns the `1`s after a minus sign into `-` themselves. This is done by matching `|-1+` (i.e. either a space or a negative number) and performing a transliteration on it. The transliteration goes from `1p` to `-_`, but here, `p` expands to all printable ASCII characters and `_` means delete. So `1`s in those matches get turned into `-`s and minuses and spaces get removed. Our example now looks like this: ``` 11111111----- ``` ``` +`.\b. ``` This stage handles the case where there's one positive and one negative number in the input. If so, there will be `1`s and `-`s in the string and we want them to cancel. This is done by matching two characters with a word-boundary between them (since `1`s is considered a word character and `-` isn't), and replacing the match with nothing. The `+` instructs Retina to do this repeatedly until the string stops changing. Now we're left with *only* `1`s or *only* `-`s. ``` ^(-)?.* $1$.& ``` To convert this back to decimal, we match the entire input, but if possible we capture a `-` into group `1`. We write back group `1` (to prepend a `-` to negative numbers) and then we write back the length of the match with `$.&` (also a Retina-specific substitution feature). [Answer] # Geometry Dash - 15 objects Finally done. 15 objects aren't much, but it was still a nightmare to do this (especially because of the negative numbers). [![enter image description here](https://i.stack.imgur.com/ci97N.png)](https://i.stack.imgur.com/ci97N.png) Because I would have to insert 15 images here for how to reproduce this, I just uploaded the level. The level ID is 5216804. The description tells you how to run it and you can copy it since it is copyable. **Explanation:** The top-left trigger (Instant Count 2) checked if the first addend was 0. If it was, it then checked if the second addend was positive or negative. If it was positive, it transferred the value from the second addend to the sum (BF-style, using loops) and if it was negative, it would do the same thing. The reason why we need to check if the second addend is positive or negative is that we would need to subtract one from the second addend and add one to the sum or add one to the second addend and subtract one from the sum respectively. If the first addend is not zero, it tests whether it is positive or negative using the process above. After one iteration in the while loop, it tests to see if the first addend is zero and if it is, it does the process described at the beginning of the explanation. Since Geometry Dash is remarkably similar to BF, you could make a BF solution out of this. [Answer] # APOL, 6 bytes ``` +(i i) ``` I AM BOT FEED ME BUTTER [Answer] # Mathematica, ~~4~~ 2 bytes ``` Tr ``` *Crossed out ~~4~~ is still regular 4...* `Tr` applied to a one-dimensional list takes the sum of said list's elements. [Answer] # JavaScript (ES6), 9 bytes ``` a=>b=>a+b ``` [Answer] # Haskell, 3 bytes ``` (+) ``` The parentheses are here because it needs to be an prefix function. This is the same as taking a section of the + function, but no arguments are applied. It also works on a wide range of types, such as properly implemented Vectors, Matricies, Complex numbers, Floats, Doubles, Rationals, and of course Integers. Because this is Haskell, here is how to do it on the type-level. This will be done at compile time instead of run time: ``` -- This *type* represents Zero data Zero -- This *type* represents any other number by saying what number it is a successor to. -- For example: One is (Succ Zero) and Two is (Succ (Succ Zero)) data Succ a -- a + b = c, if you have a and b, you can find c, and if you have a and c you can find b (This gives subtraction automatically!) class Add a b c | a b -> c, a c -> b -- 0 + n = n instance Add Zero n n -- If (a + b = c) then ((a + 1) + b = (c + 1)) instance (Add a b c) => Add (Succ a) b (Succ c) ``` Code adapted from [Haskell Wiki](https://wiki.haskell.org/Type_arithmetic) [Answer] # [Shakespeare Programming Language](http://esolangs.org/wiki/Shakespeare), ~~155~~ 152 bytes ``` . Ajax,. Ford,. Act I:. Scene I:. [Enter Ajax and Ford] Ajax: Listen to thy heart Ford: Listen to THY heart!You is sum you and I.Open thy heart [Exeunt] ``` Ungolfed: ``` Summing Two Numbers in Verona. Romeo, a numerical man. Juliet, his lover and numerical counterpart. Act I: In which Italian addition is performed. Scene I: In which our two young lovers have a short chat. [Enter Romeo and Juliet] Romeo: Listen to thy heart. Juliet: Listen to THY heart! Thou art the sum of thyself and I. Open thy heart. [Exeunt] ``` I'm using [drsam94's SPL compiler](https://github.com/drsam94/Spl) to compile this. To test: ``` $ python splc.py sum.spl > sum.c $ gcc sum.c -o sum.exe $ echo -e "5\n16" | ./sum 21 ``` [Answer] # dc, 2 bytes ``` +f ``` Adds top two items on stack (previously taken from `stdin`), then dumps the stack's contents to `stdout`. **EDIT:** Upon further consideration, it seems there are several ways this might be implemented, depending on the desired I/O behaviour. ``` + # adds top two items and pushes on stack +n # adds top two and prints it, no newline, popping it from stack +dn # ditto, except leaves result on stack ??+ # takes two inputs from stdin before adding, leaving sum on stack ``` I suppose the most complete form for the sum would be this: ``` ??+p # takes two inputs, adds, 'peeks' # (prints top value with newline and leaves result on stack) ``` Wait! Two numbers can be taken on the same line, separated by a space! This gives us: ``` ?+p ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes ``` +. ``` Expects a list with the two numbers as input Alternatively, if you want the answer to `STDOUT`: ``` +w ``` [Answer] # Python, ~~11~~ 3 bytes ``` sum ``` --- ~~`int.__add__`~~ A simple special operator. [Answer] # [Plumber](https://github.com/Radvylf/plumber), ~~244~~ 176 bytes ``` [] [] [] ][=][] []=][][=][ []=]===]] ][]][=[=]] =]] []][ ][===[=[] ]][]=][[[=]=]][][ []]=]=]=]=[] ][]=[]][ []]=][=][] = =]=]][[=[== ][=]=]=]=]===][= ``` ## Old Design (244 bytes) ``` [] [] [][=[] [[=[][] [][] ][]][= ][[] ][[=]]]][]=[[] []===][] ][===][] ][][ [] ][ ] [][] [ ][]=][[[===][[ ][]]]=][[]=[=]=]=]]==]=]][ ][=]=]]==]=][] ][ [][=][=[[][[=]][ ==]=]][[=[= = ``` I thought I had a good solution for a while...except it didn't work with `0` or `1` as the first input. This program consists of three parts: incrementer, decrementer, and outputter. The decrementer is on the left, and holds the first value. It is incremented, since a `0` would cause an infinite loop (as the program tries to decrement to `0` and gets a negative value). It will decrement the stored value at execution, and send a packet to the incrementer. The incrementer is on the right, and stores the second input. When the decrementer sends a packet, it increments its stored value, and sends a packet back to the decrementer. Whenever the decrementer sends the packet to the incrementer, it is checked by the outputter. If the packet is `0`, execution stops and the value of the incrementer is read and outputted. It uses a NOT gate, one of the most complicated parts of the program. ## Older design (doesn't work with some inputs), 233 bytes ``` [] [] [][] [][] =][] []=][]=][[=]][ [][===][ [][===[] [][] [ [] ][][ ] [===][=]][ ] ][[=[=[=[=[=]=[]][=[[[][ ][[=[=[=[==[[=[=][ []]=][=][] = =]=]][[=[== ``` The new one is flipped to save bytes, and it's really confusing me. This design is the one I worked with for a week or so when designing the interpreter. [Answer] # Cheddar, 3 bytes ``` (+) ``` This is a cool feature of Cheddar called "functionized operators". Credit for this idea goes to @CᴏɴᴏʀO'Bʀɪᴇɴ. Here are more examples of functionized operators: ``` (+)(1,2) // 3 (/)(6,2) // 3 (-)(5) // -5 ``` [Answer] # MATL, 1 byte ``` s ``` Accepts an array of two integers as input and sums them. While the simple program of `+` also works, that has already been shown for other languages. [**Try it Online**](http://matl.tryitonline.net/#code=cw&input=WzIgNF0) [Answer] # PHP, 20 bytes Surprisingly short this time: ``` <?=array_sum($argv); ``` Runs from command line, like: ``` $ php sum.php 1 2 ``` [Answer] # [Fuzzy Octo Guacamole](https://github.com/RikerW/Fuzzy-Octo-Guacamole), 1 byte ``` a ``` A function that takes inputs from the top of the stack and outputs by pushing to the stack. Example running in the REPL: ``` >>> 8 9 : [8,9] >>> a : 17 ``` [Answer] # C, 35 bytes ``` s(x,y){return y?s(x^y,(x&y)<<1):x;} ``` What I've done here is defined addition without the use of boolean or arithmetic operators. This recursively makes x the sum bits by 'xor', and y the carry bits by 'and' until there is no carry. Here's the ungolfed version: ``` int sum(int x,int y){ if(y==0){ //anything plus 0 is itself return x; } //if it makes you happier imagine there's an else here int sumBits=x^y; int carryBits=(x&y)<<1; return sum(sumBits,carryBits); } ``` [Answer] # x86\_32 machine code, 2 bytes ``` 08048540 <add7>: 8048540: 01 c8 add %ecx,%eax ``` Assuming the two values are already in the ecx and eax registers, performing the add instruction will add the values of the two registers and store the result in the destination register. You can see the full program written in C and inline assembly [here](https://gcc.godbolt.org/z/WdGbEP7x4). Writing the wrapper in C makes it easier to provide inputs and do testing, but the actual add function can be reduced down to these two bytes. [Answer] ## Perl 5.10, 8 bytes The two numbers to add must be on 2 separate lines for this one to work: ``` say<>+<> ``` [Try this one here.](https://ideone.com/PTznrK) One with input on the same line (**14 + 1 bytes for *-a* flag**) ``` say$F[0]+$F[1] ``` [Try it here!](https://ideone.com/6PZ9NR) One with input on the same line (**19 + 1 bytes for *-a* flag**) ``` map{$s+=$_}@F;say$s ``` [Try this one here.](https://ideone.com/ykfi5N) Another one, by changing the array default separator (**19 + 1 bytes for *-a* flag** as well) ``` $"="+";say eval"@F" ``` [Try this one here!](https://ideone.com/arDZIJ) [Answer] ## Batch, ~~25~~ ~~18~~ 16 bytes ``` @cmd/cset/a%1+%2 ``` Edit: saved ~~7~~ 9 bytes by using my trick from [Alternating Sign Sequence](https://codegolf.stackexchange.com/questions/80858/alternating-sign-sequence/80868#80868). [Answer] ## PowerShell v2+, 17 bytes ``` $args-join'+'|iex ``` Takes input as two separate command-line arguments, which get pre-populated into the special array `$args`. We form a string with the `-join` operator by concatenating them together with a `+` in the middle, then pipe that string to `Invoke-Expression` (similar to `eval`). --- Thanks to @DarthTwon for reminding me that when dealing with such minimal programs, there are multiple methods of taking input all at the same byte-count. ``` $args[0]+$args[1] param($a,$b)$a+$b ``` PowerShell is nothing if not flexible. [Answer] ## [><>](https://esolangs.org/wiki/fish), ~~7~~ ~~6~~ 3 bytes ``` +n; ``` [Online interpreter](https://fishlanguage.com/playground) Or try it on TIO with the -v flag. [Try it online](http://fish.tryitonline.net/#code=K247&input=&args=LXYgMTU+LXYgMjU) [Answer] # [Alchemist](https://esolangs.org/wiki/Alchemist), ~~253 211~~ 205 bytes ``` _->u+v+2r u+r->In_a+In_x v+r->In_b+In_y a+b->Out_"-" 0_+0r+0d+0a+0b->d 0d+0a+x+b+y->b 0r+0d+a+0b+0y->d+Out_"-" 0r+0d+0b+a+0x->d a+x+0b+y->a 0r+0d+0a+b+0x->d+Out_"-" 0r+0d+0a+b+0y->d d+x->d+y d+y->d+Out_"1" ``` Since Alchemist can't handle negative numbers (there can't be a negative amount of atoms) this takes 4 inputs on *stdin* in this order: * sign of `x` (0 -> `+` and 1 -> `-`) * the number `x` itself * sign of `y` (0 -> `+` and 1 -> `-`) * the number `y` itself Output is in unary, [try it online!](https://tio.run/##XYyxDgIhEET7/QzaCcl69vRWfgJhxUQTtcDjAl@PLJgzsdnMzsub8Ljcrs/7e23NW5exYUmUkaw7vXxAP4W27yv6VgoQ68559cYaYg9O4AgO4N5HmrlAUK0TmlQhuBcRuzk1UVZUVImHFWjflAn/rQF0jiIGrz385g@mNaaFmI4f "Alchemist – Try It Online") (for your convenience, [here](https://tio.run/##bVHBitswFLzrKwatKRuEKjulh1LWS9tD2UsL3eOmGNlWYoEjB0n2Jmz3213JDvG25CKe3mjmzeiV0jXjWEmPHLKutdedeV9ZQ8gNvnVmUNbD9PtSWfgO9PHh@4@N@fL1cWMo8V0h26pRe@18oc2h97hd4YUAsnR3NLlVVdMhyfAHTtVwgguxogH2ynlQijtcefSU8k@/hditKIAbJPfQDhn0FkbtpNeD@owUqnUqKE1kmtxvTBJmRlOv0fmv3uBiDc/aN/CNQtVZqyqPyavDu9CYE3a9j@63ttujN9KeYthaVXovW7IIndPN9Bjwyg8k2ep6fz1Fn9Qj9WC18dvgfVajIb/oDl5ceEv1z2KwzkWtBmH6tp0Und6ZIPgyKQuRvdJ5AUXw/2YQ50jmaG@2EernCrwKQoG0vKRhHyxYBs@RxAHJWfD8w4u18DBZj2PB854NbG1JzyzPH0whWTiOZDhfy3g9EclKnv/sfUE5JWnBUsvSmqWSpaFfk7k@spKdeF6SGY0gS0OjZhfmTCsjdozESEonliQXzXIG/2dNQJQjNZvwUygW@YyO/OP44S8 "Bash – Try It Online") is a wrapper, converting inputs and returning decimal outputs) ## Explanation & ungolfed Since Alchemist applies the rules non-deterministically we need a lot of *0-rules*.. Initially there is only one `_` atom, so we use that to read the inputs: ``` _->u+v+2r u+r->In_a+In_x v+r->In_b+In_y ``` The following rules can't be applied because they all require `0r`, now we have `a`, `b` as the signs of `x` and `y` respectively. ``` # Case -x -y: we output the sign and remove a,b # therefore we will handle them the same as +x +y 0_+0r+0d+a+b->Out_"-" #: 0_+0r+0d ⇐ a+b # Case +x +y: doesn't need anything done 0_+0r+0d+0a+0b->d # Case +x -y: ## remove one atom each 0_+0r+0d+0a+x+b+y->b #: 0_+0r ⇐ x+b ## if we had |y| > x: output sign and be done 0_+0r+0d+a+0b+0y->d+Out_"-" #: 0_ ⇐ 0r+a ## else: be done 0_+0r+0d+0b+a+0x->d #: 0_ ⇐ 0r+a # Case -x +y is symmetric to the +x -y case: 0_+0r+0d+a+x+0b+y->a #: 0_+0r+0d ⇐ a+y 0_+0r+0d+0a+b+0x->d+Out_"-" #: 0_ ⇐ 0r+b 0_+0r+0d+0a+b+0y->d #: 0_ ⇐ 0r+b # All computations are done and we can output in unary: 0_+d+x->d+Out_"1" #: 0_ ⇐ d 0_+d+y->d+Out_"1" #: 0_ ⇐ d ``` To the right of some rules I marked some golfs with `#: y ⇐ x` which should read as: "The conditions `x` imply `y` at this stage and thus we can remove it without changing the determinism" ]
[Question] [ ### The challenge The shortest code by character count to help Robot find kitten in the fewest steps possible. Golfers, this is a time of crisis - Kitten gone missing and it's Robot's job to find it! Robot needs to reach Kitten in the shortest path possible. However, there are a lot of obstacles in Robot's way, and he needs you to program a solution for him. Robot used to have a program do it for him, but that program was lost and Robot have no backup :(. Robot's runtime is not the best, and the least characters Robot has to read from the source code, the least time it will spend processing, and that means Kitten will be found faster! Robot's memory contains a map of the location he is currently in with the top representing North, bottom representing South, right representing East and left representing West. Robot is always in a rectangular room of an unknown size surrounded by walls, represented by `#` in his radar map. Areas Robot can walk in are represented by a space . Robot's radar also scans for many obstacles in the room and marks them in various ASCII letters. Robot cannot walk across those obstacles. The radar will mark Kitten as the special ASCII character `K`, while Robot's location is marked with `R`. Robot's navigation system works this way: He can understand a duo of direction and number of movement units he should travel to - for example, `N 3` means 'go north 3 movement units'. Robot's radar map is made such that a movement unit is one ASCII character. Robot can only go in 4 directions and cannot travel diagonally. Your task, brave Kitten saver, is to read Robot's radar map once, and output the least amount of directions, with the least movement unit travel distance. Robot is guaranteed to have at least one path to Kitten. To ensure Robot does not waste time executing a malfunctioning program that will not help Robot find Kitten, I encourage you, brave Kitten saver, to use this output of Robot's past program to ensure no time is wasted on finding Kitten! ## Test cases ``` Input: ###################### # d 3 Kj # # # # R # # q # ###################### Output: E 13 N 2 ``` --- ``` Input: ###################### # d r 3 Kj # # p p # # T X # # q s t # # # # R o d W # # # # g t U # # # ###################### Output: N 1 E 10 N 4 E 2 ``` --- ``` Input: ###################### # spdfmsdlwe9mw WEK3# # we hi # # rdf fsszr# # sdfg gjkti # # fc d g i # # dfg sdd # # g zfg # # df df # # xcf R# ###################### Output: N 1 W 9 N 5 E 4 N 1 E 4 N 1 ``` Code count includes input/output (i.e full program). [Answer] ### C++ 1002 899 799chars Note requires the use of C++0x to eliminate the space between > > in templates. It does find the route with the minimum number of turns. ``` #include<iostream> #include<vector> #include<string> #include<set> #include<memory> #define D make_pair #define F first #define S second using namespace std;typedef pair<int,int>L;typedef vector<L>R;typedef multiset<pair<float,pair<L,R>>>B;vector<string> M;string l;int z,c,r=0;set<L> s;B b;L n;B::iterator f;R v;void A(int x,int y,int w){n=f->S.F;for(c=1;(z=M[n.S+=y][n.F+=x])==32||(z==75);++c)v.back()=D(w,c),b.insert(D(f->F+c+1./c,D(n,v)));}int main(){for(;getline(cin,l);++r){if((c=l.find(82))!=string::npos)b.insert(D(0,D(D(c,r),R())));M.push_back(l);}while(!b.empty()){f=b.begin();n=f->S.F;v=f->S.S;if(M[n.S][n.F]==75)break;if(s.find(n)==s.end()){s.insert(n);v.push_back(L());A(0,1,83);A(0,-1,78);A(1,0,69);A(-1,0,87);}b.erase(f);}for(c=v.size(),r=0;r<c;++r)n=v[r],printf("%c %d\n",n.F,n.S);} ``` It `Dijkstra's Algorithm` for solving the shortest path problem. To distinguish between multiple equal size routes a long straight line has less weight that multiple short lines (this favors routes with less turns). ``` Cost of a path: Len + 1/Len Looking at Test Case 1: ======================== Thus Path E13 + N2 has a cost of 13 + 1/13 + 2 + 1/2 An alternative path E9 + N2 + E4 has a cost of 9 + 1/9 + 2 + 1/2 + 4 + 1/4 The difference is Straight Path: 1/13 < Bendy Path: (1/9 + 1/4) ``` In a more readable form: ``` #include<iostream> #include<vector> #include<string> #include<set> #include<memory> using namespace std; typedef pair<int,int> L; typedef vector<L> R; typedef multiset<pair<float,pair<L,R>>> B; vector<string> M; string l; int z,c,r=0; set<L> s; B b; L n; B::iterator f; R v; void A(int x,int y,int w) { n=f->second.first; for(c=1;(z=M[n.second+=y][n.first+=x])==32||(z==75);++c) v.back()=make_pair(w,c), b.insert(make_pair(f->first+c+1./c,make_pair(n,v))); } int main() { for(;getline(cin,l);++r) { if((c=l.find(82))!=string::npos) b.insert(make_pair(0,make_pair(make_pair(c,r),R()))); M.push_back(l); } while(!b.empty()) { f=b.begin(); n=f->second.first; v=f->second.second; if(M[n.second][n.first]==75) break; if(s.find(n)==s.end()) { s.insert(n); v.push_back(L()); A(0,1,83); A(0,-1,78); A(1,0,69); A(-1,0,87); } b.erase(f); } for(c=v.size(),r=0;r<c;++r) n=v[r], printf("%c %d\n",n.first,n.second); } ``` [Answer] ## Scala 2.8 (451 characters) ...but it doesn't solve ties in favor of least amount of directions (though it does find the least amount of steps). ``` val m=io.Source.stdin.getLines.map(_.toArray).toSeq var l=m.indexWhere(_ contains'R') var c=m(l)indexOf'R' val q=collection.mutable.Queue(l->c->"") def s{val((l,c),p)=q.dequeue if("R "contains m(l)(c))for((i,j,k)<-Seq((-1,0,"N"),(0,1,"E"),(1,0,"S"),(0,-1,"W")))q.enqueue(((l+i,c+j),p+k)) m(l)(c)='X'} def P(s:String){if(s.nonEmpty){val (h,t)=s.span(s.head==) println(s.head+" "+h.size) P(t)}} def Q{s val((l,c),p)=q.head if (m(l)(c)=='K')P(p)else Q} Q ``` Scala 2.8, 642 characters, solves ties correctly; ``` val m=io.Source.stdin.getLines.toSeq var b=Map(0->0->0).withDefault(_=>Int.MaxValue) var l=m.indexWhere(_ contains'R') var c=m(l)indexOf'R' val q=collection.mutable.PriorityQueue(l->c->List((' ',0)))(Ordering.by(t=>(-t._2.map(_._2).sum,-t._2.size))) def s{val(p@(l,c),u@(h@(d,n))::t)=q.dequeue if("R ".contains(m(l)(c))&&u.map(_._2).sum<=b(p)){b=b.updated(p,u.map(_._2).sum) for((i,j,k)<-Seq((-1,0,'N'),(0,1,'E'),(1,0,'S'),(0,-1,'W'))){ val o=if(k==d)(d,n+1)::t else (k,1)::h::t q.enqueue(((l+i,c+j),o))}}} def P(l:List[(Char,Int)]){l.reverse.tail.foreach{t=>println(t._1+" "+t._2)}} def Q{s;val((l,c),p)=q.head;if (m(l)(c)=='K')P(p)else Q} Q ``` It discovered a shorter path for the second example than the one given in the problem: ``` N 1 E 10 N 4 E 2 ``` [Answer] ## Python 2.6 (504 characters) ``` import sys,itertools W,Q=len,list M=[] B=[] for l in sys.stdin.readlines(): r=Q(l.strip()) B.append([0]*W(r)) M.append(r) if "R" in r:x,y=r.index("R"),W(B)-1 def S(B,M,x,y,P): c=M[y][x] b=B[y][x] if b and W(P)>b:return 0 B[y][x]=W(P) if c=="K":return P elif c=="R" and P:return 0 if c in "R ": b=[] for q,w,s in((1,0,"E"),(-1,0,"W"),(0,-1,"N"),(0,1,"S")): r=S(B,M,x+q,y+w,P+s) if r and(W(r)<W(b)or not b):b=r if b:return b return 0 print "\n".join(k+str(W(Q(g)))for k,g in itertools.groupby(S(B,M,x,y,""))) ``` [Answer] ## Python 2.6 (535 characters) ``` exec 'eJzNlLFugzAQhneewhki2/KBworksVOkDu3QgVqVE2hBioFgCDhV371nJ1VbKR3SKYtl/jvs77MwtenafiBVqbs9WGcjLW05MB69tj05QEfqhpTNaMpeDyXDhsQORd3wLCK+YwT7u6PzFVK/Ep9Tsn6gmU50UTA2woHzc01KuqYZ20PPZSh85/iCO2etzBnTG8tcvlLxnovTPFVxzyGEC4lpiBay5xiuYMXBcRVtzxqTfP+IpqrelaRFsheoYJbBNvFj13asxd23gXHGmZU7bTaFDgiZH+MUYydtKBuZRuS0nvPmOt564Sl3CmlxcWAG6D3lXIkpeUMGB7nyfj82HW3FWvjTTVSYCXNJEUupEimannu+nl04WyM8XoB1F13E9S6Pt+ki0vDZXOdyd5su8X9cnm7DBa/tLGW4yh7yKCn1rIF+9vSTj/HiBeqCS1M3bMrnwOvbl5Ysi+eGLlkBhosjxl1fNwM5Ak7xH6CiT3SdT4U='.decode('base64').decode('zlib') ``` Unpacks to a severely mistreated A\* implementation. Reads stdin. Searches for solutions with minimal total distance. Breaks ties by preferring minimal number of directions. Lists moves to stdout. Finds kittens. **Unpacked**: The source has been manually anti-golfed in a few places in order to obtain a smaller compressed representation. For example, a for loop over the compass directions was unrolled. ``` import heapq,sys a=set() for v,p in enumerate(sys.stdin): for u,s in enumerate(p): if s in' KR':a.add((u,v)) if s=='K':(q,r)=(u,v) if s=='R':y=(u,v) o=[((abs(y[0]-q)+abs(y[1]-r),(y[0]!=q)+(y[1]!=r)),(0,0),y)] c=set() w={} while o: _,h,x=heapq.heappop(o) c.add(x) s=lambda(u,v):(u,v-1) y=s(x) m=1 while y in a-c: w[y]=[(h,x,(m,'N'))]+w.get(y,[]) heapq.heappush(o,((abs(y[0]-q)+abs(y[1]-r)+h[0]+m,(y[0]!=q)+(y[1]!=r)+h[1]+1),(h[0]+m,h[1]+1),y)) m+=1 y=s(y) s=lambda(u,v):(u,v+1) y=s(x) m=1 while y in a-c: w[y]=[(h,x,(m,'S'))]+w.get(y,[]) heapq.heappush(o,((abs(y[0]-q)+abs(y[1]-r)+h[0]+m,(y[0]!=q)+(y[1]!=r)+h[1]+1),(h[0]+m,h[1]+1),y)) m+=1 y=s(y) s=lambda(u,v):(u+1,v) y=s(x) m=1 while y in a-c: w[y]=[(h,x,(m,'E'))]+w.get(y,[]) heapq.heappush(o,((abs(y[0]-q)+abs(y[1]-r)+h[0]+m,(y[0]!=q)+(y[1]!=r)+h[1]+1),(h[0]+m,h[1]+1),y)) m+=1 y=s(y) s=lambda(u,v):(u-1,v) y=s(x) m=1 while y in a-c: w[y]=[(h,x,(m,'W'))]+w.get(y,[]) heapq.heappush(o,((abs(y[0]-q)+abs(y[1]-r)+h[0]+m,(y[0]!=q)+(y[1]!=r)+h[1]+1),(h[0]+m,h[1]+1),y)) m+=1 y=s(y) if x==(q,r): z='' while x in w: _,x,(m,d)=min(w[x]) z='%s %d\n'%(d,m)+z print z, o=[] ``` [Answer] ## c++ -- 681 necessary characters ``` #include <string> #include <iostream> #include <sstream> using namespace std; int d[]={-1,0,1,0},i,j,k,l,L=0,p=41,S;string I,m,D("ESWN"); int r(int o,int s){S=s;while((m[o]==32||m[o]==37)&&m[o+S]-35) if(m[o+S]-p)S+=s;else return o+S;return 0;} void w(int o){for(i=0;i<m.length();++i)for(j=0;j<4;++j) if(k=r(o,d[j])){stringstream O;O<<D[j]<<" "<<int((k-o)/d[j])<<"\n"<<I; I=O.str();if(p-41)--p,m[k]=37,w(k);cout<<I;exit(0);}} int main(){while(getline(cin,I))m+=I,l=I.length(); d[1]-=d[3]=l;I="";for(i=0;i<m.length();++i) switch(m[i]){case 82:case 75:m[i]/=2;case 32:break;default:m[i]=35;} do{for(i=0;i<m.length();++i)if(r(i,-1)+r(i,-l)+r(i,1)+r(i,l)) {if(m[i]==37)w(i);m[i]=p+1;}}while(++p);} ``` It first replaces all the obstacles on the map with into `#`s (and changes the values of `K` and `R`, to leave headroom in the character space for very long paths. *Then it scribbles on the map.* An iterative process marks all the successively accessible squares until it is able to reach the kitten in one move. After that is uses the *same* accessibility checking routine to find a string of positions that lead back to the start in minimal instructions. These instructions are loaded into a string by pre-pending, so that they print in the proper order. I don't intend to golf it further as it does not properly resolve ties and can not be easily adapted to do so. It fails on ``` ##### # # # # # #R#K# # # ##### ``` producing ``` $ ./a.out < kitten_4.txt N 2 E 2 S 2 ``` **More or less readable version:** ``` #include <string> #include <iostream> #include <sstream> using namespace std; int d[]={-1,0,1,0} , i, j, k , l /* length of a line on input */ , L=0 /* length of the whole map */ , p=41 /* previous count ( starts 'R'/2 ) */ , S /* step accumulator for step function */ ; string I/*nput line, later the instructions*/ , m/*ap*/ , D("ESWN"); /* Reversed sence for back tracking the path */ int r/*eachable?*/(int o/*ffset*/, int s/*step*/){ // cerr << "\tReachable?" // << endl // << "\t\tOffset: " << o << " (" << o/5 << ", " << o%5 << ")" // << " [" << m[o] << "]" << endl // << "\t\tStep: " << s // << endl // << "\t\tSeeking: " << "[" << char(p) << "]" // << endl // << "\t\tWall: " << "[" << char(35) << "]" // << endl; S=s; while ( ( (m[o]==32) /* Current character is a space */ || (m[o]==37) ) /* Current character is a kitten */ && (m[o+S]-35) /* Target character is not a wall */ ) { // cerr << "\t\tTry: " << o+S << "(" << (o+S)/5 << ", " << (o+S)%5 << ")" // << " [" << m[o+S] << "]" << endl; if (m[o+S]-p /* Target character is not the previous count */ ) { // cerr << "\t\twrong " << " [" << m[o+S] << "] !!!" << endl; S+=s; } else { /* Target character *is* the previous count */ // cerr << "\t\tFound " << " [" << m[o+S] << "] !!!" << endl; return o+S; } /* while ends */ } return 0; } void w/*on*/(int o/*ffset*/){ // cerr << "\tWON" << endl // << "\t\tOffset: " << o << "(" << o/5 << ", " << o%5 << ")" // << " [" << m[o] << "]" // << endl // << "\t\tSeeking: " << "[" << char(p) << "]" // << endl; for(i=0;i<m.length();++i) /* On all map squares */ for(j=0;j<4;++j) if (k=r(o,d[j])) { // cerr << "found path segment..." // << (k-o)/d[j] << " in the " << d[j] << " direction." << endl; stringstream O; O << D[j] << " " << int((k-o)/d[j]) << "\n" << I; I = O.str(); // cerr << I << endl; /* test for final solution */ if (p-41) --p,m[k]=37, w(k); /* recur for further steps */ cout << I; exit(0); } /* inner for ends */ /* outer for ends */ } int main(){ while(getline(cin,I)) m+=I,l=I.length(); // cerr << "Read the map: '" << m << "'." << endl; d[1]-=d[3]=l;I=""; // cerr << "Direction array: " << D << endl; // cerr << "Displacement array: " << d[0] << d[1] << d[2] << d[3] << endl; // cerr << "Line length: " << l << endl; /* Rewrite the map so that all obstacles are '#' and the start and goal are '%' and ')' respectively. Now I can do pathfinding *on* the map. */ for(i=0;i<m.length();++i) switch (m[i]) { case 82: /* ASCII 82 == 'R' (41 == ')' ) */ case 75:m[i]/=2; /* ASCII 75 == 'K' (37 == '%' ) */ case ' ':break; default: m[i]=35; /* ASCII 35 == '#' */ }; // cerr << "Re-wrote the map: '" << m << "'." << endl; do { /* For each needed count */ // cerr << "Starting to mark up for step count " // << p-41+1 << " '" << char(p) << "'" << endl; for(i=0;i<m.length();++i){ /* On all map squares */ // cerr << "\tTrying position (" << i/l << ", " << i%l << ")" // << " [" << m[i] << "]" // << endl; if ( r(i, -1) /* west */ + r(i, -l) /* north */ + r(i, 1) /* east */ + r(i, l) /* south */ ) { // cerr << "Got a hit on : '" << m << "'." << endl; // cerr << "\twith '" << char(m[i]) <<" at position " << i << endl; // cerr << "target is " << char(37) << endl; if(m[i]==37) w(i); /* jump into the win routine which never returns */ m[i]=p+1; // cerr << "Marked on map: '" << m << "'." << endl; } } } while(++p); } ``` [Answer] ## Ruby - 539 characters Could do with a lot of improvement, but it does work for shortest steps as well as directions. ``` M=[*$<] r=M.map{|q|q.index('R')||0} k=M.map{|q|q.index('K')||0} D=M.map{|q|q.split('').map{[99,[]]}} def c h h.map{|i|i.inject([[]]){|a,b|a.last[0]!=b ? a<<[b, 1]:a.last[1]+=1;a}}.sort_by{|a|a.length}[0] end def t x,y,s,i z,w=D[x][y][0],D[x][y][1] if [' ','R','K'].index(M[x][y, 1])&&(z>s||z==s&&c(w).length>=c([i]).length) D[x][y]=[s,z==s ? w<<i:[i]] s+=1 t x+1,y,s,i+['S'] t x-1,y,s,i+['N'] t x,y+1,s,i+['E'] t x,y-1,s,i+['W'] end end t r.index(r.max), r.max, 0, [] puts c(D[k.index(k.max)][k.max][1]).map{|a|a*''} ``` [Answer] ## Ruby - 648 characters Another one that fails the least number of directions test as I can't think of any easy way to embed it in A\*. ``` m=$<.read.gsub /[^RK\n ]/,'#' l=m.index($/)+1 s=m.index'R' g=m.index'K' h=->y{(g%l-y%l).abs+(g/l-y/l).abs} n=->y{[y+1,y-1,y+l,y-l].reject{|i|m[i]=='#'}} a=o=[s] d=Array.new(m.length,9e9) c,k,f=[],[],[] d[s]=0 f[s]=h[s] r=->y,u{u<<y;(y=k[y])?redo:u} (x=o.min_by{|y|f[y]} x==g ? (a=r[x,[]].reverse;break):0 o-=[x];c<<x n[x].map{|y|c&[y]!=[]?0:(t=d[x]+1 o&[y]==[]?(o<<y;b=true):b=t<d[y] b ? (k[y]=x;d[y]=t;f[y]=t+h[y]):0)})until o==[] k=a.inject([[],nil]){|k,u|(c=k[1]) ? (k[0]<<(c==u-1?'E':c==u+1?'W':c==u+l ? 'N':'S')) : 0;[k[0],u]}[0].inject(["","",0]){|k,v|k[1]==v ? k[2]+=1 : (k[0]+=k[1]+" #{k[2]}\n";k[1]=v;k[2]=1);k} puts k[0][3,9e9]+k[1]+" #{k[2]}\n" ``` ]
[Question] [ Write the shortest program in your favourite language to interpret a [brainfuck](http://en.wikipedia.org/wiki/brainfuck) program. The program is read from a file. Input and output are standard input and standard output. 1. Cell size: 8bit unsigned. Overflow is undefined. 2. Array size: 30000 bytes (not circled) 3. Bad commands are not part of the input 4. Comments begin with # and extend to the end of line Comments are everything not in `+-.,[]<>` 5. no EOF symbol A very good test can be found [here](http://esoteric.sange.fi/brainfuck/bf-source/prog/PRIME.BF). It reads a number and then prints the prime numbers up to that number. To prevent link rot, here is a copy of the code: ``` compute prime numbers to use type the max number then push Alt 1 0 =================================================================== ======================== OUTPUT STRING ============================ =================================================================== >++++++++[<++++++++>-]<++++++++++++++++.[-] >++++++++++[<++++++++++>-]<++++++++++++++.[-] >++++++++++[<++++++++++>-]<+++++.[-] >++++++++++[<++++++++++>-]<+++++++++.[-] >++++++++++[<++++++++++>-]<+.[-] >++++++++++[<++++++++++>-]<+++++++++++++++.[-] >+++++[<+++++>-]<+++++++.[-] >++++++++++[<++++++++++>-]<+++++++++++++++++.[-] >++++++++++[<++++++++++>-]<++++++++++++.[-] >+++++[<+++++>-]<+++++++.[-] >++++++++++[<++++++++++>-]<++++++++++++++++.[-] >++++++++++[<++++++++++>-]<+++++++++++.[-] >+++++++[<+++++++>-]<+++++++++.[-] >+++++[<+++++>-]<+++++++.[-] =================================================================== ======================== INPUT NUMBER ============================ =================================================================== + cont=1 [ - cont=0 >, ======SUB10====== ---------- [ not 10 <+> cont=1 =====SUB38====== ---------- ---------- ---------- -------- > =====MUL10======= [>+>+<<-]>>[<<+>>-]< dup >>>+++++++++ [ <<< [>+>+<<-]>>[<<+>>-]< dup [<<+>>-] >>- ] <<<[-]< ======RMOVE1====== < [>+<-] ] < ] >>[<<+>>-]<< =================================================================== ======================= PROCESS NUMBER =========================== =================================================================== ==== ==== ==== ==== numd numu teid teiu ==== ==== ==== ==== >+<- [ >+ ======DUP====== [>+>+<<-]>>[<<+>>-]< >+<-- >>>>>>>>+<<<<<<<< isprime=1 [ >+ <- =====DUP3===== <[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<<< =====DUP2===== >[>>+>+<<<-]>>>[<<<+>>>-]<<< < >>> ====DIVIDES======= [>+>+<<-]>>[<<+>>-]< DUP i=div << [ >>>>>+ bool=1 <<< [>+>+<<-]>>[<<+>>-]< DUP [>>[-]<<-] IF i THEN bool=0 >> [ IF i=0 <<<< [>+>+<<-]>>[<<+>>-]< i=div >>> - bool=0 ] <<< - DEC i << - ] +>>[<<[-]>>-]<< >[-]< CLR div =====END DIVIDES==== [>>>>>>[-]<<<<<<-] if divides then isprime=0 << >>[-]>[-]<<< ] >>>>>>>> [ - <<<<<<<[-]<< [>>+>+<<<-]>>>[<<<+>>>-]<<< >> =================================================================== ======================== OUTPUT NUMBER =========================== =================================================================== [>+<-]> [ ======DUP====== [>+>+<<-]>>[<<+>>-]< ======MOD10==== >+++++++++< [ >>>+<< bool= 1 [>+>[-]<<-] bool= ten==0 >[<+>-] ten = tmp >[<<++++++++++>>-] if ten=0 ten=10 <<- dec ten <- dec num ] +++++++++ num=9 >[<->-]< dec num by ten =======RROT====== [>+<-] < [>+<-] < [>+<-] >>>[<<<+>>>-] < =======DIV10======== >+++++++++< [ >>>+<< bool= 1 [>+>[-]<<-] bool= ten==0 >[<+>-] ten = tmp >[<<++++++++++>>>+<-] if ten=0 ten=10 inc div <<- dec ten <- dec num ] >>>>[<<<<+>>>>-]<<<< copy div to num >[-]< clear ten =======INC1========= <+> ] < [ =======MOVER========= [>+<-] =======ADD48======== +++++++[<+++++++>-]<-> =======PUTC======= <.[-]> ======MOVEL2======== >[<<+>>-]< <- ] >++++[<++++++++>-]<.[-] =================================================================== =========================== END FOR =============================== =================================================================== >>>>>>> ] <<<<<<<< >[-]< [-] <<- ] ======LF======== ++++++++++.[-] @ ``` Example run: ``` $ python2 bf.py PRIME.BF Primes up to: 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 ``` [Answer] # Python (no eval), 317 bytes ``` from sys import* def f(u,c,k): while(c[1]>=k)*u: j,u='[]<>+-,.'.find(u[0]),u[1:];b=(j>=0)*(1-j%2*2);c[1]+=b*(j<2) while b*c[c[0]]and j<1:f(u,c,k+1);c[1]+=1 b*=c[1]==k;c[[0,c[0],2][j/2-1]]+=b if(j==6)*b:c[c[0]]=ord(stdin.read(1)) if(j>6)*b:stdout.write(chr(c[c[0]])) f(open(argv[1]).read(),[-1]+[0]*30003,0) ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~843~~ 691 bytes Edit: decided to revisit this and found a surprising number of ways to golf off bytes ``` >>>,[>++++[-<-------->]<-[>+<<]>[----------[>]>[<+<+>>>>]<<<-[>]>[<+<+>>>>]<<<-[>]>[<+<+>>>>]<<<-[>]>[<-<+++>>>>]<<<--------------[>]>[<++<+>>>>]<<<--[>]>[<-<+++++++>>+>>]<<++++[-<------>]+<+[>]>[<++<+>>>>]<<<--[>]>[<<+>>>>]<<-<[+]<[>]>,>]<]<-[<]>[-[<<]>[<+[>]>>[<+[<<[<]<<-[>>]<[>>>>[>]>+<<[<]<]<-[>>]<[>>>>[>]>-<<[<]<]<++[->>+<<]>>[>]>]]<<<[<]>-<]>-[<<]>[<++[>]>+>[<-]<[<<[<]>[-<<+>>]>--[<<]>[[>]>+<<[<]<]>+[<<]>[[>]>-<<[<]<]>+[>]>]<<[<]>--<]>-[<<]>[[>]>>.<<<[<]<]>-[<<]>[[>]>>-<<<[<]<]>-[<<]>[[>]>>,<<<[<]<]>-[<<]>[[>]>>+<<<[<]<]>-[<<]>[[>]>>>[>>]>[<<<[<<]<+>>>[>>]>-]>[-]<<+[<[->>+<<]<]<[->>+<<]<[<]<]>-[<<]>[[>]>-[+>[-<<+>>]>]+<<[-]+[-<<]<[->>>[>>]>+<<<[<<]<]<[<]<]<++++++++>>[+<<->>]>] ``` This takes input in the form `code!input` where the `!input` is optional. It also simulates negative cells without using negative cells itself and can store up to `(30000-(length of code+6))/2` cells. [Try it online!](https://tio.run/##lVJLDsJQCDyLax6egHARwqKamBgTFyaevzK8T59aF9I0bQdmYHg9PZbr/fI839ZVVYspRRgLt1AXDlDE1XiEaXwKCQUnKkT@QFiiw8DeolFmzkyiJFJm3sZUD8pv8kBYjFwAlviEs7Rl6a4q5FMkEjmwojwCKaqwf@LccUykdVeZcAyBFoy7d8k2BE@hUfNhBDNGUaua2yltGG8Y9Jv6JJ8WjtLLZpR30bKL0i6q8I19Ym7PrSbCcIAzMekLiGu8fgmx0WbZ4ZMdh9lIVZR6Gx/b7X@ARY6Tu67FjsUPy@n8Ag "brainfuck – Try It Online") [Answer] ## 16 bit 8086 machine code: 168 bytes Here's the [base64](http://www.motobit.com/util/base64-decoder-encoder.asp) encoded version, convert and save as 'bf.com' and run from Windows command prompt: 'bf progname' ``` gMYQUoDGEFKzgI1XAgIfiEcBtD3NIR8HcmOL2LQ/i88z0s0hcleL2DPA86sz/zP2/sU783NHrL0I AGgyAU14DTqGmAF194qOoAH/4UfDJv4Fwyb+DcO0AiaKFc0hw7QBzSGqT8MmODV1+jPtO/NzDaw8 W3UBRTxddfJNee/DJjg1dPoz7U509YpE/zxddQFFPFt18U157sM+PCstLixbXUxjTlJWXmV+ ``` **EDIT** Here's some assembler (A86 style) to create the executable (I had to reverse engineer this as I'd misplaced the original source!) ``` add dh,10h push dx add dh,10h push dx mov bl,80h lea dx,[bx+2] add bl,[bx] mov [bx+1],al mov ah,3dh int 21h pop ds pop es jb ret mov bx,ax mov ah,3fh mov cx,di xor dx,dx int 21h jb ret mov bx,ax xor ax,ax repz stosw xor di,di xor si,si inc ch program_loop: cmp si,bx jnb ret lodsb mov bp,8 push program_loop symbol_search: dec bp js ret cmp al,[bp+symbols] jnz symbol_search mov cl,[bp+instructions] jmp cx forward: inc di ret increment: inc b es:[di] ret decrement: dec b es:[di] ret output: mov ah,2 mov dl,es:[di] int 21h ret input: mov ah,1 int 21h stosb backward: dec di ret jumpforwardifzero: cmp es:[di],dh jnz ret xor bp,bp l1: cmp si,bx jnb ret lodsb cmp al,'[' jnz l2 inc bp l2: cmp al,']' jnz l1 dec bp jns l1 ret jumpbackwardifnotzero: cmp es:[di],dh jz ret xor bp,bp l3: dec si jz ret mov al,[si-1] cmp al,']' jnz l4 inc bp l4: cmp al,'[' jnz l3 dec bp jns l3 ret symbols: db '><+-.,[]' instructions: db forward and 255 db backward and 255 db increment and 255 db decrement and 255 db output and 255 db input and 255 db jumpforwardifzero and 255 db jumpbackwardifnotzero and 255 ``` [Answer] ## Perl, 120 ~~138~~ ``` %c=qw(> $p++ < $p-- + D++ - D-- [ while(D){ ] } . print+chrD , D=ord(getc)); $/=$,;$_=<>;s/./$c{$&};/g;s[D]'$b[$p]'g;eval ``` This runs hello.bf and primes.bf flawlessly: ``` $ perl bf.pl hello.bf Hello World! $ perl bf.pl prime.bf Primes up to: 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 ``` Initialization: The opcode to Perl translation table is stored in `%c`. The readable form looks like this: ``` %c=( '>' => '$p++', '<' => '$p--', '+' => '$b[$p]++', '-' => '$b[$p]--', '[' => 'while($b[$p]){', ']' => '}', '.' => 'print chr$b[$p]', ',' => '$b[$p]=ord(getc)', ); ``` Step 1: Slurp program input to `$_` and transform it to Perl code using the translation table. Comments are automatically stripped (replaced with `undef`) in this step. Step 2: Uncompress all `$b[$p]` occurrences Step 3: Launch the program using `eval`. [Answer] # [Vim](https://www.vim.org), ~~809~~ 580 bytes *-229 bytes because shenanigans and balderdash.* ``` qq<C-v><C-v><C-v>q<Esc>^mbO<C-r>q elsei "<C-r>q<C-r>c"=="<Esc>^"xc$<C-r>q norm <Esc>^"zc$en<C-r>q <Esc>^"yd$i`b"cyl:if "<C-v><C-r>c"==">"<C-r>z@f<C-r>x<"<C-r>z@b<C-r>x+"<C-r>z@i<C-r>x-"<C-r>z@d<C-r>x,"<C-r>z@p<C-r>x."<C-r>z@o<C-r>x["<C-r>z@s<C-r>x]"<C-r>z@l<C-v> <C-r>y`blmb@e<Esc>^"ec$`b^mbjj30000ddk30000o0<C-v><Esc>jjmo`lk$d`ox`bjjmp`ljmi`b<Esc>^"rc$`p:if line(".")<30002<C-r>zj<C-v> <C-r>ymp<Esc>^"fc$`p:if line(".")>3<C-r>zk<C-v> <C-r>ymp<Esc>^"bc$`p<C-v><C-a>Y:if <C-v><C-r>"<C-v><C-h>>255<C-r>z<C-v><C-x><C-v> <C-r>y<Esc>^"ic$`p<C-v><C-x>Y:if <C-v><C-r>"<C-v><C-h><0<C-r>z<C-v><C-a><C-v> <C-r>y<Esc>^"dc$`i"qx`p:if "<C-v><C-r>""!="<C-r>q<Esc>"<C-r>z3xi<C-r>q<C-r>=char2nr("<C-r>q<C-r>q")<C-r>q <C-r>q<Esc><C-v> else<C-r>z`i3i<C-v><C-v><Esc>a<C-v><Esc><C-r>q<Esc><C-v> <C-r>y<Esc>^"pc$`py$`oA<C-v><C-r>=nr2char(<C-v><C-r>")<C-v> <C-v><Esc>$mo<Esc>^"oc$`py$`b:if <C-v><C-r>"==0<C-r>z%mb<C-v> <C-r>y<Esc>^"sc$`py$`b:if <C-v><C-r>"!=0<C-r>z%mb<C-v> <C-r>y<Esc>^"ld$ddo<Esc>90i-<Esc>30000o0<Esc>o<Esc>90i-<Esc>o<Esc>moo<Esc>ml90i-<Esc>o<C-v><Esc><Esc>mio<Esc>90i-<Esc>`bjjmp ``` [Try it online!](https://tio.run/##ZVDBitswEGVvJUcdxIIuWeFCQioTYvbQYov0C3ouIYvWlrOVI1m2A4vin3dnbLWl7YD8ZvTejMbvfZr6nlLasxdXfiP9qra32qw56UnFi4KzFx6qBO5bP7g1VGOV1C3UkN51YlTJq7v9Yi5rTpcOycl4vJCQI5Yk7BANCQJRk/AJsSMhRfQknBBvJJwRLV2RuyqtK481vFBXiSphsabJ9hBaX2f0e8qaxnllr4lWPigQuE7ZxsE@0DZAW4c7WdPWG57ybY59BzI2ON91oLn8p5EZGa@/@RJ5@vAdJZRw@kEenp/JSB9RAbyZ@cc/fL4H9iGyGljD@7A8AdZw/lSAqQx@MgsG3C2qH6/DoR02aHXPt2Ap0HT2n4zKZIZS9krZfDnP7PDFe6L8V0qKdjjggA1M3tIVZYnzIPFRUsatigKW@ujKOOH2D/30N211orVnn/dGsOgzi6VnzsOxS0EZcyYyi/fTsV6/vWFTprWy8Jl2MU7y1xeT5eQQ4iwhk0LK3Sk/YylTKYRIY1@KSQqXuUjzORdzRIAEOlOYl07i/Sc "V (vim) – Try It Online") More than just an interpreter, this sets up an environment for programming in brainfuck with the following format: ``` brainfuck program ------------------------------------------------------------------- list of 30000 memory cells ------------------------------------------------------------------- program output ------------------------------------------------------------------- program input ^[ ------------------------------------------------------------------- ``` It also sets up some macros: * `@f` - `>` moves the MP forward * `@b` - `<` moves the MP backward * `@i` - `+` increments the cell at the MP * `@d` - `-` decrements the cell at the MP * `@p` - `,` input a character and store it in the cell at the MP * `@o` - `.` output the signified by the cell at the MP * `@s` - `[` start `while` loop * `@l` - `]` end `while` loop * `@e` - Execute. Recursively get the command at the IP and call the corresponding macro if it is a valid command, then increment the IP. * `@r` - Reset. Clear the output, reset all memory cells, and move the IP back to the beginning of the program. If using the TIO link, the input box is where the program goes to be executed. To pass input to the brainfuck program, add this to the footer before anything else: ``iiYour Input Here<Esc>`. Additionally, I added `gg30003dd`l3dd` to the footer to strip away everything except the brainfuck program's output, so you can remove that from the footer to see the entire result. If using Vim, copy the TIO code and paste it into Vim to set up the environment. From there, you can use ``b` to jump to the brainfuck program, ``p` to jump to the MP, ``o` to jump to the output, and ``i` to jump to the input. A few caveats: * The environment does not support newlines in the program, so the brainfuck program must be a single line. * The input must be terminated with `<Esc>`. The setup code automatically puts the `<Esc>` in the input section, so just make sure that the input goes before the `^[`. * To "read the program from a file", as it were, you can use Vim to open a file containing the brainfuck program and paste this code to set everything up and then execute it, as long as the program is already in a single line. * It's kinda slow. The test program for finding primes took ~2 minutes to finish with `n=2`. It took ~10 minutes with `n=7`. I didn't even bother trying anything higher. Nevertheless, it works. Note: This is the second version, and is golfed much further than the original, but I could almost certainly get it even shorter by defining the macros as macros instead of deleting into named registers. However, that will require pretty much rewriting this entire program, which I just golfed into illegibility, so I don't feel like doing it right now, but I might do it some time later. [Answer] # Ruby 1.8.7, ~~188~~ ~~185~~ ~~149~~ 147 characters ``` eval"a=[i=0]*3e4;"+$<.bytes.map{|b|{?.,"putc a[i]",?,,"a[i]=getc",?[,"while a[i]>0",?],"end",?<,"i-=1",?>,"i+=1",?+,"a[i]+=1",?-,"a[i]-=1"}[b]}*";" ``` Somewhat readable version: ``` code = "a = [0] * 3e4; i = 0;" more_code ARGF.bytes.map {|b| replacements = { ?. => "putc a[i]", ?, => "a[i] = getc", ?[ => "while a[i] > 0 do", ?] => "end", ?< => "i -= 1", ?> => "i += 1", ?+ =>"a[i]+=1", ?- =>"a[i]-=1" } replacements[b] }.join(";") eval code+more_code ``` As you see I shamelessly stole your idea of translating to the host language and then using eval to run it. [Answer] # Binary Lambda Calculus 112 The program shown in the hex dump below ``` 00000000 44 51 a1 01 84 55 d5 02 b7 70 30 22 ff 32 f0 00 |DQ...U...p0".2..| 00000010 bf f9 85 7f 5e e1 6f 95 7f 7d ee c0 e5 54 68 00 |....^.o..}...Th.| 00000020 58 55 fd fb e0 45 57 fd eb fb f0 b6 f0 2f d6 07 |XU...EW....../..| 00000030 e1 6f 73 d7 f1 14 bc c0 0b ff 2e 1f a1 6f 66 17 |.os..........of.| 00000040 e8 5b ef 2f cf ff 13 ff e1 ca 34 20 0a c8 d0 0b |.[./......4 ....| 00000050 99 ee 1f e5 ff 7f 5a 6a 1f ff 0f ff 87 9d 04 d0 |......Zj........| 00000060 ab 00 05 db 23 40 b7 3b 28 cc c0 b0 6c 0e 74 10 |....#@.;(...l.t.| 00000070 ``` expects its input to consist of a Brainfuck program (looking only at bits 0,1,4 to distinguish among ,-.+<>][ ) followed by a ], followed by the input for the Brainfuck program. Save the above hex dump with xxd -r > bf.Blc Grab a blc interpreter from <https://tromp.github.io/cl/cl.html> ``` cc -O2 -DM=0x100000 -m32 -std=c99 uni.c -o uni echo -n "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.]" > hw.bf cat bf.Blc hw.bf | ./uni ``` Hello World! [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~386~~ ~~391~~ 386 bytes Code contains unprintable NUL (`0x00`) characters. It's also not super golfed yet, because it's already really slow, and if I golf it more, I don't know how long it'd take to finish. Appears to time out on the prime-finding sample. There may be bugs in the online interpreter or in my program (leading new lines don't show in the output?). Takes input like `<code>│<input>`. No, that is not a pipe (`|`). It's the Unicode character [`U+2502`](http://apps.timwhitlock.info/unicode/inspect?s=%E2%94%82). The code also uses the Unicode characters `ÿ▶◀├║`. Unicode characters are used in order to support input of all ASCII characters. Therefore, these characters need to be separated from the code by a non-ASCII character. [**Try it online**](https://tio.run/nexus/retina#XVBBTsMwEPR53@GDncQWSa8hFfAFbrYj/wCpOaaVED9AKnDpO7j20J/kI2HWbkMgsrKr3Zmd2Z2H2NuCps9veTcdT9PHO1JBwxgVks4WqNhCI1dWK7vVJGvZMHyTSJTgmcZBcGRqe6OCxzVZM7yh53g5GxHFS1Tb9h41X16RyLWl3pcEkDCXM5ALyvwFGUoi3qJyPLHK0oUee9zIBhYZVDHmLZlXV3ieklG8gXdqNV@QQ2C7Y30QlE@BV2rleudDKLR3JBuXdqJD5Ov86wf0g6xpF5XLJZYJKxnXi8BOp69XvAAjuzHCyG2EQrXU@GUlyIC@bqY@moldEyN/7bgeOwed9fRy/cHHdIJ9ckHzXFlnApXpc12OZWtCZ6myhBkPj08/) ``` s`^.* ▶$0├║▶ s{`(▶>.*║.*)▶(.)(.?) $1$2▶$3 ▶$ ▶ ║▶ ║▶ (▶<.*║.*)(.)▶ $1▶$2 T`ÿ-`o`(?<=▶\+.*║.*▶). ^\+ T`-ÿ`ÿo`(?<=▶-.*║.*▶). ^- (▶\..*├.*)(║.*▶)(.) $1$3$2$3 (▶,.*│)(.?)(.*├.*▶). $1$3$2 ▶\[(.*║.*▶) [▶▶${1} {`(▶▶+)([^[\]]*)\[ $2[$1▶ }`▶(▶+)([^[\]]*)\] $2]$1 r`([[\]]*)▶\](.*║.*▶[^]) $1◀◀]$2 r{`\[([^[\]]*)(◀+)◀ $2[$1 }`\]([^[\]]*)(◀◀+) $2◀]$1 ◀ ▶ }`▶([^│])(.*║) $1▶$2 s\`.*├|║.* ``` Note there is a trailing newline there. ### Brief Explanation: Zeros `0x00` are used for the tape, which is infinite. The first replacement sets up the interpreter in the form `▶<code>│<input>├<output>║▶<tape>`, where the first `▶` is the pointer for the code, and the second one is the pointer for the tape. `ÿ` is `0xFF` (255), which is used for Transliteration (used to implement `+` and `-`) to wrap the cells back around to zero. `◀` is only used for readability (in case the program is stopped in the middle or you want to see the program mid-execution). Otherwise, you couldn't tell which way the pointer was moving. ### Commented Code: ``` s`^.* # Initialize ▶$0├║▶ s{`(▶>.*║.*)▶(.)(.?) # > $1$2▶$3 ▶$ ▶ ║▶ # < ║▶ (▶<.*║.*)(.)▶ $1▶$2 T`ÿ-`o`(?<=▶\+.*║.*▶). # + ^\+ T`-ÿ`ÿo`(?<=▶-.*║.*▶). # - ^- (▶\..*├.*)(║.*▶)(.) # . $1$3$2$3 (▶,.*│)(.?)(.*├.*▶). # , $1$3$2 ▶\[(.*║.*▶) # [ [▶▶${1} {`(▶▶+)([^[\]]*)\[ $2[$1▶ }`▶(▶+)([^[\]]*)\] $2]$1 r`([[\]]*)▶\](.*║.*▶[^]) # ] $1◀◀]$2 r{`\[([^[\]]*)(◀+)◀ $2[$1 }`\]([^[\]]*)(◀◀+) $2◀]$1 ◀ ▶ }`▶([^│])(.*║) # next instruction $1▶$2 s\`.*├|║.* # print output ``` [Click here](https://tio.run/nexus/retina#XVExbsMwDNz5Dg2SFQmys7oO2n6hmyRDPygQj0aAoD8okLZL3tE1Q37ij7hHKXHdGoJJkHe8EzUPqbcVTZ/fwk2n8/TxjtTRMCaJpLMVKrZSyKVV0u4UiVo0DN9mEmV4oXFwHJna3qngcU3UDG/oJV0vxiX3muSufUAt6BsSubLUB00AOXO9ALmgzF@QoSwSLCqnM6ssXeixx61oYJFBG8a8ZfPyBi9TCopvELxczXfkEdjuWB8clVXgaCV970OMlQqeROPzneiQeDv/@hH9KGraJ@lLiWXiSsb3LrLT6euIE2FkPyYYuY@QqGqFX1GCDOjrZu6jmdk1MfLXju9x56iKnlq2P4SUVyD5TdkIOvO8sd5E0vnzXYm6NbGztLGEQY9Pzz8) for the code with zeros in place of null bytes. Any occurrences of `$0` should not be replaced with nulls. **Edit**: Now supports empty input and suppresses trailing newline. [Infinite output is now supported.](https://tio.run/nexus/retina#XVFBTsMwEPR53@GDnTQWTq@Fij9wsx35B0jNMVRC/ACpwKXv4NpDf5KPhNk1CSmSFa92ZnZ2nKnPnato/PzWd@PpPH68o1TUD9mgeHAVOq6yqI2zxu0taa9bpm9FREIvMr4U3yzdzVLouKc901t6ytdLo7J6zma/u0cv1r9M1NZRF2sCSTXXC5gLq7klNSQm0aFzOluzYHDjDbe6xYJVzIK/CEyE0qGkElQmbJjwJsmMcGeLMoTjxWBW5ooCLs4y@KOi8k44tTWhCzGlysZAug0SmI6Zn@4fnoAn7emQTSgttkkrm9CpxEHGr1echEUOQ8Yi8wiDbm3xKU6wgXwNCg5Q1J6Y@bdO6JA52eJnl1/T3z7XNG2CS2A@/gA) (403 bytes) [Answer] ## Conveyor, 953 This might be the most beautiful code you will ever see: ``` 0 :I\1\@p >#====) ^#====< PP0 P<=======================< 00t:)01t1 a:P:P:P:P:P:P:^ >===========">">2>">2>">"^ ^ +^-^5^ ^5^]^.^ ^ "^"^*^"^*^"^"^ ^ -^-^6^-^6^-^-^ ^ #^#^*^#^*^#^#^ ^ P P -^P )^P P ^ P P #^P )^P P ^t1\)t0:))t01 P -^ 1 ^===========< P #^ 0 ^ t1\(t0:))t01 P t ^=============< P ) ^ t11(t01 0 0 ) ^===============<. t P 10 ^ FT#T#=< ^=================< P ^ t11)t01 ^===================< 10t))0tP00t:(01t(1a:P: ^ >=====#=>==========">" ^ ^ ]^[ ^ P ^ "^" ^===========================<=^#=====< -^- ^==< ^ PP#^#= ^===PTPT< ^ )P P ^=<=< ( ^===< ``` [Answer] ## Python 275 248 255 I decided to give it a try. ``` import sys i=0 b=[0]*30000 t='' for e in open(sys.argv[1]).read(): t+=' '*i+['i+=1','i-=1','b[i]+=1','b[i]-=1','sys.stdout.write(chr(b[i]))','b[i]=ord(sys.stdin.read(1))','while b[i]:','pass','']['><+-.,['.find(e)]+'\n' i+=(92-ord(e))*(e in'][') exec t ``` [Answer] # TypeScript Types, ~~1807~~ 1771 bytes ``` //@ts-ignore type B<X="\0\x01\x02\x03\x04\x05\x06\x07\b\t\n\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff",a=[]>=X extends`${infer A}${infer C}`?B<C,[...a,A]>:a;type C={[K in keyof B&`${number}`as B[K]]:D<K>};type D<T,A=[]>=T extends`${A["length"]}`?A["length"]:D<T,[0,...A]>;type E<A=[]>=255 extends A["length"]?[...A,0]:E<[...A,[...A,0]["length"]]>;type F=[255,0,...E];type G<L,D=never>=L extends[infer A,{}]?A:D;type H<L,D=never>=L extends[{},infer B]?B:D;type M<a,b,c=0,d="",e=0,f=0,g=0,h=0,i=[],>=a extends`${infer j}${infer a}`?h extends 0?j extends"+"?M<a,b,c,d,e,E<[]>[f],g>:j extends"-"?M<a,b,c,d,e,F[f],g>:j extends"<"?e extends 0?M<a,b,c,d,e,f,g>:M<a,b,c,d,H<e>,G<e>,[f,g]>:j extends">"?M<a,b,c,d,[f,e],G<g,0>,H<g,[]>>:j extends"["?f extends 0?M<a,b,c,d,e,f,g,1>:M<a,b,[a,c],d,e,f,g>:j extends"]"?f extends 0?M<a,b,H<c>,d,e,f,g>:M<G<c>,b,c,d,e,f,g>:j extends","?b extends`${infer k}${infer b}`?M<a,b,c,d,e,k extends keyof j?j[k]:0,g>:M<a,b,c,d,e,0,g>:j extends"."?M<a,b,c,`${d}${B[f]}`,e,f,g>:M<a,b,c,d,e,f,g>:j extends"]"?M<a,b,c,d,e,f,g,G<i,0>,H<i,[]>>:j extends"["?M<a,b,c,d,e,f,g,1,[1,i]>:M<a,b,c,d,e,f,g,h,i>:d ``` [Try it online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAIQB4ANAXgCIAdABloA96BGZ+gJg4GYOAWDgFYOANg4B2WgCNa4WoloA3WgDNaqDgFEOAMWatGTVu2PdjfY4OMjj441OMAOAwE4DAQQPEDAYQMAIgY6xrqEAIS01ADEACQApABkAOQAFACUAFQA1AA00AB0wGycPPxCohJOrgBcANyklAB8APygHsS+AVq6AOIAEgCSAFIA0gAyALIAcgDyAAoAigBKAMoAKgCqAGoA6uQAmgBaANq0tAC6AHoA+gAGAIbSAMYAJuiq8AAWsABWANYAGwAtig8ABHVCQcAAVyUAHcmDgAF4AbwAPgBfAB+zAk+iYTiMTlMTnMTksTmsTlsTnsTkcThchPchK8hJ8hP8hKChJCTgJriMrlMrnMrksrmsrlsrnsrkcrmZrlZrnZrk5rm5rl5rhCrgJDyMD1MD3MD0sD2sD1sD3sD0cD2ZD1ZDwezCeHueHteHvQHvUTGkRmkpmk5mklmk1mktmk9mkjmkzOkrOk7qDsiD3qDvqD-qDgeeRmepme5melme1metme9mejmezOerOeGeeWeeObezGeBeegdeRleple5lelle1letle9lejlezNerNeGdeW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vufs-uvuftSCAdSD0Ba2hWfvaD0BV3vtSBkTAda3aBLMQf0D0BLNvuvtLOocvuIcIfAdLNSCYehVLPIfEcockckfYeEd7trrTkAB6UpwAQAA) [Answer] # [C (gcc)](https://gcc.gnu.org/) Linux x86\_64, ~~884 621 525 487 439 383 358~~ 347 bytes ``` *z,*mmap();d[7500];h;(*p)();*j(char*a){char*t=a,*n,c,q=0;for(;read(h,&c,!q);t=c==47?n=j(t+9),z=mempcpy(t,L"\xf003e80Ƅ",5),*z=n-t-9,n:c==49?q=*t++=233,z=t,*z=a-13-t,z+1:stpcpy(t,c-18?c-16?~c?c-1?c-2?c?t:"1\xc0P_\xF\5":"RXR_\xF\5":L"໾":L"۾":L"컿":L"웿"))c-=44;return t;}main(P,g)int**g;{*j(p=mmap(0,1<<20,6,34,h=open(g[1],0),0))=195;p(0,d,1);} ``` [Try it online!](https://tio.run/##tVjdbuJGFL6fpzjlosLYTu2Q7CZhPHQ3kBaJQERCVMlBFRhncRQbB0yVZLu96lv0UVbq3vUletMH6Duk82sMMRtokhHYg@c7PzPnO2fGDPrT0YPXTzCut4@BDC6vgmTLeyjdG6Uw7MdFrTJ03@5aVq8yqhRLsUYflK6K3qg/KfW1j/yeOH2jFBmeceNYlcvxpFiZ@P1hcWR86xnf3GiVxPEcZ@dtNXKuiom@rxn3TuiHsRffFROjWbi4vbSssr9n/fV7wdjVjNK9E5mJuW9EB0xuv3rjlBJdd7bLZSqZsPG@aZfNxLjX7YNpIhV5pr1XpZc31d88dqff7apXTQ4K9sWtZ538fHF7dLFbOCh0fuqofrPwz@c/2e1vfv338xd@@@NLQdM809nZoTNJZpMIksqnsB9ExRPjgxZESan0ofKRLkPs8DWyDBvjbct4Y5R3jJEzjv2o@MG1e4al0Y/m2Pu7FYYaGrZW@fRAFxp5HsilBnMsumgehXgShP50a3CJvHEYzxIf@BOIZuHAn0xRMobZ1IfkLqaXkQ9h/1aOsZ8RxLPpCN5dJ2CDhZznt5U6oN09O@mewelZp9H6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MPS@9L3iP2t4HujMT2kW79ufcf/U4D0n4SH/wA "Bash – Try It Online") This is a JIT that compiles BF code into x86\_64 machine language at runtime. This performs a straight translation so commonly occurring sequences such as `>>>`, `<<<`, `+++` and `---` aren't coalesced into faster instructions. Less golfed version: ``` // size of data area *z,c,*mmap();d[7500];h;(*p)(); // recursive function translates BF commands to x86_64 instructions *j(char*a){ char*t=a,*n,q=0; for(;read(h,&c,!q);) c-=44, t=c==47? // [ // cmpb $0x0,(%rsi) // je n-t-9 n=j(t+9), z=mempcpy(t,L"\xf003e80Ƅ",5), *z=n-t-9, n : c==49? // ] // jmp a-13-t q=*t++=233, z=t, *z=a-13-t, z+1 : stpcpy(t,c-18? // > c-16? // < ~c? // + c-1? // - c-2? // . c? // , "" : // xor %eax,%eax // push %rax // pop %rdi // syscall "1\xc0P_\xF\5" : // push %rdx // pop %rax // push %rdx // pop %rdi // syscall "RXR_\xF\5" : // decb (%rsi) L"໾" : // incb (%rsi) L"۾" : // dec %esi L"컿" : // inc %esi L"웿"); return t; } main(P,g)int**g;{ // allocate text (executable) memory and mark as executable p=mmap(0,1<<20,6,34,h=open(g[1],0),0); // run JIT, set %rdx=1 and call code like a function p(*j(p)=195,d,1); } ``` [Answer] ## Haskell, 457 413 characters ``` import IO import System z=return '>'#(c,(l,d:r))=z(d,(c:l,r)) '<'#(d,(c:l,r))=z(c,(l,d:r)) '+'#(c,m)=z(succ c,m) '-'#(c,m)=z(pred c,m) '.'#t@(c,_)=putChar c>>hFlush stdout>>z t ','#(_,m)=getChar>>=(\c->z(c,m)) _#t=z t _%t@('\0',_)=z t i%t=i t>>=(i%) b('[':r)=k$b r b(']':r)=(z,r) b(c:r)=f(c#)$b r b[]=(z,[]) f j(i,r)=(\t->j t>>=i,r) k(i,r)=f(i%)$b r main=getArgs>>=readFile.head>>=($('\0',("",repeat '\0'))).fst.b ``` This code "compiles" the BF program into an `IO` action of the form `State -> IO State` the state is a zipper on an infinite string. Sad that I had to expend 29 characters to turn buffering off. Without those, it works, but you don't see the prompts before you have to type input. The compiler itself (`b`, `f`, and `k`) is just 99 characters, the runtime (`#` and `%`) is 216. The driver w/initial state another 32. ``` >ghc -O3 --make BF.hs [1 of 1] Compiling Main ( BF.hs, BF.o ) Linking BF ... >./BF HELLO.BF Hello World! >./BF PRIME.BF Primes up to: 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 ``` *update 2011-02-15:* Incorporated J B's suggestions, did a little renaming, and tightened up `main` [Answer] # Brainfuck, 948 bytes Well, that took a while. I golfed [a Brainfuck self-interpreter by ... not me.](https://github.com/ludamad/bf-self-interpreter) ``` ->->>>-[,+>+<[->-]>[->]<+<-------------------------------------[+++++++++++++++++++++++++++++++++++++>-]>[->]<<[>++++++++[-<----->]<---[-[-[-[--------------[--[>+++++++[-<---->]<-[--[[+]->]<+[->++>]->]<+[->+>]->]<+[->+++++>]->]<+[->++++++>]->]<+[->+++++++>]->]<+[->++++>]->]<+[->++++++++>]->]<+[->+++>]->]+<+[->->]>[-<->]<]>>->>-<<<<<+++[<]>[-[-[-[-[-[-[-[-<<++++++++>>>[>]>>>>+[->>+]->,<<<+[-<<+]-<<<[<]<]>[<<<+++++++>>>[>]>>>>+[->>+]->.<<<+[-<<+]-<<<[<]]<]>[<<<++++++>>>[>]>>>>+[->>+]<<-<<+[-<<+]-<<<[<]]<]>[<<<+++++>>>[>]>>>>+[->>+]+>>-<<[-<<+]-<<<[<]]<]>[<<<++++>>>[>]>>>>+[->>+]->-<<<+[-<<+]-<<<[<]]<]>[<<<+++>>>[>]>>>>+[->>+]->+<<<+[-<<+]-<<<[<]]<]>[<++[>]>>>>+[->>+]->[<<<+[-<<+]-<<<[<]-[<<-[>->-[<+]]<+[->>[<]]<-[>-->+[<++]]<++[-->>[<]]<++>>[[-<+>]<<[->>+<<]]<[>]>]]<[<<+[-<<+]-<<<[<]>--<<++>]>]<]>[<<<+>>>[>]>>>>+[->>+]->[<<<+[-<<+]-<<<[<]]<[<<+[-<<+]-<<<[<]+[>-[<-<]<<[>>]>>-[<+<]<<[>>]>>++<[>[-<<+>>]<[->+<]]<[>]>]]>[[-<<+>>]<[->+<]>]]>] ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~150~~ ~~149~~ 148 bytes ``` k2T0ẋ→_0→0?£{D¥L<|¥i:‛+-$c[:‛ +ḟ←_:_←›Ǔṫ∇∇+J←›ǔ→_|:‛<>$c[:‛ >ḟ←+→|:\.=[←_← iC₴|:\,=[←_:_←?CȦ→_|:\[=[←_← i¬[Ȯ¥$ȯ\]ḟ∇∇+$]|:\]=[Ȯ¥$Ẏf\[=TG‹∇$_]]]]]]]_› ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrMlQw4bqL4oaSXzDihpIwP8Kje0TCpUw8fMKlaTrigJsrLSRjWzrigJsgK+G4n+KGkF86X+KGkOKAuseT4bmr4oiH4oiHK0rihpDigLrHlOKGkl98OuKAmzw+JGNbOuKAmyA+4bif4oaQK+KGknw6XFwuPVvihpBf4oaQIGlD4oK0fDpcXCw9W+KGkF86X+KGkD9DyKbihpJffDpcXFs9W+KGkF/ihpAgacKsW8iuwqUkyK9cXF3huJ/iiIfiiIcrJF18OlxcXT1byK7CpSThuo5mXFxbPVRH4oC54oiHJF9dXV1dXV1dX+KAuiIsIiIsIisrKysrKysrKytbPisrKysrKys+KysrKysrKysrKz4rKys+Kzw8PDwtXT4rKy4+Ky4rKysrKysrLi4rKysuPisrLjw8KysrKysrKysrKysrKysrLj4uKysrLi0tLS0tLS4tLS0tLS0tLS4+Ky4+LiJd) "But there's already a Vyxal answer that's ~~100~~ ~~99~~ 98 bytes shorter bro what is this cringe" I hear you say. Well this version doesn't use `eval`, and instead runs it manually. Note that it can be slow because it's doing things like rotating a 30000 item list quite frequently, so [here's a version with only 100 cells for testing](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIxMDAgMOG6i+KGkl8w4oaSMD/Co3tEwqVMPHzCpWk64oCbKy0kY1s64oCbICvhuJ/ihpBfOl/ihpDigLrHk+G5q+KIh+KIhytK4oaQ4oC6x5TihpJffDrigJs8PiRjWzrigJsgPuG4n+KGkCvihpJ8OlxcLj1b4oaQX+KGkCBpQ+KCtHw6XFwsPVvihpBfOl/ihpA/Q8im4oaSX3w6XFxbPVvihpBf4oaQIGnCrFvIrsKlJMivXFxd4bif4oiH4oiHKyRdfDpcXF09W8iuwqUk4bqOZlxcWz1UR+KAueKIhyRfXV1dXV1dXV/igLoiLCIiLCIrKysrKysrKysrWz4rKysrKysrPisrKysrKysrKys+KysrPis8PDw8LV0+KysuPisuKysrKysrKy4uKysrLj4rKy48PCsrKysrKysrKysrKysrKy4+LisrKy4tLS0tLS0uLS0tLS0tLS0uPisuPi4iXQ==) Some assumptions this program makes: * Closed brackets * EOF handled manually * Program on first line, each input character on a new line ## Explained ### Quick Overview ``` k2T0ẋ→_ # Tape 0→ # Cell pointer 0 # Instruction pointer ?£ # Prog {D¥L<| # While the instruction pointer is less than program length :,←_,¥i # Get command :‛+-$c[:‛ +ḟ←_:_←›Ǔṫ∇∇+J←›ǔ→_| # Handle addition and subtraction in the same place :‛<>$c[:‛ >ḟ←+→| # Handle moving the pointer left and right :\.=[←_← iC,| # Output :\,=[←_:_←?CȦ→_| # Input :\[=[ # jump to next `]` if tape[cell] == 0 ←_← i¬[Ȯ¥$ȯ:,\]ḟ›∇+$]| :\]=[Ȯ¥$Ẏf\[=TG›∇$_] # Jump back to the previous `[` ]]]]]] _ # Remove the char from the stack › # Next command } ``` ### Detailed Explanation ``` k2T0ẋ→_ ``` This is the tape. It consists of 30000 0s in a list. It's stored in a global variable called `_`. ``` 0→ ``` This is the cell pointer. It tracks which cell is being pointed to. It's stored in the ghost variable. The ghost variable is another name for the variable with no name (as in, its name is literally `""` - the empty string.) ``` 0 ``` This is the instruction pointer. It tracks which character of the program is being executed. It's stored on the stack as the bottom of the stack. Throughout this answer, the stack is `[instruction pointer, current character, ...]` where `...` is whatever processing is happening in each command. ``` ?£ ``` This gets the program to execute and stores it in the register. ``` {D¥L<| ``` This is the main program execution loop. It calls its code while the instruction pointer is less than the length of the program. Before performing the comparison, the instruction pointer is triplicated (i.e. three copies of it are pushed to the stack). This is so that there is a copy for the comparison, for getting the current character in the program and for maintaining the value of the pointer. ``` ¥i ``` This gets the character at the index of the instruction pointer and puts it on the stack. The stack is now `[instruction pointer, command]`. We now move on to handling the commands #### Addition and Subtraction ``` :‛+-$c[:‛ +ḟ←_:_←›Ǔṫ∇∇+J←›ǔ→_ ``` The above snippet is the entirety of the section that handles the `+` and `-` commands. ``` :‛+-$c ``` This checks if the command is in the string `"+-"`, while leaving a copy of the command on the stack for further comparison if needed. ``` [:‛ +ḟ ``` If the command *is* one of `+` or `-`, then the command is duplicated yet again, and its index in the string `" +"` is returned. This returns `1` for `+` and `-1` for `-`, as `-1` is returned for characters not in the string. The `1` or `-1` acts as an offset for the current cell, and saves having to check for `+` and `-` individually. It also means `+` can be used for both commands instead of `›` for addition and `‹` for subtraction. ``` ←_:_←›Ǔ ``` This pushes the tape (stored in the global variable called `_`), the value of the cell pointer + 1 (stored in the ghost variable and then incremented) and then rotates the tape left that many times. The `:_` after `←_` is needed because there seems to be a bug with list mutability when rotating. (TODO: Fix) After the rotation, the cell that is to be incremented or decremented is at the tail of the tape. ``` ṫ∇∇+J ``` This separates the tail and the rest of the list - first it pushes `tape[:-1]` and then it pushes `tape[-1]`. It then rotates the top three items on the stack so that the order is `[tape[:-1], tape[-1], offset]`. The offset is then added to the tail, and the tail is then appended back to the rest of the tape. ``` ←›ǔ→_ ``` The tape is then rotated `cell pointer + 1` times to the right to "undo" the left rotation and then placed back into the global variable called `_`. #### Moving the Cell Pointer ``` |:‛<>$c[:‛ >ḟ←+→ ``` The above snippet is the entirety of the section that handles the `<` and `>` commands. ``` |:‛<>$c ``` Just like with the `+` and `-` commands, a check is done to see if the command is in the string `"<>"`. ``` [:‛ >ḟ ``` And also just like with the `+` and `-` commands, if the command *is* one of `<` or `>`, then the command is duplicated yet again, and its index in the string `" >"` is returned. This returns `1` for `>` and `-1` for `<`. The `1` or `-1` acts as an offset for the current cell location, and saves having to check for `<` and `>` individually. It also means `+` can be used for both commands instead of `›` for moving right and `‹` for moving left. ``` ←+→ ``` This adds the offset to the cell pointer and updates the value stored in the ghost variable. It also acts as a weird face. #### Output ``` |:\.=[←_← iC₴ ``` The above snippet is the entirety of the section that handles the `.` command. ``` |:\.= ``` This checks if the command is equal to the string `"."`. Unlike addition/subtraction and cell pointer movement, input and output cannot be handled in the same if-statement, as their functions are different at a fundamental level. ``` [←_← i ``` If the command is `.`, the tape is pushed, as well as the cell pointer's value. The item at the location of the cell pointer is then retrieved. The space after the second `←` is needed to avoid it being interpreted as `←i` ``` C₴ ``` This prints that item after converting it to its ASCII equivalent (think `chr` in python) #### Input ``` |:\,=[←_:_←?CȦ→_ ``` The above snippet is the entirety of the section that handles the `,` command. ``` |:\,= ``` This checks if the command is equal to the string `","`. ``` [←_:_←?C ``` If the command *is* `,`, the tape and current cell pointer are pushed to the stack, as well as the ordinal value (think `ord` in python) of the next input. ``` Ȧ→_ ``` This sets the `cell pointer`th item of `tape` to the input. Basically `tape[cell_pointer] = ord(input())`. #### Looping ``` |:\[=[←_← i0=[Ȯ¥$ȯ\]ḟ∇∇+$] ``` The above snippet is the entirety of the section that handles the `[` command. ``` |:\[= ``` The usual check for a certain character. `[` this time. ``` [←_← i ``` If the command is `[`, get the `cell pointer`th item of `tape`. ``` ¬[ ``` If the cell is not a truthy value (i.e. not `0`), then: ``` Ȯ¥$ȯ\]ḟ ``` Push `program[instruction_pointer:]` and find the first `]` in that string. The stack is now `[instruction pointer, command, position of "]"]`. ``` ∇∇+$ ``` Rotate the stack so that its order is `[command, position of "]", instruction pointer]` and add the position of the `]` to the instruction pointer. This has the effect of iterating through the program until the next `]` is found without having to have lengthy while loops. ``` |:\]=[Ȯ¥$Ẏf\[=TG‹∇$_ ``` The above snippet is the entirety of the section that handles the `]` command. ``` |:\]= ``` Check if the command is `]` ``` [Ȯ¥$Ẏf\[=TG ``` And if it is, get the greatest index of all `[`s in the string `program[0:instruction_pointer]`. This has the effect of backtracking to the matching `[` without having to have a lengthy while loop. ``` ‹∇$_ ``` Decrement that so that the instruction pointer will be re-incremented to the position of the matching `[` and rotate the stack so that the stack order is once again `[instruction pointer, command]` #### Final bits ``` ]]]]]]] # Close all the if statements _ # Remove the command from the stack › # Move the instruction pointer forward 1 } # Close the main while loop ``` [Answer] # CJam, 75 bytes ``` lq3e4Vc*@{"-<[],.+>"#"T1$T=(t T(:T; { _T=}g \0+(@T@t _T=o "_'(')er+S/=}%s~@ ``` Try it online: [string reverser](http://cjam.tryitonline.net/#code=bHEzZTRWY2EqQHsiLTxbXSwuKz4iIyJUMSRUPSh0IFQoOlQ7IHsgX1Q9fWcgXDArKEBUQHQgX1Q9byAiXycoJyllcitTLz19JXN-QA&input=LFs-LF08Wy48XQpIaSwgQ0phbSE), [Hello World](http://cjam.tryitonline.net/#code=bHEzZTRWY2EqQHsiLTxbXSwuKz4iIyJUMSRUPSh0IFQoOlQ7IHsgX1Q9fWcgXDArKEBUQHQgX1Q9byAiXycoJyllcitTLz19JXN-QA&input=KysrKysrKytbPisrKytbPisrPisrKz4rKys-Kzw8PDwtXT4rPis-LT4-K1s8XTwtXT4-Lj4tLS0uKysrKysrKy4uKysrLj4-LjwtLjwuKysrLi0tLS0tLS4tLS0tLS0tLS4-PisuPisrLg). ## Explanation Takes code on the first line of STDIN and input on all lines below it. ``` l Read a line from STDIN (the program) and push it. q Read the rest of STDIN (the input) and push it. 3e4Vc* Push a list of 30000 '\0' characters. @ Rotate the stack so the program is on top. { }% Apply this to each character in prog: "-<[],.+>"# Map '-' to 0, '<' to 1, ... and everything else to -1. ...= Push a magical list and index from it. s~ Concatenate the results and evaluate the resulting string as CJam code. @ Rotate the top three elements again -- but there are only two, so the program terminates. ``` What about that magical list? ``` "T1$T=(t T(:T; { _T=}g \0+(@T@t _T=o " Space-separated CJam snippets. (Note the final space! We want an empty string at the end of the list.) _'(')er+ Duplicate, change (s to )s, append. S/ Split over spaces. ``` The resulting list is as follows: ``` T1$T=(t (-) T(:T; (<) { ([) _T=}g (]) \0+(@T@t (,) _T=o (.) T1$T=)t (+) T):T; (>) { (unused) _T=}g (unused) \0+(@T@t (unused) _T=o (unused) (all other characters) ``` We generate the snippets for `+` and `>` from those for `-` and `<`, simply by changing left parens (CJam’s “decrement”) into right parens (CJam’s “increment”). [Answer] ## C 284 362 (From a file) ``` #include <stdio.h> char b[30000],z[9999],*p=b,c,*a,i;f(char*r,int s){while(c=*a++){if(!s){(c-62)?(c-60)?(c-43)?(c-45)?(c-46)?(c-44)?0:(*p=getchar()):putchar(*p):--*p:++*p:--p:++p;if(c==91)f(a,!*p);else if(c==93){if(!*p)return;else a=r;}}else{if(c==93){--s;if(!*p&&!s)return;}else if(c==91){s++;}}}}main(int c,char**v){fread(z,1,9999,fopen(*++v,"r"));a=z;f(0,0);} ``` **Primes:** ``` Primes up to: 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 Press any key to continue . . . ``` Compiled and ran successfully VS2008 Original solution failed to recognize loops that were initially set to zero. Still some room to golf. But finally solves the Prime Number program. **Ungolfed:** ``` #include <stdio.h> char b[30000],z[9999],*p=b,c,*a,i; f(char*r,int s) { while(c=*a++) { if(!s) { (c-62)?(c-60)?(c-43)?(c-45)?(c-46)?(c-44)?0:(*p=getchar()):putchar(*p):--*p:++*p:--p:++p; if(c==91)f(a,!*p); else if(c==93){if(!*p)return;else a=r;} } else { if(c==93) { --s; if(!*p&&!s)return; } else if(c==91) { s++; } } } } main(int c,char**v){ fread(z,1,9999,fopen(*++v,"r")); a=z; f(0,0); } ``` **Tests:** [Hello World](http://en.wikipedia.org/wiki/Brainfuck) [Rot13](http://esoteric.sange.fi/brainfuck/bf-source/prog/rot13.bf) [Answer] ## PHP 5.4, ~~296~~ ~~294~~ ~~273~~ ~~263~~ ~~261~~ ~~209~~ ~~191~~ ~~183~~ ~~178~~ 166 characters: I gave it a shot without using eval, but I eventually had to use it ``` <?$b=0;eval(strtr(`cat $argv[1]`,["]"=>'}',"["=>'while($$b){',"."=>'echo chr($$b);',","=>'$$b=fgetc(STDIN);',"+"=>'$$b++;',"-"=>'$$b--;',">"=>'$b++;',"<"=>'$b--;'])); ``` All commands are working. This heavily abuses variable variables, and spews warnings. However, if one changes their php.ini to squelch warnings (or pipes stderr to /dev/null), this works great. Verification (It's the "Hello World!" example from [Wikipedia](http://en.wikipedia.org/wiki/Brainfuck#Hello_World.21)): <http://codepad.viper-7.com/O9lYjl> **Ungolfed, ~~367~~ ~~365~~ ~~335~~ ~~296~~ 267 characters:** ``` <?php $a[] = $b = 0; $p = implode("",file($argv[1])); // Shorter than file_get_contents by one char $m = array("]" => '}', "[" => 'while($a[$b]){',"." => 'echo chr($a[$b]);', "," => '$a[$b]=fgetc(STDIN);', "+" => '$a[$b]++;', "-" => '$a[$b]--;', ">" => '$b++;', "<" => '$b--;'); $p = strtr($p,$m); @eval($p); ``` This should be run via the command line: `php bf.php hello.bf` [Answer] ## Windows PowerShell, 204 ``` '$c=,0*3e4;'+@{62='$i++ ';60='$i-- ';43='$c[$i]++ ';45='$c[$i]-- ';44='$c[$i]=+[console]::ReadKey().keychar ';46='write-host -n([char]$c[$i]) ';91='for(;$c[$i]){';93='}'}[[int[]][char[]]"$(gc $args)"]|iex ``` Fairly straightforward conversion of the instructions and then `Invoke-Expression`. History: * 2011-02-13 22:24 (220) First attempt. * 2011-02-13 22:25 (218) `3e4` is shorter than `30000`. * 2011-02-13 22:28 (216) Unnecessary line breaks. Matching on integers instead of characters is shorter. * 2011-02-13 22:34 (207) Used indexes into a hash table instead of the `switch`. * 2011-02-13 22:40 (205) Better cast to string removes two parentheses. * 2011-02-13 22:42 (204) No need for a space after the argument to `Write-Host`. [Answer] ## F#: 489 chars The following program doesn't jump at '[' / ']' instructions, but scans the source code for the next matching token. This of course makes it kind of slow, but it can still find the primes under 100. F# integer types don't overflow but wrap. Here's the short version: ``` [<EntryPoint>] let M a= let A,B,i,p,w=Array.create 30000 0uy,[|yield!System.IO.File.ReadAllText a.[0]|],ref 0,ref 0,char>>printf"%c" let rec g n c f a b=if c then f i;if B.[!i]=a then g(n+1)c f a b elif B.[!i]=b then(if n>0 then g(n-1)c f a b)else g n c f a b while !i<B.Length do(let x=A.[!p]in match B.[!i]with|'>'->incr p|'<'->decr p|'+'->A.[!p]<-x+1uy|'-'->A.[!p]<-x-1uy|'.'->w x|','->A.[!p]<-byte<|stdin.Read()|'['->g 0(x=0uy)incr '['']'|']'->g 0(x>0uy)decr ']''['|_->());incr i 0 ``` A nasty gotcha was that the primes.bf program chokes on windows newlines. In order to run it I had to save the input number to a UNIX formatted text document and feed it to the program with a pipe: ``` interpret.exe prime.bf < number.txt ``` *Edit: entering Alt+010 followed by Enter also works in Windows* cmd.exe Here's the longer version: ``` [<EntryPoint>] let Main args = let memory = Array.create 30000 0uy let source = [| yield! System.IO.File.ReadAllText args.[0] |] let memoryPointer = ref 0 let sourcePointer = ref 0 let outputByte b = printf "%c" (char b) let rec scan numBraces mustScan adjustFunc pushToken popToken = if mustScan then adjustFunc sourcePointer if source.[!sourcePointer] = pushToken then scan (numBraces + 1) mustScan adjustFunc pushToken popToken elif source.[!sourcePointer] = popToken then if numBraces > 0 then scan (numBraces - 1) mustScan adjustFunc pushToken popToken else scan numBraces mustScan adjustFunc pushToken popToken while !sourcePointer < source.Length do let currentValue = memory.[!memoryPointer] match source.[!sourcePointer] with | '>' -> incr memoryPointer | '<' -> decr memoryPointer | '+' -> memory.[!memoryPointer] <- currentValue + 1uy | '-' -> memory.[!memoryPointer] <- currentValue - 1uy | '.' -> outputByte currentValue | ',' -> memory.[!memoryPointer] <- byte <| stdin.Read() | '[' -> scan 0 (currentValue = 0uy) incr '[' ']' | ']' -> scan 0 (currentValue > 0uy) decr ']' '[' | _ -> () incr sourcePointer 0 ``` [Answer] ## C, 333 characters This is my first BF interpreter and the first golf I actually had to debug. This runs the prime number generator on Mac OS X/GCC, but an additional `#include<string.h>` may be necessary at a cost of 19 more characters if the implicit definition of `strchr` doesn't happen to work on another platform. Also, it assumes `O_RDONLY == 0`. Aside from that, leaving `int` out of the declaration of `M` saves 3 characters but that doesn't seem to be C99 compliant. Same with the third `*` in `b()`. This depends on the particulars of ASCII encoding. The Brainfuck operators are all complementary pairs separated by a distance of 2 in the ASCII code space. Each function in this program implements a pair of operators. ``` #include<unistd.h> char C[30000],*c=C,o,P[9000],*p=P,*S[9999],**s=S,*O="=,-\\",*t; m(){c+=o;} i(){*c-=o;} w(){o<0?*c=getchar():putchar(*c);} b(){if(o>0)*c?p=*s:*--s;else if(*c)*++s=p;else while(*p++!=93)*p==91&&b();} int(*M[])()={m,i,w,b}; main(int N,char**V){ read(open(V[1],0),P,9e3); while(o=*p++) if(t=strchr(O,++o&~2)) o-=*t+1, M[t-O](); } ``` [Answer] ## C, 267 ``` #define J break;case char*p,a[40000],*q=a;w(n){for(;*q-93;q++){if(n)switch(*q){J'>':++p;J'<':--p;J'+':++*p;J'-':--*p;J'.':putchar(*p);J',':*p=getchar();}if(*q==91){char*r=*p&&n?q-1:0;q++;w(r);q=r?r:q;}}}main(int n,char**v){p=a+read(open(v[1],0),a,9999);*p++=93;w(1);} ``` Run as ./a.out primes.bf ## Ungolfed Version: ``` #define J break;case char*p,a[40000],*q=a; // packed so program immediately followed by data w(n){ for(;*q-93;q++){ // until ']' if(n)switch(*q){ // n = flagged whether loop evaluate or skip(0) J'>':++p; J'<':--p; J'+':++*p; J'-':--*p; J'.':putchar(*p); J',':*p=getchar(); } if(*q==91){char*r=*p&&n?q-1:0;q++;w(r);q=r?r:q;} // recurse on '[', record loop start } } main(int n,char**v){ p=a+read(open(v[1],0),a,9999); *p++=93; // mark EOF with extra ']' and set data pointer to next w(1); // begin as a loop evaluate } ``` [Answer] # C, 260 + 23 = 283 bytes I created a C program which can be found [here](http://phimuemue.com/?p=257). ``` main(int a,char*s[]){int b[atoi(s[2])],*z=b,p;char*c=s[1],v,w;while(p=1, *c){q('>',++z)q('<',--z)q('+',++*z)q('-',--*z)q('.',putchar(*z))q(',',*z =getchar())if(*c=='['||*c==']'){v=*c,w=184-v;if(v<w?*z==0:*z!=0)while(p) v<w?c++:c--,p+=*c==v?1:*c==w?-1:0;}c++;}} ``` Has to be compiled via `gcc -D"q(a,b)"="*c-a||(b);" -o pmmbf pmmbf.c` and can be called as follows: `pmmbf ",[.-]" 30000` whereby the first argument (quoted) contains the bf-program to run, the second determines how large the tape should be. [Answer] ## Delphi, 397 382 378 371 366 364 328 characters Eat this Delphi! ``` 328 var p,d:PByte;f:File;z:Word=30000;x:Int8;begin p:=AllocMem(z+z);d:=p+z;Assign(F,ParamStr(1));Reset(F,1);BlockRead(F,p^,z);repeat z:=1;x:=p^;case x-43of 1:Read(PChar(d)^);3:Write(Char(d^));0,2:d^:=d^+44-x;17,19:d:=d+x-61;48,50:if(d^=0)=(x=91)then repeat p:=p+92-x;z:=z+Ord(p^=x)-Ord(p^=x xor 6);until z=0;end;Inc(p)until x=0;end. ``` Here the same code, indented and commented : ``` var d,p:PByte; x:Int8; f:File; z:Word=30000; begin // Allocate 30000 bytes for the program and the same amount for the data : p:=AllocMem(z+z); d:=p+z; // Read the file (which path must be specified on the command line) : Assign(F,ParamStr(1)); Reset(F,1); BlockRead(F,p^,z); // Handle all input, terminating at #0 (better than the spec requires) : repeat // Prevent a begin+end block by preparing beforehand (values are only usable in '[' and ']' cases) : z:=1; // Start stack at 1 x:=p^; // Starting at '[' or ']' // Choose a handler for this token (the offset saves 1 character in later use) : case x-43of 1:Read(PChar(d)^); // ',' : Read 1 character from input into data-pointer 3:Write(Char(d^)); // '.' : Write 1 character from data-pointer to output 0,2:d^:=d^+44-x; // '+','-' : Increase or decrease data 17,19:d:=d+x-61; // '<','>' : Increase or decrease data pointer 48,50: // '[',']' : Start or end program block, the most complex part : if(d^=0)=(x=91)then // When (data = 0 and forward), or when (data <> 0 and backward) repeat // p:=p+92-x; // Step program 1 byte back or forward z:=z+Ord(p^=x) // Increase stack counter when at another bracket -Ord(p^=x xor 6); // Decrease stack counter when at the mirror char until z=0; // Stop when stack reaches 0 end; Inc(p) until x=0; end. ``` This one took me a few hours, as it's not the kind of code I normally write, but enjoy! Note : The prime test works, but doesn't stop at 100, because it reads #13 (CR) before #10 (LF)... do other submissions suffer this problem too when running on CRLF OSes? [Answer] # Python 2, 223 I admit that I recycled an old program of mine (but had to change it quite a bit, because the old version didn't have input, but error checking...). ``` P="";i,a=0,[0]*30000 import os,sys for c in open(sys.argv[1]).read():x="><+-.[,]".find(c);P+=" "*i+"i+=1 i-=1 a[i]+=1 a[i]-=1 os.write(1,chr(a[i])) while+a[i]: a[i]=ord(os.read(0,1)) 0".split()[x]+"\n";i+=(x>4)*(6-x) exec P ``` Runs the primes calculator fine. I see now that Alexandru has an answer that has some similarities. I'll post mny answer anyways, because I think there are some new ideas in it. [Answer] # [Desmos](https://www.desmos.com/calculator), 470 bytes Program input: * variable \$P\$, containing an array of ASCII codepoints representing the brainfuck program. * variable \$I\$, also containing an array of ASCII codes for stdin You can use [this program](https://tio.run/##NYw9DsMgDIV3TuERFOGlS1VRzpA9YqjyoyIlBhGWnJ7aSfokm89@z@SjfhM9nrm0tpS0wX7sELecSoW9TpFUD28YglpSgTXSDJEu46UAiL11Ji2G4VlCoyRkIQGAHj85zzTpVCY9GqNyiVR1b1rrbg3@3wWuciwbPJO33neDCzJ69NZavO9QAHnpLLqT7an7YeBL5P/wBw) to convert your ASCII to a list of numbers. Unless you like to play the waiting game, I would also recommend that you minify your program stdout is represented by the array \$O\$. Like \$P\$ and \$I\$, it is also an array of codepoints. In addition, you can inspect the memory tape in variable \$M\$. The memory consists of 30000 unsigned bytes, though it will only store as many bytes as necessary because storing 30000 bytes is not great for performance. To begin execution, run the "reset" action and then start the ticker. --- **Ticker code** ``` \left\{j<=P.length:c,a\right\} ``` **Expression list** ``` O=[] i=1 k=1 M=[0] s(x)=M->[\{l=p:\mod(x,256),M[l]\}\for l=[1...M.\length]] p=1 v=M[p] w=P[i] j=1 N=[] S=[] a=\{59<w<63:p->p+w-61,w=44:b,42<w<46:s(v+44-w),w=46:O->O.\join(v),w=91:i->\{v=0:N[i],i\}+1,w=93:i->\{v=0:i,N[i]\}+1\},\{w=62:\{30000>p>=M.\length:M->M.\join(0)\}\},\{\{w=91,w=93,0\}=0:i->i+1\} b=s(I[k]),k->k+1 c=\{P[j]=93:d,N->N.\join(0)\},\{P[j]=91:S->\join(j,S)\},j->j+1 d=N->[\{m=S[1]:j,m=j:S[1],N[m]\}\for m=[1...j]],S->S[2...] ``` [Try it on Desmos!](https://www.desmos.com/calculator/grk3m0wlem) The program loaded in the above TioD is a "Hello, World!" program. The prime number program took around five minutes to print `2 3 5` so I decided that maybe it wasn't the best idea to run it. --- **How it works** The interpreter first matches up bracket pairs, then scans through the program character-by-character and executes them. Below is the code for bracket-matching: ``` j=1 N=[] S=[] c=\{P[j]=93:d,N->N.\join(0)\},\{P[j]=91:S->\join(j,S)\},j->j+1 d=N->[\{m=S[1]:j,m=j:S[1],N[m]\}\for m=[1...j]],S->S[2...] ``` * \$j\$ is a list index, indicating that character \$P[j]\$ is currently being processed * \$N\$ holds the index of the matching bracket pair, if it exists. If \$N[i]\$ is a positive integer, then \$P[i]\$ matches with \$P[N[i]]\$. * \$S\$ is a stack containing the indices of all unmatched `[`s thus far. The top of the stack is at \$S[1]\$. Next there are two actions, \$c\$ and \$d\$. Every time action \$c\$ is run, the next character in the program is processed. ``` c=\{P[j]=93:d,N->N.\join(0)\},\{P[j]=91:S->\join(j,S)\},j->j+1 c= c is an action containing: \{ \}, a conditional... P[j]=93:d, that runs d if P[j]=93 (']') N->N.\join(0) and appends 0 to N otherwise \{ \}, a conditional... P[j]=91: that when P[j]=91 ('[')... S->\join(j,S) pushes j to S j->j+1 increment j ``` \$d\$ is the response to when a `']'` character is detected. Because it consists of two actions, it cannot be directly placed in the conditional and thus must be defined separately. ``` d=N->[\{m=S[1]:j,m=j:S[1],N[m]\}\for m=[1...j]],S->S[2...] d= d is an action consisting of: N->[\{ N[m]\}\for m=[1...j]], a modification to N m=S[1]:j, in which N[S[1]] is set to j m=j:S[1], and N[j] is set to S[1] S->S[2...] the topmost value is popped from S ``` Once bracket pairs are matched the expression is evaluated character-by-character: ``` i=1 k=1 M=[0] s(x)=M->[\{l=p:\mod(x,256),M[l]\}\for l=[1...M.\length]] p=1 v=M[p] w=P[i] a=\{59<w<63:p->p+w-61,w=44:b,42<w<46:s(v+44-w),w=46:O->O.\join(v),w=91:i->\{v=0:N[i],i\}+1,w=93:i->\{v=0:i,N[i]\}+1\},\{w=62:\{p=M.\length:M->M.\join(0)\}\},\{\{w=91,w=93,0\}=0:i->i+1\} b=s(I[k]),k->k+1 ``` * \$i\$ is the instruction pointer * \$k\$ is the next character to be read in stdout * \$M\$ is the memory tape * \$s(x)\$ sets the value of the current cell to \$x\$ * \$p\$ points to the current memory cell * \$v\$ is the value of the current cell * \$w\$ is the current instruction \$a\$ is an action that executes the next character. \$b\$ is a utility for reading from stdin - like \$d\$, \$b\$ is separated because conditional branches only support one action. \$a\$ is rather long, so here it is branch-by-branch: ``` a= \{ 59<w<63:p->p+w-61, ><: hack for p±±-ing; 6 bytes smaller than doing it separately w=44:b, ,: read from stdin (do this before +- to avoid interference) 42<w<46:s(v+44-w), +-: same hack w=46:O->O.\join(v), .: write to stdout w=91:i->\{v=0:N[i],i\}+1, [: jump to end if v=0 w=93:i->\{v=0:i,N[i]\}+1 ]: jump to start if v!=0 \}, \{w=62:\{p=M.\length:M->M.\join(0)\}\}, widen memory tape if necessary \{\{w=91,w=93,0\}=0:i->i+1\} increment instruction pointer if not '[' or ']' ``` Essentially \$a\$ is a big conditional that performs different actions for different characters, then ties up some loose ends afterwards. \$b\$, which reads from stdin, is relatively straightforward: ``` b=s(I[k]),k->k+1 b= b is an action that s(I[k]), writes the next character from stdin into memory k->k+1 and increments the character pointer for stdin ``` Finally, the exection of all of this is controlled by a ticker: ``` \left\{j<=P.length:c,a\right\} ``` This ticker will choose between \$a\$ and \$c\$ depending on whether the bracket matching is done or not. When the input program and stdin are set up and the ticker is run, this program should be able to interpret any brainfuck expression. Just maybe not in a reasonable time frame. [Answer] ## X86\_64/Linux Machine Code, 104 101 100 99 98 97 96 95 93 92 91 89 **Usage:** ``` $> gcc -s -static -nostartfiles -nodefaultlibs -nostdlib -Wl,-Tbss=0x7ffe0000 -DBF_IDEAL_BSS -Wl,--build-id=none bf.S -o bf $> ./bf <input> ``` #### Notes * Size is measured in machine code (i.e 89 bytes of `PROGBITS`; `.text`, `.data`, etc...) * `-9` bytes if reads input prog from stdin * `-4` more bytes without `BF_EXITCLEANLY` (it will segfault to exit). * `-2` more bytes with `BF_BALANCED` (assumes that over course of program data cell returns to start). * So minimum possible size **74** bytes. * **NOTE** Without the ideal bss setup (at address `0x7ffe0000` and `BF_IDEAL_BSS` defined as seen in compile command above) add `+2` bytes. ``` #define BF_LBRACE 91 #define BF_RBRACE 93 #define BF_DOT 46 #define BF_COMMA 44 #define BF_PLUS 43 #define BF_MINUS 45 #define BF_LSHIFT 60 #define BF_RSHIFT 62 #define BF_READFILE #define BF_EXITCLEANLY // #define BF_IDEAL_BSS // #define BF_BALANCED .global _start .text _start: /* All incoming registers at zero. */ /* Large read range. This may cause errors for huge programs (which will fail anyways). */ decl %edx #ifdef BF_READFILE /* open. */ movb $2, %al /* 3rd argument in rsp is first commandline argument. */ pop %rdi pop %rdi pop %rdi /* O_RDONLY is zero. */ syscall /* Error is okay, we will eventually just exit w.o executing. */ xchgl %eax, %edi /* Sets ESI at 2 ** 31. This is an arbitrary address > 65536 (minimum deref address on linux) < 2 ** 32 - PROG_SPACE (PROG_SPACE ~= 262144). We setup bss at 2 ** 31 - 131072 via linker script (-Tbss=0x7ffe0000). */ # ifdef BF_IDEAL_BSS bts %edx, %esi # else movl $(G_mem + 65536), %esi # endif /* bss initialized memory is zero. This is cheapest way to zero out eax. */ lodsl #else # ifdef BF_IDEAL_BSS bts %edx, %esi # else movl $(G_mem + 65536), %esi # endif #endif /* eax/edi are already zero which happens to match SYS_read/STDIN_FILENO. */ syscall /* Usage linux' pre-allocated stack for braces. */ /* Program code grows up. */ movl %esi, %ebx /* Assuming no errors, reach stores size in eax. Note errors or 0-byte reads are okay. The ebx is readable memory and zero- initialized (bss), so it its zero-length, it will just be an invalid op and we will hit bounds check below. If its error, eax is negative so ebx will be negative and likewise we will hit bounds check below. */ #ifdef BF_BALANCED addl %eax, %esi xchgl %eax, %ebp #else addl %esi, %eax xchgl %eax, %ebp movl %ebp, %esi #endif /* We have -1 in edx, so negative to get 1. 1 is needed in a variety of places. */ negl %edx run_program: /* Need to zero eax. */ movb (%rbx), %al incl %ebx /* %al contains the program "instruction". Its unique to one of 8 values so just test each in order. If instruction matches execute it then fallthrough (%al can only ever match one). We occasionally set al but are sure never to set it to the ASCII value of any of our 8 instructions. */ /* TODO: Brace handling could probably be smaller. */ try_lbrace: cmpb $BF_LBRACE, %al je do_lbrace try_rbrace: cmpb $BF_RBRACE, %al jne try_cont do_rbrace: /* Popping state (we might repush if we are looping back). */ pop %rdx pop %rdi /* Non-zero cell means loop. Note we have 1 cached in edx. */ cmpb %dl, (%rsi) jb next_insn movl %edi, %ebx do_lbrace: /* Restore loop state. */ push %rbx push %rdx /* If cell is zero, then we are skipping till RBRACE. Note we have 1 cached in edx. */ cmpb %dl, (%rsi) /* -1 if we want to start skipping. */ sbb %dh, %dh try_cont: orb %dh, %al /* we have set ah s.t its either zero or has a value that makes any further matches impossible. */ /* For the rest of the ops we take advantage of the fact that the ascii values of the pairs '<'/'>', '+'/'-', and '.',',' are all 2 apart. This allows use to test a pair with the following formula: `((al - PAIR_LO) & -3) == 0`. This will always leave the pair as 0/2 and will match only the pair. It turns out 0/2 are useful and can be used to do all the rest of the operations w.o extra branches. */ try_lshift: subb $BF_LSHIFT, %al testb $-3, %al jnz try_comma addl %eax, %esi decl %esi try_comma: try_dot: subb $(BF_PLUS - BF_LSHIFT), %al /* We have 0/1/2/3 for '+'/','/'-'/'.' so check if we remaining valid opcode. */ cmpb $3, %al ja next_insn /* 0/2 are '+'/'-' so check low bits. TODO: There may be a way to just care from `shr $1, %al' which would save us an instruction. But it messes up the '+'/'-' case. */ testb $-3, %al jz try_minus /* al is either 3/1. Shift by 1 to get 1/0 for our syscall number. */ shrb $1, %al // btsq $, %rax /* SYS_write == STDOUT_FILENO, SYS_read == STDIN_FILENO. */ movl %eax, %edi /* We already have 1 in rdx. */ syscall /* Assuming no io error, eax is 1. We will subtract 1 from eax in try_minus/try_plus so it will be +/- 0 which does nothing. */ try_minus: try_plus: /* If not coming from syscall eax is 0/2. 0 --> plus, 2 --> minus. So (rsi - eax + 1) translates. */ // setbe %cl subb %al, (%rsi) incb (%rsi) next_insn: #ifdef BF_BALANCED /* If BF_BALANCED is set, we assume that the program will have shifted back columns to start before exiting. */ cmpl %ebx, %esi #else cmpl %ebx, %ebp #endif jg run_program #ifdef BF_EXITCLEANLY /* eax has zero upper 24 bits so we can cheat and use movb here. (This isn't exact correct, assuming no IO errors on last instruction). */ movb $60, %al syscall #endif .section .bss .align 32 G_mem: .space(65536 * 4) ``` Edit: Just for fun, here a compliant **269** byte fully contained ELF file that implements brainfuck on Linux/X86\_64: Its possible to make this smaller. * We could take advantage of the known linux ELF impl and put code in known-unused fields. ``` 00000000 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 |.ELF............| 00000010 02 00 3e 00 01 00 00 00 b0 10 40 00 00 00 00 00 |..>.......@.....| 00000020 40 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |@...............| 00000030 00 00 00 00 40 00 38 00 02 00 00 00 00 00 00 00 |[[email protected]](/cdn-cgi/l/email-protection).........| 00000040 01 00 00 00 05 00 00 00 00 00 00 00 00 00 00 00 |................| 00000050 00 10 40 00 00 00 00 00 00 10 40 00 00 00 00 00 |..@.......@.....| 00000060 cd 00 00 00 00 00 00 00 cd 00 00 00 00 00 00 00 |................| 00000070 00 00 00 00 00 00 00 00 01 00 00 00 06 00 00 00 |................| 00000080 00 00 00 00 00 00 00 00 00 00 fe 7f 00 00 00 00 |................| 00000090 00 00 fe 7f 00 00 00 00 00 00 00 00 00 00 00 00 |................| 000000a0 00 00 04 00 00 00 00 00 20 00 00 00 00 00 00 00 |........ .......| 000000b0 ff ca b0 02 5f 5f 5f 0f 05 97 0f ab d6 ad 0f 05 |....___.........| 000000c0 89 f4 89 f3 01 c6 89 f5 f7 da 0f b6 03 ff c3 3c |...............<| 000000d0 5b 74 0c 3c 5d 75 0e 5a 5f 38 16 72 28 89 fb 53 |[t.<]u.Z_8.r(..S| 000000e0 52 38 16 18 f6 08 f0 2c 3c a8 fd 75 04 01 c6 ff |R8.....,<..u....| 000000f0 ce 2c ef 3c 03 77 0e a8 fd 74 06 d0 e8 89 c7 0f |.,.<.w...t......| 00000100 05 28 06 fe 06 39 dd 7f c1 b0 3c 0f 05 |.(...9....<..| 0000010d ``` [Answer] # [Recall](https://web.archive.org/web/20151007012840/http://www.minxomat.eu/introducing-recall), 594 bytes In short: Recall has no arithmetic operators in a classic sense, it only has bitwise operations. You can not just "add one" etc. Recall is also strictly stack-based. ``` DC505M22022M32032M606M42042M707M92092M4405022o032o06o042o07o092o044o1305022o06o042o092o52052q.q2305022o06o07o93093q.q5403206o07o14014q.q6403206o042o07o24024q.q74Yx34034z03MMMMMMMM034o3yY030401r3.4.101zyY040301r4.3.101zY01052gZ02Z040301052023s4.3.10zyY01023gZ02z030401023052s3.4.10zyY01093gZ02q20zyY01054gZ02u20zyY01014gZx20zyY01064gZ02X0zyY01024gZ03304302r33.43.20zyY01074gZ04303302r43.33.20zyyQ6205.8Y06208g6206208iZ08M808013izy062U7205.9Y07209g7207209iz09M909013izy072R53.63.82063MMMMMMMM053o63082013i53082KKKKKKKK82053063082S84.94.12.73.83t012073083TY083073012r83.73.12012084gzY012094gZt0zyy ``` --- ### Example 1: Print something Input: ``` -[--->+<]>-----..-[----->+<]>.++++.+[->++++<]>.---[----->++<]>.---.------------.++++++++.++++++++.+[-->+++++<]>-. ``` Output: ``` PPCG rocks! ``` --- ### Example 2: Output square numbers up to 100 Input: ``` +[>++<-]>[<+++++>-]+<+[>[>+>+<<-]++>>[<<+>>-]>>>[-]++>[-]+>>>+[[-]++++++>>>]<<<[[<++++++++<++>>-]+<.<[>----<-]<]<<[>>>>>[>>>[-]+++++++++<[>-<-]+++++++++>[-[<->-]+[<<<]]<[>+<-]>]<<-]<<-] ``` Output: ``` 0 1 4 9 16 25 36 49 64 81 100 ``` This example might take a few minuted to execute and might cause a "this tab is frozen" message. Ignore that and wait. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~273~~ 268 bytes ``` main(_,a){_=fopen("w.c","w");fputs("main(){char a[30000],*p=a;",_);x:a=getchar();fputs(a-62?a-60?a-43?a-45?a-46?a-44?a-91?a-93?~a?"":"}":"}":"while(*p){":"*p=getchar();":"putchar(*p);":"--*p;":"++*p;":"--p;":"++p;",_);if(~a)goto x;fclose(_);system("cc w.c;./a.out");}; ``` [Try it online!](https://tio.run/##RY/rjoMgEIVfxfAL1KHdtdtkC@KDGGIIUWvSFlJp7Ma0r@4OtpudwDecM9zGQm/tspzNcKFNbtjclJ3z7YWSiVuSk4kw0flbGClZ97DZHs01MXWxxdB56ksjSN4wcT@Ysm9DLNO/Mwb2nxVii9gVEV8R@4gd4vsjoqiepiLkQB7vOR2HU0tTz2YU@ML/tajx4lVgOUqA1MecZa8M8Jb@9a2ho0/DehdcchedPbmxpWiPP2Noz5RYm2Cjgm8Md7eAzT7EsmQ11FLWmACUjmuptVZKgVbA0eSK40BbApcZVzFWg6PxCw "C (gcc) – Try It Online") -5 thanks to ceilingcat Takes input from stdin. This relies a little bit on the environment, but is pretty consistent. This is effectively the eval solution for c. It writes an appropriate C program to the file w.c, compiles it, and runs it as the desired executable. Thus as a bonus effect this actually compiles the bf code and leaves `a.out` as a binary for it. Note that depending on the system you may need to modify the last string. In particular most windows c compilers call the default executable "a.exe". Luckily as far as I can tell, they all have the same length so the bytecount is the same. (though if you don't have a cc defined you may need to add a letter such as gcc to the compile command, adding 1 byte). *I am aware that this thread is a bit old, but I didn't see this style of C solution yet, so I thought I'd add it.* [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `DOb`, ~~54~~ ~~53~~ 50 bytes ``` `><+-][.,`£¥↔¥`‟„›‹}`f`{:|:C₴_¼`²JĿ?ṘƛC⅛;k23*(0)„Ė ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=DOb&code=%60%3E%3C%2B-%5D%5B.%2C%60%C2%A3%C2%A5%E2%86%94%C2%A5%60%E2%80%9F%E2%80%9E%E2%80%BA%E2%80%B9%7D%60f%60%7B%3A%7C%3AC%E2%82%B4_%C2%BC%60%C2%B2J%C4%BF%3F%E1%B9%98%C6%9BC%E2%85%9B%3Bk23*%280%29%E2%80%9E%C4%96&inputs=%2B%2B%2B%2B%2B%2B%2B%2B%5B%3E%2B%2B%2B%2B%5B%3E%2B%2B%3E%2B%2B%2B%3E%2B%2B%2B%3E%2B%3C%3C%3C%3C-%5D%3E%2B%3E%2B%3E-%3E%3E%2B%5B%3C%5D%3C-%5D%3E%3E.%3E---.%2B%2B%2B%2B%2B%2B%2B..%2B%2B%2B.%3E%3E.%3C-.%3C.%2B%2B%2B.------.--------.%3E%3E%2B.%3E%2B%2B.%2C.%2C.%2C.%0Aabc&header=&footer=) -4 thanks to Aaron Miller. The basic idea is that a stack is a wrapping tape if you can rotate the whole thing. So it's really just setting up the input, pushing 0s, and transpiling: * `>` - `‟` - rotate stack right * `<` - `„` - rotate stack left * `+` - `›` - increment the current item * `-` - `‹` - decrement the current item * `[` - `{:|` - set a while loop without popping the top * `]` - `}` - close a while loop * `.` - `:C₴` - Duplicate, make a char and output without a trailing newline * `,` - `_¼` - pop, then take a character from input `?ṘƛC⅛;` takes the input and pushes each character to the global array. Then `k23*(0)` pushes 30k zeroes, then `„Ė` runs the code! ]
[Question] [ ## **Challenge:** In the last stage of a two players [Texas hold 'em](http://en.wikipedia.org/wiki/Texas_hold_%27em), given a two-card hand and five cards on table, determine your probability to win versus an opponent by the [standard ranking of poker hands](http://en.wikipedia.org/wiki/List_of_poker_hands). ## **Input:** Seven cards (sdtin or arguments). The first two cards are your hand while the last five are on the table. Each card will be a two letter string of the form RS where R is rank and S is suit. The ranks range from 2-9, T for ten, and J, Q, K, and A for Jack, Queen, King, and Ace respectively. The suits are H, D, C, S for Hearts, Diamonds, Clubs, and Spades respectively. ## **Output:** The probability to win (stdout or return): from '0.00' to '1.00'. ## **Input to Output Examples:** ``` AH 7C KH QH JH TH 6C -> 1.00 ``` Explanation: You have a royal flush, 100% winning chances. ``` 9H 7C KH QH JH TH 6C -> 0.96 ``` Explanation: You have a straight flush, your opponent can only win with an AH, 95.6% winning chances. ## **Rules and Clarifications:** * There are 52 different cards. You can refer to Texas hold 'em to get the idea. * Your opponent has 2 unknown cards (out of 45 left). That's 990 possibilities with equal probability. * You are free to decide if Ties count or don't count in the calculation of the probability. * As this is code golf, the shortest answer wins. ]
[Question] [ The basic parts of [SMTP](http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol) can be implemented in surprising little code. I was able to build an example SMTP client that works with Gmail and Amazon SES [in about 320 characters using PHP](https://gist.github.com/Xeoncross/2002233#file-smtp_mail-php). Your task is to implement an SMTP client that can send UTF-8 email from at least 2 major providers listed here: * Gmail * Yahoo! * Live/Hotmail * Postmark * Amazon SES Keep in mind that most require SSL support. Some SMTP services (like Amazon) require different SMTP Auth and From addresses. Your function can take input for the actual data transmitted. After all, it woudn't make sense to hard-code anything into the transport layer. * SMTP User * SMTP Password * SMTP Host * SMTP Port * DATA (message) * From email * To email Sample DATA (message) ``` Subject: =?UTF-8?B?VGVzdCBFbWFpbA==?=\r\n To: <[[email protected]](/cdn-cgi/l/email-protection)>\r\n From: <[[email protected]](/cdn-cgi/l/email-protection)>\r\n MIME-Version: 1.0\r\n Content-Type: text/html; charset=utf-8\r\n Content-Transfer-Encoding: base64\r\n\r\n PGgxPlRlc3QgRW1haWw8L2gxPjxwPkhlbGxvIFRoZXJlITwvcD4=\r\n. ``` ### In Summary 1. Build an SMTP client that can send email through at least two of the services above. 2. Accepts the seven inputs needed to form a valid SMTP Auth request (above). (Might only need six inputs if you combine the "From" and "SMTP User" inputs). 3. Use as few characters as posible. [Answer] # Python 3 864 bytes Extremely quick and dirty. Works with AWS SES and Yahoo!. Could not get it to work with Postmark (requires STARTTLS) or Gmail (requires further authentication outside of the SMTP connection). ``` import socket,ssl from base64 import* N=b'\x00' U='utf-8' E=lambda s:s.encode(U) D=lambda b:b.decode(U) B=lambda s:D(b64encode(E(s))) A=lambda f,t,j,b:E('\r\n'.join(['DATA','Subject: =?UTF-8?B?{}?=','To: <{}>','From: <{}>','MIME-Version: 1.0','Content-Type: text/html; charset=utf-8','Content-Transfer-Encoding: base64',B(b),'','.','']).format(B(j),t,f,b)) X=lambda s,e:s.startswith(e) def S(h,u,p,t,f,j,b): c,F,W=ssl.wrap_socket(socket.create_connection((h,465))),lambda m:E(m if'amazonaws'in h else'<'+m+'>'),lambda m:c.write(m+b'\r\n') def R(d,o=[]): x,y=c.read(),str(d) if not(X(x,E(y))or filter(lambda i:X(i,X(x,E(y))),o)):raise RuntimeError(y+' '+repr(x)) R(220);W(b'EHLO x');R(250);W(b'AUTH PLAIN '+b64encode(N+E(u)+N+E(p)));R(235);W(b'MAIL FROM: '+F(f));R(250);W(b'RCPT TO: '+F(t));R(250);W(A(f,t,j,b));R(250,(354,));W(b'QUIT') ``` Invoke like `S(hostname, username, password, to, from_, subject, body)` Expect bugs and changes (kind of got bored so it feels slightly half-baked). [Answer] C# .NET, assuming all the proper namespaces have been imported and not counting newlines/whitespace as characters. Also, displays no output as it's used as a library function. ``` bool sm(string h, string u, string p, string r, string m) { try { SmtpClient smtp = new SmtpClient(); smtp.Port = 587; smtp.Host = h; smtp.Credentials = new NetworkCredential(u, p); smtp.UseSsl = true; smtp.Send(u, r, "", m); return true; } catch { return false; } } ``` In its compressed form, the way I would code it, it'd look like this: ``` bool sm(string h, string u, string p, string r, string m) { try { SmtpClient smtp = new SmtpClient(); smtp.Port = 587; smtp.Host = h; smtp.Credentials = new NetworkCredential(u, p); smtp.UseSsl = true; smtp.Send(u, r, "", m); return true; } catch { return false; } } ``` Call it cheating, because of using .NET, but 266 characters. Works with major providers that allow SMTP with STARTTLS authentication on port 587. I use this for my Gmail all the time, works with Windows Live Hotmail too. Can be used either client-side OR server-side, and requires .NET 2.0 or newer (so it's compatible with pretty much every Windows machine). ]
[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/15668/edit). Closed 8 years ago. [Improve this question](/posts/15668/edit) The challenge is to take any real number as input and output or return the absolute value. You may not use any built-in functions other than those dealing with input and output/returning. This is code golf, so the shortest code wins. This is my first question here, so bear with me if I've left something obvious out of the challenge. As per Quincunx's suggestion, I am limiting input to anywhere between -9E99 and 9E99. Also, the only functions/operators you can use are `input`, `output`, `return`, `+`, `-`, `*`, `/`, `%`, `^` `+=`, `-=`, `*=`, `/=`, `>`, `<`, `==`, `>=`, `<=`, `!=`, `square`, and `square root` or their equivalents [Answer] ## J, 2 bytes ``` ** ``` Usage: ``` f =: ** f 9.3 9.3 f -9.3 9.3 ``` **Explanation**: This uses the `*` verb in both its monadic and dyadic forms. The monadic form returns `-1` if it's given a negative number, `0` if it's given `0` and `1` if it's given a positive number. The dyadic form is just plain old multiplication. Putting them in a function literal turns them into a hook which gets evaluated like this: `y * (*y)`. [Answer] # GolfScript, 4 characters I believe I win. ;) Works with integer or decimal numbers of any length. ``` '-'/ ``` [Try it online](http://golfscript.apphb.com/?c=ICAnLTU4LjI3JwoKJy0nLw%3D%3D) These programs do the same and are of equal length: ``` '-'- ``` ``` '-'% ``` # GolfScript (old version), ~~16~~ 13 My first GS program! ([that actually does something](https://codegolf.stackexchange.com/a/13155/3808)) Doesn't work with decimal numbers because GolfScript doesn't have floating point. ``` ~:$0<{0$-}$if ``` [Answer] ## Perl: 5 characters ``` s/-// ``` The example: ``` perl -e '$_=-82.923; s/-//; print' # will print 82.923 or return it unless use 'print' ``` [Answer] # C - 21 ``` #define x(a) a<0?-a:a ``` This is a preprocessor macro, but does the same thing as Quincunx's Java solution when a real number is used as input. [Answer] ## J - 7 3 **Max of number and inverse (3)** ``` >.- ``` When assigned to a function: take the maximum between the negative and the number, using a hook so: (f g) y = y f g y ``` f=:>.- f _4 5 _1 0 4 5 1 0 ``` **root of the square (5 or 4)** ``` ]&.*: _4 5 _1 0 4 5 1 0 NB. or if an expression is good enough: %:*: _4 5 _1 0 4 5 1 0 ``` **Negate if number smaller than its negative (7)** ``` -^:(<-) ``` Takes the inverse (the inverse is bigger than the number itself) times. Would loosely translate to: ``` if -num > num then num= -num end ``` [Answer] # Brainfuck, 40 chars ``` +++++[>+++++++++<-],[->->+<<]>[>.>],[.,] ``` Or **35 chars** if [wrapping](http://esolangs.org/wiki/Brainfuck#Memory_and_wrapping) is allowed. ``` -[+>+[+<]>+],+[->->+<<]>[>-.>],[.,] ``` [Answer] # Mathematica ~~10~~ 8 **Method 1** (8 chars) Take the square root of a number squared. Sqrt@#²& Examples ``` Sqrt@#²&[-.0176987] Sqrt@#²&[.0176987] ``` > > .0176987 > > .0176987 > > > --- **Method 2** (8 chars) `Sign` returns -1 if negative, 0 if zero, 1 if positive. ``` # Sign@#& ``` Examples ``` # Sign@#&[-4.3] # Sign@#&[4.3] ``` > > 4.3 > > 4.3 > > > --- **4 chars?** As the following picture shows, it is possible to legitimately reduce the function, but I haven't been able to replicate the input on SO. ![abs value](https://i.stack.imgur.com/xfpfr.png) [Answer] ## APL, 5 ``` ×∘×⍨⎕ ``` A function would be **4 chars** ``` ×∘×⍨ ``` **Explanation** `×`, when used with one argument, is the [signum function](http://en.wikipedia.org/wiki/Signum_function); when used with two arguments, is multiplication. `∘` is the compose(combination) of two functions. `×∘×` is a function that takes two arguments and return the left argument times the signum of the right arugment. `⍨` means "use right argument as both left and right argument". `⎕` takes input from screen. [Answer] # C: 13 characters I would assume using overloaded operators are not permitted? Just because something is abstracted and doesn't follow the standard formatting of a function call doesn't mean it isn't a function. For example: (\*\*)n <==> abs(n) <==> '-'/ Anyways, here is my code: With explanation: n+: ==> +(true - false) ==> +(1-0) ==> +1 n-: ==> -(false - true) ==> -(0-1) ==> -(-1) ==> +1 ``` a=n*(n>0 - (n<0)) ``` [Answer] ## Python CLI, 20 ``` lambda x:[x,-x][x<0] ``` [Answer] **Haskell, 14 characters** ``` sqrt.flip(^)2$ ``` [Answer] # J, 13 Without using build-in functions (like signum and the like): ``` f =: -`]@.(0&<) f -1.253 1.253 f 0.91235 0.91235 ``` [Answer] # Python 2.7 (16 charcters) This one is the shortest here in python. ``` (input()**2)**.5 ``` Let n = `input()`, then ![equation](https://i.stack.imgur.com/LqGQj.png) [Answer] EXCEL, 10: ``` =SQRT(n^2) ``` -- n is a defined cell name with the input value. [Answer] # TI-Basic, 3 bytes Outputs square root of input squared. ``` √(Ans² ``` Alternates ``` √(AnsAns 3 bytes Ans²^.5 5 bytes max(Ans,-Ans 5 bytes Anscos(angle(Ans 5 bytes -min(Ans,-Ans 6 bytes If Ans<0:-Ans 7 bytes Ans-2Ans(Ans<0 8 bytes Ans(2(Ans>0)-1 10 bytes Ans(-1+2(Ans>0 10 bytes ``` [Answer] # Python - ~~31~~ ~~28~~ ~~26~~ ~~24~~ ~~23~~ 18 Uses boothby's idea of a lambda function, saving 5 characters (or 3 if I need to assign it to a variable): ``` lambda x:(x*x)**.5 ``` --- # Old Methods Uses a generator function to save 1 char, so it is necessary to print the value with some function that uses a generator/iterator, like `for i in a(b):print(i)` ``` def a(b):yield(b*b)**.5 ``` Saved ~~2~~ 3 characters by squaring and unsquaring. --- ``` def a(b):yield(b<0)*-2*b+b ``` Old one: ``` def a(b):yield b if b>0 else-b ``` Edit: saved two characters by factoring `b` in. [Answer] # C, 19 Slightly more than some other C answers, but guaranteed branch-less. the `f` variable is a `float`. I hope the bitwise operator `&` is allowed. ``` *(int*)&f&=INT_MAX; ``` Inspired from <http://devmaster.net/posts/9998/the-ultimate-fast-absolute-value> [Answer] # JavaScript 26 13 `alert((b=prompt())<0?-b:b)` Reducing it further with fat arrow functions... `a=b=>b<0?-b:b` Et voila! Reduction by 50%! Only issue is that this now only works for Firefox 22 and above with thanks to the fat arrows... [Answer] ## Seriously, ~~8~~ ~~7~~ ~~4~~ 3 bytes Thanks @quintopia My first Seriously answer, to a 2 yr old question! Note the challenge is older than the language ``` ,ª√ ``` Seriously is a stack based language. What this does is it pushes the input on the stack, then multiplies if with itself. Then it takes the square root of the result. It is based on the fact that sqrt(x^2)=|x|. [Answer] # Java - 36 This is the obvious solution. ``` double a(double b){return b<0?-b:b;} ``` [Answer] # Ruby, 15 characters ``` a=->b{b>0?b:-b} ``` # Ruby, 22 chars (with I/O) ``` p (a=gets.to_f)>0?a:-a ``` Accepts input on stdin, outputs on stdout [Answer] # Befunge 98 - ~~11~~ ~~7~~ 8 ``` ~:'-`!j, ``` Explained: ``` ~ read character input : duplicate '- fetch - and push it ` compare duplicated value with it, 1 if first is greater, otherwise 0 ! if the number on the stack is 0, set it to 1, otherwise 0 j jump the number of characters on the top of the stack, which is 1 if the input character is - , print the character on top of the stack ``` If I understand [this](http://quadium.net/funge/spec98.html) correctly, then this works for any input, but only if constant looping is allowed. It simply prints everything but the minus sign. If infinite looping is not allowed, then this should work (~~13~~ 10 chars (Thanks FireFly)): ``` ~:'-`!j,#@ ``` --- Old version (Befunge 93) - 11 ``` &:0`2*1-*.@ ``` It works like this: ``` & push input : push a duplicate 0 push a zero ` pop duplicate and 0, if duplicate greater than 0, push 1 else 0 2 push a two * pop the 1 or 0 and 2 , multiply the 1 or 0 by the 2 1 push a one - pop last two values and subtract the second value on the stack by the first (ie a-1) * pop last two values and multiply last two values on stack (ie + or - 1 * input) . print @ end program ``` Note: Only integers are valid numbers in Befunge. --- If I need to support floating point input, then it is **18** chars: ``` &&\:0`2*1-*.".",.@ ``` It is **17** chars in **Befunge 98**: ``` &&\:0`2*1-*.'.,.@ ``` Note: these print a space before the decimal point [Answer] # Clojure 13 ~~18~~ chars ``` #(max %(- %)) ``` ~~i am not sure if max is allowed, but i have seen others use it so here it goes :)~~ after the debate in the comments below, it was decided that max is indeed allowed! use it like that: ``` (#(max %(- %)) -2) ; returns 2 ``` --- ~~edit - it seems max isnt allowed, so lets resort to the trivial solution~~ a trivial solution: ``` #(if(< % 0)(- %)%) ``` or ``` #((if(< % 0)- +)%) ``` [Answer] # C# 6.0, 29 bytes ``` double m(double n)=>n<0?-n:n; ``` [Answer] # MATLAB, 10 bytes ``` @(a)a^2^.5 ``` Pretty straight forward. We are allowed `sqauare` and `square root`, so the absolute value of a number (assuming it is not complex!) is simply square it then square root it. [Answer] ## Burlesque, 4 bytes ``` XXim ``` `XX` returns the digits of an integer and `im` converts the digits back to an integer. `XX` removes the sign. You might also go with `Jsn?*` depending on the exact types. [Answer] # Prolog, 22 bytes Saves 7 bytes over printing as we were allowed to return the absolute value. **Code:** ``` p(X,Y):-Y is(X^2)^0.5. ``` **Explanation:** Input **X** is squared, taken the root of and returned as **Y**. **Example:** ``` p(-9.0e99,X). X = 9.0e+99 ``` [Answer] # [Milky Way 1.1.5](https://github.com/zachgates7/Milky-Way), 13 bytes ``` ':0e?{_^_;-}! ``` --- ### Explanation ``` ' # read input from the command line : # push a duplicate of the TOS to the stack 0 # push 0 to the stack e # push the truth value of A > B where A and B are the top two stack elements ?{_ _ } # if-else statement ^ # pop the TOS without outputting ; # swap the top two stack elements - # push the value of A - B where A and B are the top two stack elements ! # output the TOS ``` --- ### Usage ``` ./mw <path-to-code> -i <input-integer> ``` [Answer] # PHP, 30 ``` <?=($n=$argv[1])*(1-($n<0)*2); ``` [Answer] # Gema, 2 characters Same as [edem](https://codegolf.stackexchange.com/users/10880/edem)'s [Perl answer](https://codegolf.stackexchange.com/a/15693). ``` -= ``` Sample run: ``` bash-4.3$ gema -p '-=' <<< '-82.923' 82.923 ``` ]
[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/5291/edit). Closed 6 years ago. [Improve this question](/posts/5291/edit) I was wondering how one might go and produce a program that takes input from some kind of random source and uses it to produce constant output. An obvious way is, for example, to take an integer x and output x/x for 1, but that isn't too clever, is it? Therefore, the task is to write a program that outputs the same thing, no matter which input is given to it. **Specifications** * The program may assume that the input is either a number or a one line string (that is, valid characters are [a-z][A-z][0-9] and spaces). If you adopt one of those restrictions, specify which in your answer. * The program must use the entered input in some way. To put it more formally, the contents of the variable that takes the input must be used afterwards in some calculation that affects the final variable to be printed. The winner will be the most upvoted solution. [Answer] **Python** This question is boring. I'd rather sleep. ``` from time import sleep sleep(input()) ``` Input a number. [Answer] ## GolfScript ``` ~{.3*){.2%}{2/}until.@=!}do ``` This program will take a positive integer as input, and will output `1` unless the input is a counterexample to the [Collatz conjecture](http://en.wikipedia.org/wiki/Collatz_conjecture). While the Collatz conjecture remains an open problem, it is [known](http://www.ieeta.pt/~tos/3x+1.html) that there are no counterexamples below 5 × 260. [Answer] **Perl** ``` <>/0 ``` produces for any input string: ``` Illegal division by zero at test5.pl line 1, <> line 1. ``` [Answer] # Ruby ``` def a(x) 4 end ``` I somehow felt [this](http://xkcd.com/221/) was related: ![enter image description here](https://i.stack.imgur.com/iD9ua.png) [Answer] ## Python ``` n=input() p=37 print (n**p-n)%p ``` Takes an integer input, and always outputs 0. Uses [Fermat's little theorem](http://en.wikipedia.org/wiki/Fermat%27s_little_theorem), which states that n^p == n mod p. [Answer] ## J ``` = ``` Usage: ``` =10 1 ``` Always outputs 1. Or how about an unhappy smiley verb: ``` {:0[ ``` Usage: ``` {:0[ 147 0 ``` Always ouputs 0. [Answer] # C This program reads an integer from stdin and then prints that integer, right? ``` main() { int i; printf("%d\n", scanf("%d", &i)); } ``` Well, no. It just prints `1`. The input must be an integer though (otherwise it may output `0` or `-1`), which proves that the program "uses" the input. [Answer] ## Javascript ``` var input = ~~prompt("Input an integer!"); if(Math.abs(input)<=Math.pow(2,31)) console.log("It's too small! (not bigger than 2^31 = "+Math.pow(2,31)+")"); else console.log("It's quite big!"); ``` Though JS can represent any integer between ±9,007,199,254,740,992, it will *always* print > > It's too small! (not bigger than 2^31 = 2147483648) > > > because bitwise operation is performed in range of 32bit. [Answer] ## Python 2 ``` x=input() print x^x ``` Only accepts integers. always outputs `0` by `xor`ing itself [Answer] **Ruby:** ``` p !gets ``` Always outputs `false`. `gets` takes user input, `!` negates that and since strings are truthy, the result will be `false`. [Answer] ## APL ``` ⍴⍣≡ ``` `⍴` is the *shape* function, `⍴⍣≡` is the fixpoint of the shape function. All APL values have a shape. Say, a 4x6x8 array has shape `4 6 8`; a scalar (like `3`) has shape `⍬` (no dimensions). Therefore, `⍴` always returns a one-dimensional list. This means that applying the output of `⍴` to `⍴` will always get you a one-dimensional list with one number in it. *That* means that applying `⍴` *again* will always get you a one-dimensional list with the number `1` in it. Therefore, `⍴` converges to `1`; therefore `⍴⍣≡` will give `1` for all possible inputs. [Answer] ## Golfscript ``` .= ``` Accepts any input and always prints `1`. [Answer] **Python** ``` def f(x): return 0*x ``` [Answer] **JavaScript** ``` var input = prompt("Input something!"); console.log(new Number(input) === 1); ``` Will always return `false`, even with the input `1` [Answer] ## Golfscript (4 chars) ``` ~1\? ``` Accepts an integer. Outputs 1. [Answer] # Perl ``` $a=<>+1;for(1..length$a){$a=length$a}print$a ``` This program does use the input number, and it always prints 1. [Answer] ## Python ``` print float("inf")*sum(map(ord,raw_input())) ``` Always returns 'infinity'. [Answer] # Q Returns 1. Where no parameters are declared, Q implicitly uses x,y& z where appropriate. I think this satisfies the second condition... ``` {1} ``` [Answer] ## Python `print input()*0` [Answer] ## Python This one works for numbers only. I can't prove that it works for all numbers (can anyone?), but it prints "False" for all cases I've tested. EDIT: Fixed a bug in the last line. ``` p=lambda x:x>1 and (i*i>x for i in xrange(2,x+1) if x%i==0 or i*i>x).next() q=lambda x:(i<x for i in xrange(2,x+1) if p(i) and p(x-i) or i==x).next() x = input() print x%2==0 and x>2 and not q(x) ``` Explanation (for those who think my Python code is unclear): `p(x)` tells you if x is a prime. `q(x)` looks for two primes, whose some is x. The program prints True if the number is even, greater than 2 and not the sum of 2 primes. Please tell me if you find such a number. [Answer] ## C Produces 1 (prints and returns) for every input. (Input being the number of command line args) ``` j;main(c){j=0;while(c){j+=c%2;c/=2;}return j^1?main(j):printf("%d",j);} ``` This program does the same `#error 1` but cannot properly speaking be said to take input (unless you count the rest of the program after as input). [Answer] # Python ``` print eval('42#'+raw_input()) ``` Accepts any input [Answer] # PostScript This function takes one argument of any type, actively discards, and will always output `­`, unless you didn't supply it with enough arguments (which I am going to define as being undefined behavior for this function), depending on the value of the argument. Here is its implementation: ``` /f {pop} def ``` This function will always take one more argument than is currently on the stack, so it will always output a `stackunderflow` error, depending on the input. ``` /f {clear pop} def ``` And here is a third, even more useful function, which I will define as having undefined behavior, depending on the number, types, and values of the arguments. Here is its implementation: ``` ­ ``` [Answer] Common Lisp ``` (unless (read)) ``` Always returns nil (unless you crash it with stupid input) [Answer] # Clojure ``` (and(read-line)0) ``` Crudely equivalent to the prior common lisp submission, except that it makes no attempt to ensure that the line "read" is valid in any way shape or form. Compiled or interpreted, this program will read a single line and exit 0 in all cases. [Answer] ## Game Maker Language ``` if argument0 return argument0/argument0 else return argument0 ``` It can be any script, just call `script(argument)` - it returns `true` if the number is not 0, else it returns `false` If this was code golf, it would be `if argument0 a=1 return a` which is **25 characters** when compiled with the option "Treat all uninitialized variables as value 0". [Answer] ## Brainf\*\*k Since the question is self-contradictory it's hard to give a serious answer, so here it is: ``` ,[[->+<],]>[<->+<+>--<+>][->+>+[-]>+>+<<<<][->-<]+>[<->[-]]>[->--<----]+>[[---<->+<+>-]<->]>>[+>-<--]+>[[-]<->]<<[->-<-->+++>>>>>+<<<->+<<<+++++[>>++++++<<]]+>[<+>-]++>+<-<->>>>+<<<<->+<+>->>>[<]>[>]<[<[->-<]+>[<->[-]]<]+[>+>+>+>+<<---<<[-]]>>++<<[>>+[+<<<-]>>-<[<]+<<[<<->+]]>[->>+<<]>>[->+<]>[>+++++++++++<-]>[->+>+>+<<<]>[.>] ``` Accepts any string or number as input, always outputs "!!!". Have fun figuring out what it does. [Answer] # C++ Accepts any input. Prints ASCII equivalent of each character entered: ``` #include <iostream> #include <string> using namespace std; int main() { string s; cout << "Enter a string: "; cin >> s; cout << "ASCII characters of input:\n"; for (int i = 0; i < s.size(); i++) cout << s[i] << ": " << int(s[i]) << endl; return 0; } ``` [Answer] # Befunge ``` &@ ``` always returns nothing. --- And a less pointless version: ``` &>:v - ^1_.@ ``` Always returns 0 ]
[Question] [ There are 10 types of people in the world, those who understand binary and those who do not. Where are you? Let's see! # Challenge Your task is to convert a decimal integer to binary, only using a set of arithmetic operators (+, -, \*, / and %). You can use conditional statements, loops and variables. (No bitwise operator/No Builtin methods or function). # Input A decimal integer. # Output The binary number. # Examples ``` 2 -> 10 6 -> 110 etc... ``` The shortest code wins. [Answer] # [Python 2](https://docs.python.org/2/), 30 bytes ``` f=lambda n:n and n%2+10*f(n/2) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIc8qTyExL0UhT9VI29BAK00jT99I839BUWZeiUKahpnmfwA "Python 2 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 28 bytes ``` f=x=>x?x%2+10*f((x-x%2)/2):x ``` [Try it online!](https://tio.run/##DclLCsIwAAXAvafoRkj0tealfyV15SnERamNH0oirUhuH7sbmHf/65dhfn2@qfP3MVoTg@nCOWz1nmpnhQjpannQ8hji6aqRo0CJCjUatKACCWowBwuwBCuwBhuwhV5Xqdsms36@9MNTuMR0yeDd4qcxm/xDWOGklPEP "JavaScript (Node.js) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~50~~ ~~27~~ 26 bytes ``` f(n){n=n?n%2+10*f(n/2):n;} ``` [Try it online!](https://tio.run/##LYtBCsIwFET3OcVQCOTblLaBujBWD1K7kNZIFv2VmpWhZ48R3MzM4zFT9ZymlJxiitzzlaUp2@aQuTZ0Yrun5e5ZURTwHBCGET2i0UfdNtp03W4F3LpB/axH39icZ7z957E6Faj@r6zJoiw9CQCvLbNThZxRXSDnGxc6DH7UyJ/cRFbs6Qs "C (gcc) – Try It Online") [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 141 bytes ``` [S S S T N _Push_1][S N S _Dupe_1][T N T T _Read_STDIN_as_integer][T T T _Retrieve_input][S N S _Dupe_input][N S S N _Create_Label_LOOP][S N S _Dupe_top][N T S S N _If_0_Jump_to_Label_LOOP2][S S S T N _Push_1][T S S T _Subtract][S N T _Swap_top_two][S N S _Dupe_top][S S S T S N _Push_2][T S T T _Modulo][S N T _Swap_top_two][S S S T S N _Push_2][T S T S _Integer_divide][S T S S T S N _Copy_0-based_2nd][N S N N _Jump_to_Label_LOOP][N S S S N _Create_Label_LOOP2][S N T _swap_top_two][S S S T N _Push_1][S N S _Dupe_1][T T T _Retrieve_input][T S S T _Subtract][T S S S _Add][N T S T N _If_0_Jump_to_Label_DONE][S S S T S T S N _Push_10][T S S N _Multiply][T S S S _Add][N S N S N _Jump_to_Label_LOOP2][N S S T N _Create_Label_DONE][T N S T _Print_as_integer_to_STDOUT] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online](https://tio.run/##NU1RCoBQCPt2p9gZ3o0iHrz@goKOb26WyNxwzmcd97zObZ@ZJANEQagobkBoalskJKWahfEX7EbdQB58S8cqU37a6sA@a5M/wV/KnDnGCw) (with raw spaces, tabs and new-lines only). Funny thing is, is that I can use everything Whitespace has to offer for this challenge. So even if builtins were allowed, this would still be the approach to use, since Whitespace has none. ;) **Explanation in pseudo-code:** ``` Integer input = read STDIN as integer Integer index = input Integer b = input Start LOOP: If(index == 0): Jump to LOOP2 index = index - 1 Integer a[index] = b[previous_index] modulo-2 Integer b[index] = b[previous_index] integer-divided by 2 Go to next iteration of LOOP Start LOOP2: If(index+1 == input): Jump to DONE a = a + b*10 Go to next iteration of LOOP2 Label DONE: Print a as integer to STDOUT (stop program implicitly with an error) ``` **Example run: [`input = 6`](https://tio.run/##NU1RCoBQCPt2p9gpus8jHtRf8IKOb26WyNxwzuc477musc9MkgGiIFQUNyA0tS0SklLNwvgLdqNuIA@@pWOVKT9tdWCftcmf4C9lztxe)** ``` Command Explanation Stack Heap STDIN STDOUT SSST Push 1 [1] SNS Duplicate top (1) [1,1] TNTT Read STDIN as integer [1] {1:6} 6 TTT Retrieve input from heap [6] {1:6} SNS Duplicate top (6) [6,6] {1:6} NSSN Create Label LOOP [6,6] {1:6} SNS Duplicate top (6) [6,6,6] {1:6} NTSSN If 0: Jump to Label LOOP2 [6,6] {1:6} SSSTN Push 1 [6,6,1] {1:6} TSST Subtract (6-1) [6,5] {1:6} SNT Swap top two [5,6] {1:6} SNS Duplicate top (6) [5,6,6] {1:6} SSSTSN Push 2 [5,6,6,2] {1:6} TSTT Modulo (6%2) [5,6,0] {1:6} SNT Swap top two [5,0,6] {1:6} SSSTSN Push 2 [5,0,6,2] {1:6} TSTS Integer-divide (6//2) [5,0,3] {1:6} STSSTSN Copy 0-based 2nd (5) [5,0,3,5] {1:6} NSNN Jump to Label LOOP [5,0,3,5] {1:6} SNS Duplicate top (5) [5,0,3,5,5] {1:6} NTSSN If 0: Jump to Label LOOP2 [5,0,3,5] {1:6} SSSTN Push 1 [5,0,3,5,1] {1:6} TSST Subtract (5-1) [5,0,3,4] {1:6} SNT Swap top two [5,0,4,3] {1:6} SNS Duplicate top (3) [5,0,4,3,3] {1:6} SSSTSN Push 2 [5,0,4,3,3,2] {1:6} TSTT Modulo (3%2) [5,0,4,3,1] {1:6} SNT Swap top two [5,0,4,1,3] {1:6} SSSTSN Push 2 [5,0,4,1,3,2] {1:6} TSTS Integer-divide (3//2) [5,0,4,1,1] {1:6} STSSTSN Copy 0-based 2nd (4) [5,0,4,1,1,4] {1:6} NSNN Jump to Label LOOP [5,0,4,1,1,4] {1:6} SNS Duplicate top (4) [5,0,4,1,1,4,4] {1:6} NTSSN If 0: Jump to Label LOOP2 [5,0,4,1,1,4] {1:6} SSSTN Push 1 [5,0,4,1,1,4,1] {1:6} TSST Subtract (4-1) [5,0,4,1,1,3] {1:6} SNT Swap top two [5,0,4,1,3,1] {1:6} SNS Duplicate top (1) [5,0,4,1,3,1,1] {1:6} SSSTSN Push 2 [5,0,4,1,3,1,1,2] {1:6} TSTT Modulo (3%2) [5,0,4,1,3,1,1] {1:6} SNT Swap top two [5,0,4,1,3,1,1] {1:6} SSSTSN Push 2 [5,0,4,1,3,1,1,2] {1:6} TSTS Integer-divide (1//2) [5,0,4,1,3,1,0] {1:6} STSSTSN Copy 0-based 2nd (3) [5,0,4,1,3,1,0,3] {1:6} NSNN Jump to Label LOOP [5,0,4,1,3,1,0,3] {1:6} SNS Duplicate top (3) [5,0,4,1,3,1,0,3,3] {1:6} NTSSN If 0: Jump to Label LOOP2 [5,0,4,1,3,1,0,3] {1:6} SSSTN Push 1 [5,0,4,1,3,1,0,3,1] {1:6} TSST Subtract (3-1) [5,0,4,1,3,1,0,2] {1:6} SNT Swap top two [5,0,4,1,3,1,2,0] {1:6} SNS Duplicate top (0) [5,0,4,1,3,1,2,0,0] {1:6} SSSTSN Push 2 [5,0,4,1,3,1,2,0,0,2] {1:6} TSTT Modulo (0%2) [5,0,4,1,3,1,2,0,0] {1:6} SNT Swap top two [5,0,4,1,3,1,2,0,0] {1:6} SSSTSN Push 2 [5,0,4,1,3,1,2,0,0,2] {1:6} TSTS Integer-divide (0//2) [5,0,4,1,3,1,2,0,0] {1:6} STSSTSN Copy 0-based 2nd (2) [5,0,4,1,3,1,2,0,0,2] {1:6} NSNN Jump to Label LOOP [5,0,4,1,3,1,2,0,0,2] {1:6} SNS Duplicate top (2) [5,0,4,1,3,1,2,0,0,2,2] {1:6} NTSSN If 0: Jump to Label LOOP2 [5,0,4,1,3,1,2,0,0,2] {1:6} SSSTN Push 1 [5,0,4,1,3,1,2,0,0,2,1] {1:6} TSST Subtract (2-1) [5,0,4,1,3,1,2,0,0,1] {1:6} SNT Swap top two [5,0,4,1,3,1,2,0,1,0] {1:6} SNS Duplicate top (0) [5,0,4,1,3,1,2,0,1,0,0] {1:6} SSSTSN Push 2 [5,0,4,1,3,1,2,0,1,0,0,2] {1:6} TSTT Modulo (0%2) [5,0,4,1,3,1,2,0,1,0,0] {1:6} SNT Swap top two [5,0,4,1,3,1,2,0,1,0,0] {1:6} SSSTSN Push 2 [5,0,4,1,3,1,2,0,1,0,0,2] {1:6} TSTS Integer-divide (0//2) [5,0,4,1,3,1,2,0,1,0,0] {1:6} STSSTSN Copy 0-based 2nd (1) [5,0,4,1,3,1,2,0,1,0,0,1] {1:6} NSNN Jump to Label LOOP [5,0,4,1,3,1,2,0,1,0,0,1] {1:6} SNS Duplicate top (1) [5,0,4,1,3,1,2,0,1,0,0,1,1] {1:6} NTSSN If 0: Jump to Label LOOP2 [5,0,4,1,3,1,2,0,1,0,0,1] {1:6} SSSTN Push 1 [5,0,4,1,3,1,2,0,1,0,0,1,1] {1:6} TSST Subtract (1-1) [5,0,4,1,3,1,2,0,1,0,0,0] {1:6} SNT Swap top two [5,0,4,1,3,1,2,0,1,0,0,0] {1:6} SNS Duplicate top (0) [5,0,4,1,3,1,2,0,1,0,0,0,0] {1:6} SSSTSN Push 2 [5,0,4,1,3,1,2,0,1,0,0,0,0,2] {1:6} TSTT Modulo (0%2) [5,0,4,1,3,1,2,0,1,0,0,0,0] {1:6} SNT Swap top two [5,0,4,1,3,1,2,0,1,0,0,0,0] {1:6} SSSTSN Push 2 [5,0,4,1,3,1,2,0,1,0,0,0,0,2] {1:6} TSTS Integer-divide (0//2) [5,0,4,1,3,1,2,0,1,0,0,0,0] {1:6} STSSTSN Copy 0-based 2nd (0) [5,0,4,1,3,1,2,0,1,0,0,0,0,0] {1:6} NSNN Jump to Label LOOP [5,0,4,1,3,1,2,0,1,0,0,0,0,0] {1:6} SNS Duplicate top (1) [5,0,4,1,3,1,2,0,1,0,0,0,0,0,0] {1:6} NTSSN If 0: Jump to Label LOOP2 [5,0,4,1,3,1,2,0,1,0,0,0,0,0] {1:6} NSSSN Create Label LOOP2 [5,0,4,1,3,1,2,0,1,0,0,0,0,0] {1:6} SNT Swap top two [5,0,4,1,3,1,2,0,1,0,0,0,0,0] {1:6} SSSTN Push 1 [5,0,4,1,3,1,2,0,1,0,0,0,0,0,1] {1:6} SNS Duplicate top (1) [5,0,4,1,3,1,2,0,1,0,0,0,0,0,1,1] {1:6} TTT Retrieve input from heap [5,0,4,1,3,1,2,0,1,0,0,0,0,0,1,6] {1:6} TSST Subtract (1-6) [5,0,4,1,3,1,2,0,1,0,0,0,0,0,-5] {1:6} TSSS Add (0+-5) [5,0,4,1,3,1,2,0,1,0,0,0,0,-5] {1:6} NTSTN If 0: Jump to Label DONE [5,0,4,1,3,1,2,0,1,0,0,0,0] {1:6} SSSTSTSN Push 10 [5,0,4,1,3,1,2,0,1,0,0,0,0,10] {1:6} TSSN Multiply (0*10) [5,0,4,1,3,1,2,0,1,0,0,0,0] {1:6} TSSS Add (0+0) [5,0,4,1,3,1,2,0,1,0,0,0] {1:6} NSNSN Jump to Label LOOP2 [5,0,4,1,3,1,2,0,1,0,0,0] {1:6} SNT Swap top two [5,0,4,1,3,1,2,0,1,0,0,0] {1:6} SSSTN Push 1 [5,0,4,1,3,1,2,0,1,0,0,0,1] {1:6} SNS Duplicate top (1) [5,0,4,1,3,1,2,0,1,0,0,0,1,1] {1:6} TTT Retrieve input from heap [5,0,4,1,3,1,2,0,1,0,0,0,1,6] {1:6} TSST Subtract (1-6) [5,0,4,1,3,1,2,0,1,0,0,0,-5] {1:6} TSSS Add (0+-5) [5,0,4,1,3,1,2,0,1,0,0,-5] {1:6} NTSTN If 0: Jump to Label DONE [5,0,4,1,3,1,2,0,1,0,0] {1:6} SSSTSTSN Push 10 [5,0,4,1,3,1,2,0,1,0,0,10] {1:6} TSSN Multiply (0*10) [5,0,4,1,3,1,2,0,1,0,0] {1:6} TSSS Add (0+0) [5,0,4,1,3,1,2,0,1,0] {1:6} NSNSN Jump to Label LOOP2 [5,0,4,1,3,1,2,0,1,0] {1:6} SNT Swap top two [5,0,4,1,3,1,2,0,0,1] {1:6} SSSTN Push 1 [5,0,4,1,3,1,2,0,0,1,1] {1:6} SNS Duplicate top (1) [5,0,4,1,3,1,2,0,0,1,1,1] {1:6} TTT Retrieve input from heap [5,0,4,1,3,1,2,0,0,1,1,6] {1:6} TSST Subtract (1-6) [5,0,4,1,3,1,2,0,0,1,-5] {1:6} TSSS Add (1+-5) [5,0,4,1,3,1,2,0,0,-4] {1:6} NTSTN If 0: Jump to Label DONE [5,0,4,1,3,1,2,0,0] {1:6} SSSTSTSN Push 10 [5,0,4,1,3,1,2,0,0,10] {1:6} TSSN Multiply (0*10) [5,0,4,1,3,1,2,0,0] {1:6} TSSS Add (0+0) [5,0,4,1,3,1,2,0] {1:6} NSNSN Jump to Label LOOP2 [5,0,4,1,3,1,2,0] {1:6} SNT Swap top two [5,0,4,1,3,1,0,2] {1:6} SSSTN Push 1 [5,0,4,1,3,1,0,2,1] {1:6} SNS Duplicate top (1) [5,0,4,1,3,1,0,2,1,1] {1:6} TTT Retrieve input from heap [5,0,4,1,3,1,0,2,1,6] {1:6} TSST Subtract (1-6) [5,0,4,1,3,1,0,2,-5] {1:6} TSSS Add (2+-5) [5,0,4,1,3,1,0,-3] {1:6} NTSTN If 0: Jump to Label DONE [5,0,4,1,3,1,0] {1:6} SSSTSTSN Push 10 [5,0,4,1,3,1,0,10] {1:6} TSSN Multiply (0*10) [5,0,4,1,3,1,0] {1:6} TSSS Add (1+0) [5,0,4,1,3,1] {1:6} NSNSN Jump to Label LOOP2 [5,0,4,1,3,1] {1:6} SNT Swap top two [5,0,4,1,1,3] {1:6} SSSTN Push 1 [5,0,4,1,1,3,1] {1:6} SNS Duplicate top (1) [5,0,4,1,1,3,1,1] {1:6} TTT Retrieve input from heap [5,0,4,1,1,3,1,6] {1:6} TSST Subtract (1-6) [5,0,4,1,1,3,-5] {1:6} TSSS Add (3+-5) [5,0,4,1,1,-2] {1:6} NTSTN If 0: Jump to Label DONE [5,0,4,1,1] {1:6} SSSTSTSN Push 10 [5,0,4,1,1,10] {1:6} TSSN Multiply (1*10) [5,0,4,1,10] {1:6} TSSS Add (1+10) [5,0,4,11] {1:6} NSNSN Jump to Label LOOP2 [5,0,4,11] {1:6} SNT Swap top two [5,0,11,4] {1:6} SSSTN Push 1 [5,0,11,4,1] {1:6} SNS Duplicate top (1) [5,0,11,4,1,1] {1:6} TTT Retrieve input from heap [5,0,11,4,1,6] {1:6} TSST Subtract (1-6) [5,0,11,4,-5] {1:6} TSSS Add (4+-5) [5,0,11,-1] {1:6} NTSTN If 0: Jump to Label DONE [5,0,11] {1:6} SSSTSTSN Push 10 [5,0,11,10] {1:6} TSSN Multiply (11*10) [5,0,110] {1:6} TSSS Add (1+10) [5,110] {1:6} NSNSN Jump to Label LOOP2 [5,110] {1:6} SNT Swap top two [110,5] {1:6} SSSTN Push 1 [110,5,1] {1:6} SNS Duplicate top (1) [110,5,1,1] {1:6} TTT Retrieve input from heap [110,5,1,6] {1:6} TSST Subtract (1-6) [110,5,-5] {1:6} TSSS Add (5+-5) [110,0] {1:6} NTSTN If 0: Jump to Label DONE [110] {1:6} NSSTN Create Label DONE [110] {1:6} TNST Print as integer to STDOUT [] {1:6} 110 ``` Stops with an error after printing the result, because no exit is defined. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` F2‰`s}΃T*+ ``` Fixed with help of *@Grimmy*. [Try it online](https://tio.run/##yy9OTMpM/f/fzehRw4aE4trDfccmhWhp//9vBgA) or [verify the first \$[0,25]\$ inputs](https://tio.run/##yy9OTMpM/W9kemySn72SwqO2SQpK9n4u/92MHjVsSCiuNfA7NilES/t/rc5/AA). **Explanation:** ``` F # Loop the (implicit) input-integer amount of times: 2‰ # Take the divmod-2 ([n//2, n%2]) of the top value on the stack # (which will be the (implicit) input-integer in the very first iteration) `s # Push them separated to the stack, and swap their order }Î # After the loop: push 0 and the input to the stack ƒ # Loop the input+1 amount of times: T* # Multiply the top value by 10 + # And add the top two values together # (after which it is output implicitly as result) ``` [Answer] # [Perl 5](https://www.perl.org/) `-Minteger -p`, 32 bytes ``` $\+=$_%2*10**$i++,$_/=2while$_}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lRttWJV7VSMvQQEtLJVNbW0clXt/WqDwjMydVJb62@v9/Y8N/@QUlmfl5xf91fTPzSlLTU4v@6xbkAAA "Perl 5 – Try It Online") Uses no concatenation. If concatenation is allowed, it would get a little shorter: ### 26 bytes ``` $\=$_%2 .$\,$_/=2while$_}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lxlYlXtVIQU8lRkclXt/WqDwjMydVJb62@v9/Q7N/@QUlmfl5xf91fTPzSlLTU4v@6xbkAAA "Perl 5 – Try It Online") [Answer] # [PHP](https://php.net/), ~~45~~ ~~44~~ 43 bytes ``` for(;$a=&$argn>=1;$a/=2)$n=$a%2 .$n;echo$n; ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVEm3VVBKL0vPsbA2BHH1bI02VPFuVRFUjBT2VPOvU5Ix8IPX/v4nRv/yCksz8vOL/um4A "PHP – Try It Online") As the output is a string, it supports up to `PHP_INT_MAX` integers Thanks to @MariaMiller for saving 1 byte! Thanks to @GuillermoPhillips for the reference assignment trick! [Answer] # [Ruby](https://www.ruby-lang.org/), 26 bytes ``` f=->n{n>0?n%2+10*f[n/2]:n} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y6vOs/OwD5P1Ujb0EArLTpP3yjWKq/2f4FCWrRZ7H8A "Ruby – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 12 bytes Longer than 05AB1E because MathGolf doesn't have divmod ... ``` _{2‼%/}k{♂*+ ``` [Try it online!](https://tio.run/##y00syUjPz0n7/z@@2uhRwx5V/drs6kczm7S0//83NAUA "MathGolf – Try It Online") # Explanation ``` _ We have to copy the input because MathGolf outputs 0 over an empty stack. { } Do that input times: ‼%/ "Moddiv" 2 by 2 (This saves the swapping of the stack) k Repeat input times: {♂* Multiply TOS by 10 + And add second-to-top ``` # [MathGolf](https://github.com/maxbergmark/mathgolf), 10 bytes If only concatenation is allowed. MathGolf cleverly avoids the leading zeroes, unlike 05AB1E which doesn't. ``` _{2‼%/}]yx ``` [Try it online!](https://tio.run/##y00syUjPz0n7/z@@2uhRwx5V/drYyor//w1NAQ "MathGolf – Try It Online") # Explanation ``` _ We have to copy the input because MathGolf outputs 0 over an empty stack. {2‼%/} Mod-div by 2 input times over input ] Wrap whole stack into a list y Join the list into a number x Reverse the number, removing leading zeroes Anyway, the old 05AB1E answer used it, so I guess it's valid... ``` [Answer] # [Erlang (escript)](http://erlang.org/doc/man/escript.html), 36 bytes Port of various answers. ``` b(0)->0;b(N)->N rem 2+10*b(N div 2). ``` [Try it online!](https://tio.run/##Sy3KScxL100tTi7KLCj5z/U/ScNAU9fOwDpJww9I@ykUpeYqGGkbGmgBBRRSMssUjDT1/ucmZuZpRMdqKujaKWTmW5UXZZakaiRpmGkC5QA "Erlang (escript) – Try It Online") # [Erlang (escript)](http://erlang.org/doc/man/escript.html), 37 bytes Outputs a list of integers; it's longer by 1 byte anyway with concatenation ... ``` b(0)->[];b(N)->b(N div 2)++[N rem 2]. ``` [Try it online!](https://tio.run/##Sy3KScxL100tTi7KLCj5z/U/ScNAU9cuOtY6ScMPyACSCimZZQpGmtra0X4KRam5Ckaxev9zEzPzNKJjNRV07RQy863KizJLUjWSNMw0NfX@AwA "Erlang (escript) – Try It Online") [Answer] # [PHP](https://php.net/), 55 bytes ``` for($p=2**32;$p=$p/2%$p;)echo($f+=$v=$argn/$p%2)?$v:''; ``` [Try it online!](https://tio.run/##DcZLCoAgEADQy4z4iRAm3GTirntEZLbRwcLjN7V5PMrES6TfVJsCCmjMhP4PkEUB5PWx56ogDQF6gK2dxQIJ1BH6LKVndu6t9Fy13DyuHw "PHP – Try It Online") If concatenation is allowed, then see the other PHP answer by @Kaddath. **How** Take digits starting from most significant bit, which is leftmost. To strip leading zeroes, just accumulate the bit values until it goes above 0, then start displaying. Doesn't work for zero! Not sure if I'm allowed to have the power (\*\*) operator? [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 50 bytes ``` >,[[->>>+<[-<+>>-]>[-<+>>]<<<<]+>>[-<<+>>]<]<[-.<] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v/fTic6WtfOzk7bJlrXRtvOTjfWDsKItQGCWCADyIXwY4FK9Gxi///nAgA "brainfuck – Try It Online") (with 10 as input)... Or [try this naïve version with human-readable output](https://tio.run/##SypKzMxLK03O/v/fTic6WtfOzk7bJlrXRtvOTjfWDsKItQGCWG1SgR1IO0R/LNBIPZvY//@5AA), where I just added 48 + signs by hand, so that you guys can read the output. How it works: Reads the input and does the following, iteratively: * divide by 2, finding quotient and remainder * save the remainder + 1 on the left (this will make it easier to retrace the binary representation later) * move the tape right and repeat with this quotient as the new input Then we walk left, printing the remainders, by first decreasing them by 1 to restore their real value. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 26 bytes ``` {[R~] ($_,*div 2...^0)X%2} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzo6qC5WQUMlXkcrJbNMwUhPTy/OQDNC1aj2f3FipUKagqHBfwA "Perl 6 – Try It Online") Uses concatenation, as well as some questionable interpretations of `loop`s for `[R~]`, `...` and `X`. [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ©u +A*ßUz ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=qXUgK0Eq31V6&input=Ng) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` HḞпṖḂṚḞ ``` [Try it online!](https://tio.run/##y0rNyan8/9/j4Y55hycc2v9w57SHO5oe7pwF5P///9/EFAA "Jelly – Try It Online") A monadic link taking an integer and returning a list of binary digits. ## Explanation ``` Ḟп | While the current value converted to integer (by flooring) is non-zero, do the following, collecting up intermediate values: H | - Halve Ṗ | Remove last Ḃ | Mod 2 Ṛ | Reverse list Ḟ | Convert to integer ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 26 bytes ``` 1_(*:){(-2 2!\:*x),1_x}/,: ``` [Try it online!](https://ngn.codeberg.page/k#eJxLszKM19Cy0qzW0DVSMFKMsdKq0NQxjK+o1dex4uLS5zLiMuMyNDI24Yrh4rIKsUrwVDGO16iJsTSy1bJS14w3sEpILEovUzDk4kpTD+HiAgDG0BHF) [Answer] ## Pascal, 160 B This is a complete `program` according to ISO standard 7185 “Standard Pascal” using your standard [Horner scheme](https://en.wikipedia.org/wiki/Horner_scheme) recursively. ``` program p(input,output);var n:integer;procedure p(n:integer);begin if n>1 then p(n div 2);write(n mod 2:1)end;begin read(n);if n<0 then write('-');p(abs(n))end. ``` Ungolfed: ``` program changeBaseDecimalToBinary(input, output); var n: integer; procedure convert(n: integer); begin if n > 1 then begin convert(n div 2) end; { Print in reverse order. ----------------------------------- } { The `:1` specifies the _minimum_ width. If omitted, a processor-defined default is inserted. This would potentially cause ugly spaces between digits. } write(n mod 2:1) end; { === MAIN ====================================================== } begin read(n); { In Extended Pascal you would write `write('−':ord(n < 0))`. } if n < 0 then begin write('−') end; convert(abs(n)) end. ``` ]
[Question] [ Use any programming language to generate two random digits between 1 and 9 (including both). Then your program should display: * in the first line: the first random digit, * in the second line: the second random digit, * in the third line: a number whose tens and units digits are the first and second random digits respectively, * in the fourth line: the number from the third line raised to the power of 2. For example, if digits "9" and "2" were generated, your program should display exactly: ``` 9 2 92 8464 ``` [Answer] # [R](https://www.r-project.org/), ~~48~~ 47 bytes ``` cat(x<-sample(9,2,T),y<-x%*%c(10,1),y^2,fill=1) ``` [Try it online!](https://tio.run/##K/r/PzmxRKPCRrc4MbcgJ1XDUsdIJ0RTp9JGt0JVSzVZw9BAxxDIjTPSScvMybE11Pz/HwA "R – Try It Online") Thanks to J.Doe for golfing down a byte. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ 13 bytes *-1 Byte from @Oliver* ``` 2ÆÒ9ö pU¬Uì ² ``` --- ``` 2ÆÒ9ö pU¬Uì ² Full program ----------------------------------------- 2Æ Range [0,2) and map 9ö Random number in range [0, 9) Ò increased by 1 This result is assigned to U p Push into U U¬ Elements in U joined Uì ² and elements joined squared Implicit output each element separated with new line -R ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=MsbSOfYKcFWsVewgsg==&input=LVI=) [Answer] # Vim, 43 bytes ``` :%!$RANDOM :s/0//g 2f:y2hVpo*<C-r>*=*<C-r>*0**<C-r>*0 *<Esc>*kYPa ``` [Try it online!](https://tio.run/##K/v/30pVUSXI0c/F35eLy6pY30BfP53LKM2q0igjrCBfyFbIQEvIgEs6OzIgkev/fwA "V – Try It Online") Not the right tool for the job. This produces *most likely* the desired output Step by step: * `:%!$RANDOM` `Enter` `Enter` Produces a string like `/bin/bash: 25266: command not found` * `:s/0//g` removes all zeroes * `2f:y2hVp` moves the cursor to the colon after the number, copy the last two digits and replace the entire string with those * `o` `Ctrl`+`R` `=` `Ctrl`+`R` `0*` `Ctrl`+`R` `0` `Enter` add a new line and evaluate an expression. In this case, I'll multiply the number in register 0 (the one that was just copied) with itself. * `Esc` `kYPa` `Enter` Copy the upper line and paste it above. The cursor ends up in the first line, on the first character. Now we just have to append a line break to it Limitations: If the result of `$RANDOM` is a number with less than two non-zero digits, this will not produce the desired output [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~68~~ 67 bytes *-1 byte thanks to cleblanc* ``` f(r){r=rand()%81*10/9+11;printf("%d\n%d\n%d\n%d",r/10,r%10,r,r*r);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9No0izusi2KDEvRUNT1cJQy9BA31Lb0NC6oCgzryRNQ0k1JSYPgZV0ivQNDXSKVEGETpFWkaZ17X@gQoXcxMw8DU2Fai7OYrBZJZm5qRoGmprWXJxpGiCyKLWktChPwcCaq/Y/AA "C (gcc) – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 28 bytes ``` t:2?10;t,:10/t;$t,:t[2]*t[2] ``` **Explanation** ``` t:2?10 //define t as two random numbers from 1-10 t,:10/t //join the base 10 joining of the elements of t to t t,:t[2]*t[2]//join the square of the index 2 element to t $ //String each element of the result (to output on newlines) ``` [Try it online!](https://tio.run/##y9bNz/7/v8TKyN7QwLpEx8rQQL/EWgXIKIk2itUCEf//AwA "K (oK) – Try It Online") **Cleaner Output, 32 bytes** ``` t:2?10;t,:10/t;`0:$t,:t[2]*t[2]; `0: //Cleanly prints the strings ``` [Try it online!](https://tio.run/##y9bNz/7/v8TKyN7QwLpEx8rQQL/EOsHASgXILok2itUCEdb//wMA "K (oK) – Try It Online\"") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 39 bytes ``` {.comb,$_,$_²}([~] roll 1..9: 2)>>.put ``` [Try it online!](https://tio.run/##K0gtyjH7/79aLzk/N0lHJR6IDm2q1Yiui1Uoys/JUTDU07O0UjDStLPTKygt@f8fAA "Perl 6 – Try It Online") [Answer] # JavaScript (ES6), 67 bytes ``` f=_=>(n=Math.random()*90+10|0)%10?(n/10|0)+` ${n%10} ${n} `+n*n:f() ``` [Try it online!](https://tio.run/##HYhJDkAwFED3zkHyq1G1JCkncAZtzML/UmKDs9ewesNkDrPVdlz3CKlpnetUpXJAVZp9ENZgQwuwMJU8kZdkQSILwPh3rj3/xPfcH29Pcwwx64C5mnCjuRUz9fA2cw8 "JavaScript (Node.js) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 14 bytes ``` ^ i, hO9 hO9T2 ``` Note that the newlines are significant. Try it online [here](https://pyth.herokuapp.com/?code=%5E%0Ai%2C%0AhO9%0AhO9T2&debug=0). Explanation, with newlines replaced with ¶ character: ``` ^¶i,¶hO9¶hO9T2 Implicit: T=10 O9 Choose a random number in [0-9) h Increment ¶ Output with newline - value printed is yielded as expression result ¶hO9 Do the above again , Wrap the two previous results in a two-element array i T Convert to decimal from base 10 ¶ Output with newline ^ 2 Square the previous result, implicit print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes ``` 9ṗ2XṄ€ḌṄ² ``` [Try it online!](https://tio.run/##y0rNyan8/9/y4c7pRhEPd7Y8alrzcEcPkHFo0///AA "Jelly – Try It Online") ### How it works ``` 9ṗ2XṄ€ḌṄ² Main link. No arguments. 9 Set the return value to 9. ṗ2 Promote 9 to [1, ..., 9] and take the second Cartesian power, yielding [[1, 1], [1, 2], ..., [9, 8], [9, 9]]. X Pseudo-randomly select one of the pairs. Ṅ€ Print each integer in the pair, followed by a newline. Ḍ Undecimal; convert the integer pair from base 10 to an integer. Ṅ Print the integer, followed by a newline. ² Take the square. (implicit) Print the last return value. ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 41 bytes ``` puts [(a=11+10*rand(81)/9)/10,a%10,a,a*a] ``` [Try it online!](https://tio.run/##KypNqvz/v6C0pFghWiPR1tBQ29BAqygxL0XDwlBT31JT39BAJ1EVROgkaiXG/v8PAA "Ruby – Try It Online") [Answer] # T-SQL, 142 105 115 114 96 78 bytes ``` DECLARE @ int=RAND()*9+1,@a int=RAND()*9+1SELECT @,@a,10*@+@a,POWER(10*@+@a,2) ``` *-37 bytes: Realized I could just use two different random numbers and use the first digits from each!* *+10 bytes: Edited to meet requirements of range from 1-9, instead of 0-9* *-1 byte: Changed RIGHT() to LEFT() in @b* *-18 bytes: Various changes suggested by [BradC](https://codegolf.stackexchange.com/questions/175006/numbers-manipulation-challenge/175026#comment421745_175026)* *-18 bytes: More changes suggested by [BradC](https://codegolf.stackexchange.com/questions/175006/numbers-manipulation-challenge/175026?noredirect=1#comment421762_175026)* Ungolfed: ``` -- Setting RAND() separately in these produces different numbers. -- [RAND() * b + a] sets the range for a random number, from a to b inclusive. -- Declaring as an int removes the numbers after the decimal. DECLARE @ int = RAND() * 9 + 1, @a int = RAND() * 9 + 1 SELECT @, -- first random digit @a, -- second random digit 10 * @ + @a, -- multiply first digit by ten, and add second POWER(10 * @ + @a, 2) -- third digit squared ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~83~~ 76 bytes -5 bytes thanks to nwellnhof. ``` from random import* k=randint(9,89)*10//9+1 [*map(print,[k//10,k%10,k,k*k])] ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehKDEvBUhl5hbkF5VocWXbggQy80o0LHUsLDW1DA309S21DbmitXITCzQKioAyOtHZ@vqGBjrZqiBCJ1srO1Yz9v9/AA "Python 3 – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~48~~ 45 bytes ``` ($a,$b=1..9*2|Random -c 2) ($x="$a$b") +$x*$x ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0MlUUclydZQT89Sy6gmKDEvJT9XQTdZwUiTS0OlwlZJJVElSUmTS1ulQkul4v9/AA "PowerShell – Try It Online") Concatenates two ranges `1..9` together, pipes that to `Get-Random` with a `-c`ount of `2` to pull out two elements, stores them into `$a` and `$b`, and encapsulates that in parens to place a copy of them on the pipeline. Next we string concatenate `$a$b` and store it into `$x`, again placing in parens to put a copy on the pipeline. Finally we take `$x` squared and leave it on the pipeline. All the results are gathered from the pipeline and an implicit `Write-Output` gives us newlines between elements for free. *Saved 3 bytes thanks to mazzy.* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2F9LΩ=}J=n, ``` -3 bytes thanks to *@Emigna*. [Try it online.](https://tio.run/##yy9OTMpM/f/fyM3S59xK21ov2zyd//8B) **Explanation:** ``` 2F } # Loop 2 times: 9LΩ # Create a list in the range [1,9], and pick a random element from it = # Output it (without popping it from the stack) J # Join them together = # Output it (without popping it from the stack) n # Take it to the power of 2 , # And output it as well ``` --- **11 bytes alternative:** ``` 9LãΩ©`®JDn» ``` [Try it online.](https://tio.run/##yy9OTMpM/f/f0ufw4nMrD61MOLTOyyXv0O7//wE) **Explanation:** ``` 9L # List in the range [1,9] ã # Cartesian product with itself: [[1,1],[1,2],[1,3],...,[9,7],[9,8],[9,9]] Ω # Take a random element from it © # Store it in the register (without popping) ` # Pop and push both items as separated items onto the stack ® # Retrieve the list of digits from the register again J # Join them together to a single 2-digit number Dn # Duplicate it, and take the power of 2 of the copy » # Merge all values on the stack by newlines (and output implicitly) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` ≔⭆²⊕‽⁹θ↓θθ⸿IXIθ² ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU8juKQoMy/dN7FAw0hHwTMvuSg1NzWvJDVFIygxLyU/V8NSU1NTR6FQ05orAKiwRMPKJb88D1kAwVKKKVKCc5wTi0s0AvLLU4sgzEKgKUZAs6z///@vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⭆²⊕‽⁹θ ``` Generate two random characters in the range `1` to `9`. ``` ↓θ ``` Output them downwards i.e. on separate lines. ``` θ⸿ ``` Output them horizontally on their own line. ``` IXIθ² ``` Cast to integer, square, cast back to string for implicit print. [Answer] # Java 8, ~~99~~ ~~98~~ ~~90~~ ~~81~~ 80 bytes ``` v->{int i=81;i*=Math.random();return(i=i*10/9+11)/10+"\n"+i%10+"\n"+i+"\n"+i*i;} ``` -8 bytes after being inspired by [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/175015/52210). -9 bytes thanks to *@nwellnhof*. [Try it online.](https://tio.run/##PY7BisJADIbvPkUQhJkWW@emDN03sBdhL7qH7LRq3Gkq07SwSJ@9O2WLlyR/Qvi@Bw64fVQ/k/PYdXBE4tcKgFjqcEVXQzlHgJME4hs49dlSBYO2cTuuYukEhRyUwFDANGw/XvEXqNgbS0lxRLlnAblqG6VtqKUPrKigxOzyQ2qMzs0uXV94ndLmPS0tITtOdmY8@28fGQtqmA2aKKr@pc5fgHqx/O2kbrK2l@wZT@JZceYU997rRXmc/gA) **Explanation:** ``` v->{ // Method with empty unused parameter and no return-type int i=81;i*=Math.random();// Create a random integer `i` in the range [0,81) return(i=i*10/9+11) // Set `i` to 10 times `i`, integer-divided by 9, and 11 added /10+"\n" // Return the first digit of `i`, a newline, +i%10+"\n" // the last digit of `i`, a newline, +i+"\n" // `i` itself, a newline, +i*i;} // and `i` multiplied by itself // All concatted to each other ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~84~~ 75 bytes ``` from random import* k=randint(9,89)*10/9+1 for x in k/10,k%10,k,k*k:print x ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocWXbggQy80o0LHUsLDW1DA30LbUNudLyixQqFDLzFLL1DQ10slVBhE62VrZVQRFQrULF//8A "Python 2 – Try It Online") --- Saved * -1 bytes, thanks to Erik the Outgolfer * -8 bytes, thanks to nwellnhof [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 130 129 109 98 bytes ``` var r=new Random();int a=r.Next(1,10),b=r.Next(1,10),c=a*10+b;Console.Write($"{a} {b} {c} {c*c}"); ``` [Try it online!](https://tio.run/##VcexDsIgEADQX7k0DlBrU2bCYDrroIPz9UoMSQsJh1VD@HbU0eENj/hAIdr6YOfvcH1zsqsGWpAZjpCBEyZHsAU3wwmdFxJy3TBCNN4@4YJ@DquQ2vkEaGJ/tq8kVKcG2U3/JYOtGvaTHoPnsNj@Fl2yYtdkLJCnL/ppqTRS11LqBw "C# (.NET Core) – Try It Online") *-1 byte: edited console output to use wildcards (thanks to [Logern](https://codegolf.stackexchange.com/users/36046/logern))* *-20 bytes: changed* `r` *to* `var` *from* `Random`*, changed format of* `c`*; fixed* `r.Next()` *operators (thanks to [LiefdeWen](https://codegolf.stackexchange.com/users/68917/liefdewen))* *-11 bytes: changed format of* `c` *(thanks to [user51497](https://codegolf.stackexchange.com/users/82625/user51497))* Ungolfed: ``` var r = new Random(); // initializes random number generator int a = r.Next(1, 10), // gets random number between 1 and 9 inclusive b = r.Next(1, 10), // gets random number between 1 and 9 inclusive c = a * 10 + b; // concatenates a and b into one two-digit number Console.Write($"{a} {b} {c} {c*c}"); // writes a, b, c, and c^2 to the console ``` [Answer] # TI-BASIC, 27 bytes ``` 11+int(89rand Disp iPart(.1Ans),10fPart(.1Ans),Ans,Ans² ``` (can generate a 0 in the 2nd random number) Uses kamoroso94's Disp layout, but makes use of TI-BASIC integer compression. Generating the 2 random integers as a single compressed integer and extracting them via iPart and fPart allows for shaving several bytes. It's possible to generate the random integers seperately in the same number of bytes by creating them simultaneously in a list: ``` 1+int(9rand(2 ``` But the repeated calls to the list via Ans(1) and Ans(2) end up taking many more bytes than the integer compression technique. It's also important to note that rand is generally advisable over randInt( for random integer generation as they either use equivalent bytes, or rand will be shorter when the lower bound is 0, and rand has the added flexibility of list generation. [Answer] # [PHP](https://php.net/), 64 bytes ``` <?$d=($c=(10*($a=rand(1,9))+$b=rand(1,9)))*$c;echo"$a $b $c $d"; ``` [Try it online!](https://tio.run/##K8go@P/fxl4lxVZDJdlWw9BAS0Ml0bYoMS9Fw1DHUlNTWyUJiaeppZJsnZqcka@kksilksSlksylkqJk/f//v/yCksz8vOL/unkA "PHP – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 43 bytes ``` 100* L$` $.` A`0 G?`.. \*\L`. .. $.($&*$&* ``` [Try it online!](https://tio.run/##K0otycxLNPz/n8vQwECLy0clgUtFL4HLMcGAy90@QU@PK0YrxidBjwvIUtHTUFHTAqL//wE "Retina – Try It Online") Explanation: ``` 100* L$` $.` ``` Count from 0 to 99. ``` A`0 ``` Delete multiples of 10. ``` G?`.. ``` Pick a random 2-digit number. ``` *\L`. ``` Output the digits separately. ``` \ ``` Output the number. ``` .. $.($&*$&* ``` Square and implicitly output the number. [Answer] # TI-BASIC, 31 bytes ``` randInt(1,9→A randInt(1,9→B 10A+B Disp A,B,Ans,Ans² ``` [Answer] ## [MBASIC](https://archive.org/details/BASIC-80_MBASIC_Reference_Manual), ~~100~~ 86 bytes ``` 1 DEF FNR(X)=INT(RND*X)+1:A=FNR(9):B=FNR(9):PRINT A:PRINT B:C=A*10+B:PRINT C:PRINT C^2 ``` **Output** ``` 5 8 58 3364 ``` [Answer] # [sfk](http://stahlworks.com/dev/swiss-file-knife.html), 99 bytes ``` rand 1 9 +setvar a +rand 1 9 +setvar b +tell -var "#(a) #(b) #(a)#(b)" +calc -var #(a)#(b)*#(a)#(b) ``` [Try it online!](https://tio.run/##K07L/v@/KDEvRcFQwVJBuzi1pCyxSCFRQRtDLElBuyQ1J0dBF8RRUtZI1ORS1kgCEYmaIIaSgnZyYk4yRB4mqAVj/P8PAA "sfk – Try It Online") [Answer] # perl -E, 45 bytes ``` $_=10+int rand 90;y/0/1/;say for/./g,$_,$_**2 ``` This exploits the lack of a requirement that all random numbers should be picked with equal probability (it will pick numbers ending in 1 twice as often as ending in any other digit). [Answer] ## Visual C#, ~~102 Bytes~~; 101 bytes +2 Upper bound of Random.Next() exclusive, 10 instead of 9 -3 Thanks to [LiefdeWen](https://codegolf.stackexchange.com/users/68917/liefdewen) (var instead of Random) ``` var r=new Random();int x=r.Next(1,10),y=r.Next(1,10),z=x*10+y;Console.Write($"{x}\n{y}\n{z}\n{z*z}"); ``` normal form: ``` var r = new Random(); int x = r.Next(1, 10), y = r.Next(1, 10), z = x * 10 + y; Console.Write($"{x}\n{y}\n{z}\n{z * z}"); ``` [Try it online!](https://tio.run/##Vcq9CsIwFEDh2T7FpTgktZZ2Dp2cFdHBQR1CDCXQJpAba9KQZ48/m8sHB47ArUCRn6j0AOeATk6sECNHhKM1g@VTLFbouFMCZqMesOdKE3T281/vwO2ANOaZW7C9li84cf0wE6FMaQe@t81Beke6umtpHf5z6X3VtZvAdkajGWVzscpJsi6jTzcdw5flR7WkkrKcUn4D) ## Visual C#, ~~85 bytes 89 bytes~~ 91 Bytes +4 bytes: fixed problem with 0 as second digits, borrowing the `*10/9+1` from other answers +2 bytes: preventing numbers <11 Even shorter solution ``` var r=new Random();int x=r.Next(9,89)*10/9+1;Console.Write($"{x/10}\n{x%10}\n{x}\n{x*x}"); ``` normal form: ``` var r = new Random(); int x = r.Next(9, 89)*10/9+1; Console.Write($"{x/10}\n{x%10}\n{x}\n{x*x}"); ``` [Try it online!](https://tio.run/##PYu9CsIwFEZ3n@JSFJKq/dksoZOzIjo4qENIQwm0CeTGGgl59lqLeIbzLecTuBUoxicq3cLljU72bCE6jggna1rL@wVMhNlf0HGnBAxGNXDgShN0dvreHsBti/TfhREGbsHWWr7gzHVjekKZ0g58bbOj9I5Um11F07LIq3XJ9kaj6WR2tcpJskyCz8si3nXwq9/OSn1MKBtjHD8) [Answer] # [Red](http://www.red-lang.org), 69 bytes ``` prin reduce[x: random 9 n:"^/"y: random 9 n z: do rejoin[x y]n z * z] ``` [Try it online!](https://tio.run/##TcqxCoAgFAXQva@4OLY452e0ikH03mDgM6xI/XkTWloPJzG1mcm6Ia1CMeiTmSDx0ZcP3I7kBYnp3thmg@9gghi1aFX@gmpAsec9erEZxXXCiOpaewE "Red – Try It Online") [Answer] ## Batch, 95 bytes ``` @set/at=%random%%%9+1,u=%random%%%9+1,n=t*10+u,p=n*n @for %%a in (%t% %u% %n% %p%)do @echo %%a ``` `%random%` isn't a real variable, it's interpolated at parse time, so you need the `%`s even inside `set/a`. (Also don't try using it in a loop!) [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 9 bytes ``` 2æ8w)o§o² ``` [Try it online!](https://tio.run/##y00syUjPz0n7/9/ocKdlef6h5fmHNv3/DwA "MathGolf – Try It Online") ## Explanation For the example, the first random integer is 4, the second is 7. ``` 2æ Start for-loop of length two, with the next 3 chars as the body 8w Random non-negative integer less than or equal to 8 ) Increment by 1 o Output without popping (stack is unchanged) For loop ends, stack is now [4, 7], the first two lines have been printed § Concatenate the two numbers on the stack (stack is [47]) o Output without popping (stack is unchanged) ² Square number and output implicitly ``` ]
[Question] [ ## Powers We define an `important power` as a number that can be represented as \$ x^y \$ where \$ x ≥ 2 \$ and \$ y ≥ 2 \$. ## Palindrome We define an `important palindrome` as a number that is the same written forwards and backward, and is greater than `10`. Thus, the last digit must not be `0`. ## Palindromic Power We define a `Palindromic Power` as a number that is both an `important palindrome` and `important power`. ## Example My reputation when I first drafted this question was `343`, which was an `important power` as \$ 343 = 7^3 \$. It is also an `important palindrome`. Thus it is a `palindromic power`. (Interestingly, the number of badges I have when I first drafted this question was `7`). ## Your Challenge Given an integer \$ n \$, print all `palindromic powers` that are less than (and not equal to) \$ n \$. ## Example Program Your program should produce the same output as this program. The exact order of your answer does not matter ``` from math import log def is_power(n, base): return not n%base and is_power(int(n//base), base) def is_important_power(n): for base in range(2, int(n**0.5) + 1): if is_power(n, base): return True return False def is_important_palindrome(n): s = str(n) return s == s[::-1] and n>10 def is_palindromic_power(n): return is_important_power(n) and is_important_palindrome(n) def main(number): final = [] for i in range(1, number): if is_palindromic_power(i): final.append(i) return final ``` These are the palindromic powers under `1000000`: ``` 121 343 484 676 1331 10201 12321 14641 40804 44944 69696 94249 698896 ``` ## Input You may assume the input is under `100000000`. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). [Answer] # [Desmos](https://desmos.com/calculator), ~~177~~ 175 bytes ``` T->min(T+1,n),o->L[L>9] n=\ans_0 T=0 k=10^{[floor(log(T+0^T))...0]} L=join(o,[T][[0^{n-T}+∏_{A=2}^{T-1}sign(mod(log_AT,1))]=-sign(total(k[1]/kmod(floor(T/k),10))-T)^2]) o=[] ``` This was really fun to puzzle out and solve in Desmos! Surprisingly, the part to check for an important palindrome is longer than the part to check for an important power. Might be prone to floating point errors because of the usage of `log`, but any attempt to fix this will most likely cost more bytes, so I will just leave it like this for now. Output is shown in the `o` variable. More info on I/O in the graph links below. [Try It On Desmos!](https://www.desmos.com/calculator/8e7kvqv8qw) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/azgmicekqy) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` <TŸʒÓ¿≠yÂQ& ``` [Try it online!](https://tio.run/##ASEA3v9vc2FiaWX//zxUxbjKksOTwr/iiaB5w4JRJv//MTUwMDA "05AB1E – Try It Online") Before Kevin wakes up and outgolfs me. Port of Jelly. ## How? ``` <TŸʒÓ¿≠yÂQ& < # Decrement (implicit) input T # Push 10 Ÿ # Pop top two values of the stack and push inclusive range ʒ # Filter keep for n: Ó # Get the exponents of the prime factorization of n ¿≠ # Is the GCD of the exponents not one?... & # ...and... yÂQ # Is y a palindrome? ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` ’⁵rŒḂƇÆEg/’ƊƇ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw8xHjVuLjk56uKPpWPvhNtd0faDQsa5j7f///zc0NTAwAAA "Jelly – Try It Online") -1 byte thanks to Jonathan Allan! In order for some \$k = p\_1^{e\_1}p\_2^{e\_2}\cdots p\_i^{e\_i}\$ to be a perfect power (for primes \$p\_1, p\_2, \dots\$), we must have that \$\gcd(e\_1, e\_2, \dots, e\_i) > 1\$. ## How it works ``` ’⁵rŒḂƇÆEg/’ƊƇ - Main link. Takes n on the left ’ - Decrement ⁵r - Range from 10 to n-1 Ƈ - Keep those that are: ŒḂ - Palindromic ƊƇ - Keep those that are non-zero after: ÆE - Prime exponents g/ - Reduce by GCD ’ - Decremented ``` [Answer] # [Factor](https://factorcode.org/) + `math.primes.factors project-euler.common`, ~~101~~ 102 bytes ``` [ iota 10 short tail [ palindrome? ] filter [ group-factors values 0 [ gcd nip ] reduce 1 > ] filter ] ``` [Try it online!](https://tio.run/##RY2xTgMxEET7fMV8ADn5CpogQYloaBBVlMLa2yMG22t215H4@sMEIdp582bWSC66vb48PT8eEM2EDB@slTOayjuT77ln1omkFKko0c9T01TYpvUq2zX7BWuv5EmqwfizcyW2McPuX0Opjrvdbr69CSFsRyTxiDnAzqIOjynjiBZzqotK4QecsKbsrCN@U@lt//d3ibmP4fADaEFNbXSVl06MGff/4mmjmDOm7Rs "Factor – Try It Online") This is a port of caird's [Jelly answer](https://codegolf.stackexchange.com/a/247183/97916). I toyed with some brute force solutions but they came out a little longer. * `iota 10 short tail` Shortest way (I think) to create an exclusive range from 10 to the input that is empty if the input is less than 11. * `[ palindrome? ] filter` Get the palindromes within the range. * `[ ... ] filter` Get the perfect powers within the palindromes. * `group-factors values` Get the exponents of the prime factorization. * `0 [ gcd nip ] reduce` Take the GCD of a sequence. * `1 >` Is it greater than 1? Note that `[ ... ] filter [ ... ] filter` is shorter than any kind of boolean and logic that's possible in Factor, as far as I know. Compare these simple examples: * `[ odd? ] filter [ 10 > ] filter` * `[ dup odd? swap 10 > and ] filter` * `[| n | n odd? n 10 > and ] filter` * `[ { [ odd? ] [ 10 > ] } && ] filter` (short-circuiting [starts to win out at 3-4 conditions]) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 60 bytes ``` Select[h=Range[#-1],(h[[a#]]=a=h[[#]])<#>9&&PalindromeQ@#&]& ``` [Try it online!](https://tio.run/##HcZLCoAgEADQwwhSUJTLIMMj9FmKi8HGFNRA5v4mvdVLQB4TULBQnawXRrSkvTwhP6jZKMzQea2BGSNBtrX0K9sWzneIId/lTXgoxg2vewmZJuWUmH/1Aw "Wolfram Language (Mathematica) – Try It Online") ``` Select[ Range[#-1], ] pick numbers in the range where: h= (h[[a#]]=a=h[[#]]) (if x=a^b, h[[x]]=a) <# an important power #>9&&PalindromeQ@# and an important palindrome ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` ‹₀ṡ'ǐĠvLġċnḂ=∧ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigLnigoDhuaEnx5DEoHZMxKHEi27huII94oinIiwiIiwiMTUwMDAiXQ==) Port of Jelly answer. ## How? ``` ‹₀ṡ'ǐĠvLġċnḂ=∧ ‹₀ṡ # Descending range [input - 1, 10] ' # Filter for n: ǐ # Get the prime factorization of n Ġ # Group consecutive identical items vL # Get the length of each ġċ # Is the GCD of this array not one?... ∧ # ...and... nḂ= # Is n palindromic? ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 117 bytes Brute force at its finest. It might be improvable by merging the two `for` loops into one, but I currently have no idea how to go about that. ``` x,p,i,s,t;f(n){for(x=p=i=10;t=i%n;p=p<i?p*x:x/i||i==s&i/p&&printf("%d\n",i)?++i,x=2:++x)for(s=0;t;t/=10)s=s*10+t%10;} ``` [Try it online!](https://tio.run/##FcxBCsMgEEDRq0ggotGiyTJ2yEW6KRbLLGqH6GIgydmt/fv/4u0dY2tsyaIttoaksj7Sd1cMBAizDxVwzIGA7rjRxCs7PE8EKBIdSUk75prUML4eebCoN2PQMiyrMaz/UIFuhOq6pQuUafamjt29Wh/F54lZaXGIpBbf00Fc7Qc "C (gcc) – Try It Online") ### Ungolfed ``` x, p, i, s, t; f(n) { for ( x = p = i = 10; i < n; ) { // This loop calculates and sets `s` to the reverse of `i` for (s = 0, t = i; t; t /= 10) s = s * 10 + t % 10; // `p` is a running variable that holds the current // power depending on the base, `x`. if (p < i) { // While `p` is less than `i`, multiply it by `x` // (in other words, increment its exponent) p *= x; } else { if (x >= i) { // If no solution is found, // reset everything and increment `i` p = x = 2, ++i; } else if (i == s && i == p) { // If a solution is found, // print `i`, then reset everything and increment `i` printf("%d\n", i); p = x = 2, ++i; } else { // Otherwise, increment `x` to check for a solution // with the next base p = ++x; } } } } ``` [Answer] # [Haskell](https://www.haskell.org), ~~76~~ ~~72~~ 64 bytes ``` f n=[z|x<-[2..n],z<-map(x^)[2..n],z<n,(==)=<<reverse$show z,z>9] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWNx3SFPJso6tqKmx0o4309PJidapsdHMTCzQq4jThAnk6Gra2mrY2NkWpZalFxakqxRn55QpVOlV2lrEQc7bmJmbmKdgqFBRl5pUoqCikKRgaGBhA5GB2AQA) Given the ranges `[2..n]` are used, this aproach is *rather* inefficient. The ATO Link works for `n=1000`, but times out for `n=10000`. ##### Explanation: ``` f n = -- function f takes input n [z| -- returns list of all z where ... x<-[2..n], -- ... z = x^y for x in [2..n] z<-map(x^)[2..n], -- and y in [2..n] z<n, -- ... z is smaller than n (==)=<<reverse$show z, -- ... z is an palindrome z>9] -- ... and z is larger than 9 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 111 bytes ``` i,t,r;g(n){r=9/--n||g(n);for(t=n;t;t/=10)r=r*10+t%10;for(t=i=2;r==n&i<n;)t=t/n?t-n?++i:printf("%d\n",i=n):t*i;} ``` [Try it online!](https://tio.run/##LclBCsIwEEDRfY9RqCRNQhLBhR2HXsSNRBpm4ViG2bU9e1Tw7x6/hFpKa@TVC1TDdhO8xhB433@C5S1GkUFBI@ZkBWXMyemQ0/8RnkEQ@UQ3BquokWcNPDtH0yrEuph@eN6594RsJx0JjvZ6EBu7ddVc0jcL3dE@ "C (gcc) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 100 bytes ``` .+ $*¶ $.` 10A` G`^(?=(.)+)(?<-1>\1)+$ .+ $* Gr`(?=((?=((1*)(?=\5\3+$)1)(\2*$))\4){2,}1$)^(..+) %`1 ``` [Try it online!](https://tio.run/##HcqxDcJADEbh3nMYyf8ZrHMgHSGiyhJWZAoKGoqIDrEWA7DYASle9b7l@rjdL62ZEpfPm4gtyes5acpZxkEMChmPOz@FQ5lWSNOS/7nm5QeG6GOvDIdEVxiIA57d9uWMWcwUtElvra/1Cw "Retina 0.8.2 – Try It Online") Link uses `n=500` as otherwise it would be too slow. Explanation: Based on my answer to [Perfect radicals](https://codegolf.stackexchange.com/q/215858). ``` .+ $*¶ $.` ``` List all the integers up to `n`. ``` 10A` ``` Delete the first `10` (i.e. `0`..`9`). ``` G`^(?=(.)+)(?<-1>\1)+$ ``` Keep only palindromes. ``` .+ $* ``` Convert to unary. ``` Gr`(?=((?=((1*)(?=\5\3+$)1)(\2*$))\4){2,}1$)^(..+) ``` Keep only powers whose degree is at least `2`. Note that the `r` flag reverses the direction of processing, as if the entire regex was in a lookbehind. ``` %`1 ``` Convert to decimal. [Answer] # [Python](https://www.python.org), ~~87~~ 82 bytes ``` lambda n:[m for k in range(4,n*n)if 9<int(str(m:=(k//n)**(k%n))[::-1])==m<n>k%n>1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3g3ISc5NSEhXyrKJzFdLyixSyFTLzFIoS89JTNUx08rTyNDPTFCxtMvNKNIpLijRyrWw1svX18zS1tDSyVfM0NaOtrHQNYzVtbXNt8uyAInaGsRCT1xYUgTSlaZgbGGhqQsQWLIDQAA) Brute-force. Extremely slow. \$O\Big(n^2\Big)\$. *-5 bytes thanks to jezza\_99* ### Here's a much, much, much faster one: # [Python](https://www.python.org), 128 bytes ``` import sympy.ntheory as s,math lambda x:[x for x in range(10,x)if math.gcd(*s.factorint(x).values())!=1and str(x)==str(x)[::-1]] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY5BDoIwFET3nuK7aw00sjMkPQlh8QUKTWhL2o9pt17DDRtdex1vI0iczSQvM5N5vKZEg7PL8pxJ5ZfPXZvJeYKQzJSEpaFzPgEGCJlBGg5KjmiuLUIsqwjKeYigLXi0fceKcxa5VrAlRd-07BSEwoac15ZY5OKG49wFxvlRFmhbCORXLOXuVVnmRV3vT97Tr6TW0U2c7_h_9As) \$O\Big(n\Big)\$. [Answer] # [Julia 1.0](http://julialang.org/), 55 bytes ``` !n=filter(i->"$i"==reverse("$i")&&i∈(r=2:i)'.^r,10:n) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/XzHPNi0zpyS1SCNT105JJVPJ1rYotSy1qDhVA8TTVFPLfNTRoVFka2SVqamuF1ekY2hglaf5PyWzuCAnsVJD0cjAwEDzPwA "Julia 1.0 – Try It Online") with a beautiful \$O(n^3)\$ complexity and \$O(n^2)\$ memory usage [Answer] # [JavaScript (V8)](https://v8.dev/), 81 bytes ``` n=>(g=x=>(x*=p)<n?[...x+''].reverse(g(x)).join``==x&&print(x):++p*p<n&&g(p))(p=7) ``` [Try it online!](https://tio.run/##HcjBCoMwDIDht6mJZcGdHMNsDyKCMmqphyxUKXn7Kv6H7/BvS1n2X056PMqrrlyFPxDZLq1lxUG@IxGZb5qJcigh7wEiGCJt/yTzzGzOaU5yXPPtvbY6iHMRFBGUe6wrPLs7rCc "JavaScript (V8) – Try It Online") ### Note For \$n<7\$, there is no \$k\$ such that \$n^k\$ is a palindromic power less than \$100000000\$ with at least 2 decimal digits. Therefore, we can safely start the search with \$n=7\$ and get rid of the few single-digit palindromic powers (\$2^2\$, \$2^3\$, \$3^2\$). ### Commented ``` n => ( // n = upper bound g = // g is a recursive function taking x => // the current result x (x *= p) < n ? // multiply x by p; if it's less than n: [...x + ''] // turn x into an array of digits .reverse( // reverse this array g(x) // do a recursive call with x unchanged ) // (reverse() ignores this argument) .join`` == x && // if x is palindromic: print(x) // print it : // else: ++p * p < n && // increment p; if p² is less than n: g(p) // do a recursive call with x = p // (otherwise, stop the recursion) )(p = 7) // initial call to g with x = p = 7 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes ``` ɽ₀ȯ'ɽ›Ėe:⌊=anḂ=∧ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJUIiwiIiwiyb3igoDIryfJveKAusSWZTrijIo9YW7huII94oinIiwiIiwiMTMwIl0=) Who needs smart prime factorisation when you can just brute force it? ## Explained ``` ɽ₀ȯ'ɽ›Ėe:⌊=anḂ=∧ ɽ₀ȯ' # From the range [11, n) (empty if n < 10) keep only items (x) where: ɽ›Ėe:⌊=a # there exists a number in the range [2, x) where that number to an integer power equals x nḂ=∧ # and x is a palindrome ``` The part which checks for important power better explained: ``` ɽ›Ėe:⌊= ɽ› # the range [2, x) Ė # the reciprocal of each number in that range - no need to worry about floating point accuracy errors because everything is stored as fractions internally e # x to the power of each of those reciprocals - this is taking every nth root of x which is less than x :⌊= # determine whether each item is a whole integer. ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-rprime`, 88 bytes ``` ->x{(10..x).select{|y|y.prime_division.map(&:last).inject(:gcd)>1&&y.digits*''==y.to_s}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7KI026WlJWm6FjcjdO0qqjUMDfT0KjT1ilNzUpNLqmsqayr1wCrjUzLLMosz8_P0chMLNNSschKLSzT1MvOygMo0rNKTUzTtDNXUKvVSMtMzS4q11NVtbSv1SvLji2trIeavLlBIizY0AIFYiMiCBRAaAA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` IΦ…χN›⁼ι⮌ι⬤…²ι⊖Σ↨ιλ ``` [Try it online!](https://tio.run/##LYtLDgIhEAWv0ssmwYRx68p/3BgznqDFjpI0qA3M9XFI5i3rVfk3qf@QtHbTkAruKRc8BSmsOFJ6MQ7OwiV9a7nW@JipMRbOytSN46@SZAwWRp5YM2Po91ZkidcWwgwO7JUjp8JPvNeIO@qqBTHLNq0Nzrm2muQP "Charcoal – Try It Online") Link is to verbose version of code. Very brute force. Explanation: ``` … Range from χ Predefined variable `10` to N Input as a number Φ Filtered where ι Current value ⁼ Equals ι Current value ⮌ Reversed › And not … Range from ² Literal integer `2` to ι Current value ⬤ All value satisfy ι Outer value ↨ Converted to base λ Inner value Σ Take the sum ⊖ Is not equal to `1` I Cast to string Implicitly print each match on its own line ``` A more efficient version for 28 bytes: ``` IΦ…χN∧⁼ι⮌ι⊙↨ι²⁼¹Σ↨ι⌈X⊖ι∕¹⁺²μ ``` [Try it online!](https://tio.run/##TYzNCsIwEIRfZY9bWMH26klbBS9S6hPEdqkLSar5qfj0MVUR5zbzzUx/Va6flE6pdWID1soHPIgO7LBTdmQs1wRHe4vhFM0lp0VBsLUD7u9RaY9C0PHMzjPKBz1xpxZHUGX/rZUE52h@pGbRYkdsp0e@bLh3bNgGHvIJQSOzDLxsWh09VgSm@NMmpXL9VlrN@gU "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Works by only testing `20` (for `n=1000000`) approximate roots for each palindrome instead of all `n`. [Answer] # Java 8, 133 bytes ``` n->{for(;--n>9;)for(int t=2,i=2;(n+"").contains(new StringBuffer(n+"").reverse())&i<n;t=t>n?++i:t*i)if(t==n)System.out.println(i=n);} ``` Outputs in reversed order. Very slow for larger test cases. Inspired by [*@att*'s C answer](https://codegolf.stackexchange.com/a/247224/52210). [Try it online.](https://tio.run/##LY9BT8MwDIXv@xXWDsihtCqTOIyQInFnlx0RQiFLkEfnTolbhKb@9pKyXiz72fL73tEOtjwevifX2pTg1RJfVgDE4mOwzsNuHgGGjg7gMOvASmdpXOWSxAo52AGDmbhsLqGLqMuSm61Wcz/fi9nckdlo5GK9VpXrWLJLQvY/sJdI/PXSh@Djso9@8DF5VOqGnliLkYafi4Ie5ZYUBRRjWO1/k/hT1fVSnfMHaRkpy3qc9Mx17j/bzLXg/bOfside7d7erbqm4srh/cNHXddLpnH6Aw) **Explanation:** ``` n->{ // Method with integer parameter and no return-type for(;--n>9;) // Loop `n` downward in the range (n,9): for(int t=2,i=2;// Create two temp integers, starting at 2 (n+"").contains(new StringBuffer(n+"").reverse())& // If the current `n` is a palindrome: i<n // Inner loop as long as `i` is still smaller than `n`: ; // After every iteration: t= // Replace `t` with: t>n? // If `t` is larger than `n`: ++i // Increase `i` by 1 first, and set `t` to this new `i` : // Else: t*i) // Multiply `t` by `i` if(t==n) // If `t` is equal to the current `n`: System.out.println( i=n // Set `i` to the current `n` );} // And print it with trailing newline ``` [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 48 bytes ``` -.{J<-==}FO9.-f{Jbcjfc:-.jqLGZ]{J@1.>jXXsm&&}ay} ``` [Try it online!](https://tio.run/##SyotykktLixN/V@U@V9Xr9rLRtfWttbN31JPN63aKyk5Ky3ZSlcvq9DHPSq22svBUM8uKyKiOFdNrTaxsvb/f1MDAwA "Burlesque – Try It Online") ``` -. # Decrement {J<-==}FO # Filter palindromes 9.- # Drop single digits f{ # Filter J # Duplicate bc # Repeat infinitely jfc # Factors :-. # Greater than 1 jqLGZ] # Log of number against factor { J@1.> # Greater than 1 jXXsm # Is whole number &&} # And ay # Any } ``` [Answer] # [J-uby](https://github.com/cyoce/J-uby) `-rprime`, 85 bytes Port of [Steffan’s Ruby answer](https://codegolf.stackexchange.com/a/247213/11261). ``` :!~&10|:select+(-[:prime_division|:*&:last|:/&:gcd|:<&1,:==%[:digits|:join,S]]|:all?) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXJ1tJJuUUFRZm6qUuyiNNulpSVpuhY3Q60U69QMDWqsilNzUpNLtDV0o63AiuJTMssyizPz82qstNSschKLS2qs9NWs0pNTaqxs1Ax1rGxtVaOtUjLTM0uKa6yy8jPzdIJjY2usEnNy7DUhhq8qUEiLNjQAgliIwIIFEBoA) ]
[Question] [ **This question already has answers here**: [Factorial digit sum](/questions/100823/factorial-digit-sum) (58 answers) Closed 5 years ago. In light of today's date... A factorial of a number n, is the product of all the numbers from 1 to n inclusive. ## The Challenge Given an integer n where 0 <= n <= 420, find the sum of the digits of n!. It's that simple :P *Notes: I feel like this challenge isn't too simple, as some languages have a very hard time storing numbers that are fairly large. Also, coding a BigInteger datatype is fairly straightforward, but hard to golf.* --- ## Examples > > Input: 100. Output: 648. > > > Input: 200. Output: 1404. > > > Input: 420. Output: 3672. > > > --- ## Scoring * The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. EDIT: Ok, I guess it's actually easy...take a look at the Jelly answer below. Anyways, I guess we all know which one's going to be accepted. But, I'd still like to see some interesting ideas and tricks to this problem! [Answer] # (old problem) [JavaScript (Node.js)](https://nodejs.org), ~~99~~ ~~94~~ ~~92~~ ~~88~~ ~~86~~ ~~83~~ ~~80~~ 78 bytes ``` f=(x,t=[...21+Array(999)])=>x?f(s=x-1,t.map(d=>-s+(s+=(t=~~d*x+t/10|0)%10))):s ``` [Try it online!](https://tio.run/##bchBCsIwEADAu/8Qdk0Tk@ClwlZ8h3gITSNKbUo2SATp16MeBec4N/dw3KfrnOUU/VBrIChNppNSyhpxTMk9oW1bPCN15RCAqUjTZHV3M3jqJAtgQZBpWfymiLw1@qVxbTQi7rn2ceI4DmqMFwhg9KdXv2f/3M5@r74B "JavaScript (Node.js) – Try It Online") well, first language without large number support Thank Arnauld for 4 bytes ``` f = (x, t = ['2', '1', ...','.repeat(998)]) => // init x, t=1 x ? f( // recursive x':=x-1, t'=t*x s = x-1, // s init to 0 when x==1, in next recursion just return t.map ( b = // init b to NaN d => -s + ( // to return the added value s+= ( // -s + (s + k) == k b= ~~d*x+b/10 | 0 // ~~d converts ',' to 0 // b is initally NaN, after first iteration // it's zero, then the last digit sum result with carry ) % 10 ) ) ) : s // the sum from x==1 ``` [Answer] # [Neim](https://github.com/okx-code/Neim), 2 bytes ``` 𝐓𝐬 ``` Explanation: Factorial `𝐓`; sum `𝐬`. This outgolfs 3-byte answers as the sum command is able to implicitly convert to a list. [Try it online!](https://tio.run/##y0vNzP3//8PcCZOBeM3//4YGBgA "Neim – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes ``` Total@IntegerDigits[#!]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyS/JDHHwTOvJDU9tcglMz2zpDhaWTFW7X@ag@X//7oFRZl5JQA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` !SO ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fMdj//38TIwMA "05AB1E – Try It Online") **Explanation** ``` ! # factorial of input S # split to list of digits O # sum ``` [Answer] # [Haskell](https://www.haskell.org/), 42 40 38 bytes ``` f n=sum[read[d]|d<-show$product[1..n]] ``` [Try it online!](https://tio.run/##Lci9CoAgGEbhvat4h9bEpDGvRBykzyjyDzVauneLaHo4ZzPlsM61tiLIcnqVrSFF@qZ5KFu8@pQjnUtVI2NB6@bNHiBBsQOcrUhvpLyHCob1fQkj55/idxK8PQ "Haskell – Try It Online") Thanks to @Laikoni for saving 2 bytes with list comprehension. [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/attache), 11 bytes ``` Sum@List@`! ``` [Try it online!](https://tio.run/##SywpSUzOSP2fZmX7P7g018Ens7jEIUHxv19qakpxtEpBQXJ6LFdAUWZeSUhqcYlzYnFqcXSajkK0oYGBjoIRiDAxMoiN/Q8A "Attache – Try It Online") `Sum`s the `List` of digits in the factorial (`!`) of the input. Anonymous function. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 16 bytes ``` n->sumdigits(n!) ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1664NDclMz2zpFgjT1Hzf2JBQU6lRp6Crp1CQVFmXgmQqQTiKCmkaeRpauooRBsaGOgoGIEIEyODWM3/AA "Pari/GP – Try It Online") [Answer] # [J](http://jsoftware.com/), 13 11bytes ``` 1#.,.&.":@! ``` [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N9QWU9HT01PycpB8b8ml5KegnqarZ66go5CrZVCWjEXV2pyRr5CmoKhgUEFjG2ExDYxArL/AwA "J – Try It Online") ## Explanation: `!` calculate the factorial `@` and `,.&.":` convert it to a list of digits (convert to string `":`, ravel `,.` and convert each char back to number) `1#.` find their sum by base-1 conversion [Answer] # [Perl 6](https://perl6.org), 21 bytes ``` {[*](2..$_).comb.sum} ``` [Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszcWVW6mglqZg@786WitWw0hPTyVeUy85PzdJr7g0t/Z/cWKlQpqCoYGBNReEaYRgmhgZWP8HAA "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 [*]( # reduce using &infix:« * » 2 .. $_ # Range starting at 2 (slight optimization over 1) ).comb # split the result into digits .sum # find the sum of those digits } ``` [Answer] # [R](https://www.r-project.org/) + gmp, 66 bytes ``` sum(strtoi(el(strsplit(paste(gamma(gmp::as.bigz(scan())+1)),"")))) ``` [Try it online!](https://tio.run/##FcYxDoAgDADAvzi10Rg1TvymKMEmVAitg34e9aarLbGvVG@QYEfeFZteAmrVMkNI/7QkNiikFiCSCEGU4hzp6Dk@oBudgNjPiEPX4aety9Re "R – Try It Online") `gmp` is one of the several BigInteger packages available on CRAN. [Answer] # [Python 2](https://docs.python.org/2/), 51 bytes ``` f=lambda L,p=1:0**L*sum(map(eval,`p`))or f(L-1,p*L) ``` [Try it online!](https://tio.run/##FYtLCoAgFAD3neItVV6g0iroBt4ggoySHqQ9@kGnN5vFwCyG32vdk805dJuP0@zBIXem1Uo5dd5RRM9iefyGI49S7gcE4WqDrJzMoSQBJeitRjC6yP5qrB7aCgp8ULqAsFwk8wc "Python 2 – Try It Online") We'd like to write `map(int,`p`)`, but since `repr(p)` might have a trailing `L`, that won't work. Ordinarily, we'd resort to `map(int,str(p))` and lose three bytes. Here, can we name our counting-down variable `L`, and write `map(eval,`p`)`. Since `L` is 0 when we compute the result, the digit sum is unaffected. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` !DS ``` [Try it online!](https://tio.run/##y0rNyan8/1/RJfj///8mRgYA "Jelly – Try It Online") ``` !DS - main link, taking an integer e.g. 9 ! - factorial --> 362880 D - convert to decimal --> [3,6,2,8,8,0] S - sum of list --> 27 ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 2 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage) ``` !Ś ``` [Try it online!](https://tio.run/##K6gs@f9f8eis//8NDQwA) Explanation: ``` Implicit input ! Factorial Ś Sum of digits Implicit output ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~52~~ ~~54~~ 52 bytes ``` f=lambda n,r=1:1/n*sum(map(int,str(r)))or f(n-1,n*r) ``` [Try it online!](https://tio.run/##DcsxCsMwDEDROT2FRimoxDaZAjlJ6eASTAW1bBRnyOldD394w693@xYNvaf9F/PniKBsu9/8ovN5ZcyxomjjsxkaERWDhPr0rLNRT4MCovAKjr1zHEZrcO/tMVUbHwgnFOp/ "Python 2 – Try It Online") -2 bytes thx to [Kirill L.](https://codegolf.stackexchange.com/users/78274/kirill-l) [Answer] # [Octave](https://www.gnu.org/software/octave/) with Symbolic Package, ~~43~~ 42 bytes ``` @(s)sum(char(sym(['factorial(' s 41]))-48) ``` Anonymous function that takes the input as a string and outputs a nubmer. [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo1izuDRXIzkjsUijuDJXI1o9LTG5JL8oMzFHQ12hWMHEMFZTU9fEQvN/moa6oYGBuiYXkGEEY5gYARn/AQ "Octave – Try It Online") [Answer] # [Bash + GNU utilities](https://www.gnu.org/software/bash/), 36 * 6 bytes saved thanks to @Cowsquack ``` seq -s* $1|bc|sed 's/\B\|\\/+&/g'|bc ``` [Try it online!](https://tio.run/##RcqxCoMwFIXh3ac4iK1gCblKt0IHnyOLmmvrklRPxrx76lI6/fDxzxPfZY0HkjItExVbwCDoRc4I7oM84GP1ObaQVtQXwjxRo/n9FTXBmD8U6g7DDk2f5yVTPVpaN7rsnL1d7as9ufgYtHwB "Bash – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 7 bytes ``` IΣΠ…¹⊕N ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0VyOgKD@lNLlEIygxLz1Vw1BHwTMvuSg1NzWvJDVFwzOvoLTErzQ3KbVIQxMCrP//NzEy@K9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input as a number ⊕ Increment ¹ Literal 1 … Range Π Product Σ Sum (of digits) I Cast to string Implicitly print ``` `InclusiveRange(1, InputNumber())` also works but the explanation is prettier this way. [Answer] # [Elixir](https://elixir-lang.org/), 54 bytes ``` fn n->Enum.sum Integer.digits Enum.reduce 1..n,&*/2end ``` [Try it online!](https://tio.run/##Hcg7CoAwDADQq2SSVjS2HsDNwclDtLEEbJB@wNtH8I2Pbn656HEiS30oNGP0EpB526VnrD3DIY0SFYycuFX4v1DsgcAjyjSMy0oS1aLxzlmrHw "Elixir – Try It Online") Ungolfed: ``` def sum_factorial(n) do # factorial Enum.reduce(1..n, fn(x, acc) -> x * acc end) # sum digits |> Integer.digits |> Enum.sum ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 107 bytes ``` f(x){int a[999]={1},i,c; for(;x;--x)for(c=i=0;i<999;)c=(a[i]=a[i]*x+c)/10,a[i++]%=10; for(;i--;)x+=a[i]; i=x;} ``` [Try it online!](https://tio.run/##LY5BjsIwDEX3OUXEqFI8TcBFbCqTXqR0UaUELEE6AkaKqHr2kgAb@3/528/OnJxbFq8iTBwesm/ruu7sVM2atSM/3hRFMiZCls6yReJ9yhA4q/qWO5vLbywdbCrUyZRlV9gKP7tsDEEs3yFiG2lefji4y/9w3N8fA4/rcyMy@NpzUDAJmU1o0wu7Leotoq4QZxIyn8sztnd@Hkcvw@YrsA1dBjVIIKT8u6WYV6tikKaRxXAIKx0SXnuVGwCJeXkB "C (gcc) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 3 bytes ``` ΣdΠ ``` [Try it online!](https://tio.run/##yygtzv6fG3xoSWrxo6bG/@cWp5xb8P///2hDAwMdIyA2MTKIBQA "Husk – Try It Online") ### Explanation ``` ΣdΠ Implicit input Π Factorial d Convert to list of digits Σ Sum ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 33 bytes ``` ->n{(2..n).inject(:*).digits.sum} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNITy9PUy8zLys1uUTDSktTLyUzPbOkWK@4NLf2f4FCWrSJkUHsfwA "Ruby – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 4 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ║▼⌡è ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=ba1ff58a&i=100%0A%0A200%0A%0A420&m=1) ### Unpacked (5 bytes) and explanation ``` |FE|+ |F Implicit input. Factorial. E Array of decimal digits. |+ Sum of list. Implicit print. ``` [Answer] [**Python**](https://www.python.org/), 75 bytes ``` import math print(sum(map(int,list(str(math.factorial(int(input()))))))) ``` [Answer] # [Tcl](http://tcl.tk/), 78 bytes ``` proc S n {proc F n {expr $n?($n)*\[F $n-1]:1} expr [join [split [F $n] ""] +]} ``` [Try it online!](https://tio.run/##K0nO@f@/oCg/WSFYIU@hGsxyA7FSKwqKFFTy7DVU8jS1YqLdgGxdw1grw1ousEx0Vn5mnkJ0cUFOZokCWDZWQUkpVkE7tvZ/Tm5iAcgILkMDAy4jIDYxMuCqBRpeWlIMVGgVoxAdDNJQ@x8A "Tcl – Try It Online") [Answer] # Java 10, 135 bytes ``` n->{var r=java.math.BigInteger.ONE;for(;!n.equals(r.ZERO);n=n.subtract(r.ONE))r=r.multiply(n);return(r+"").chars().map(c->c-48).sum();} ``` **Explanation:** [Try it online.](https://tio.run/##pVCxTsMwEN37FUcnWyhWqTogWemA1IGBRKIbiOHqOqmD44SzHamq8u3BBNg6gXQ33N17d@9dgwNmzfF9Uha9hyc07rIAMC5oqlBpKL7KuQGKNQktWgwn8WDqx4SpNYHjMkHGlCl8wGAUFOAgh8ll28uABJRfY4qy2MmqIyZvnNAfEa1nJF52zyWXLnfCx0MgVIHNSM4pJ9FGG0xvzyxdJR0iOUa3yyUX6oTkGU83eqayrco29zxtaBmX4yQXSVofDzZJ@1E4dOYIbbLL9oGMq1/fAPm31/3ZB92KLgbRp1Gwjjlx3bwY0EZdVuxuteJ8fsTf@Ot/8jfrX/64GKdP) ``` n->{ // Method with BigInteger parameter and integer return-type var r=java.math.BigInteger.ONE; // BigInteger, starting at 1 for(;!n.equals(r.ZERO); // Loop as long as `n` is not 0 yet n=n.subtract(r.ONE)) // After every iteration: subtract 1 from `n` r=r.multiply(n); // Multiply `r` by `n` return(r+"").chars() // Loop over the characters of `r` .map(c->c-48) // Convert them to digits .sum();} // And return the sum of those digits ``` [Answer] ## Ceylon, 98 bytes ``` import ceylon.whole{l=one}Integer q(Integer n)=>sum({0,*product({l,*(l:n)}).string*.offset('0')}); ``` [Try it online](https://try.ceylon-lang.org/?gist=5c2e0772578a68dab9f3d51c3d9a9ac7) ## Explanation: This is quite long, because we need to convince the compiler that we are not doing bogus stuff. ``` import ceylon.whole { l = one } // 1 Integer q(Integer n) => // 2 sum({0,*product({l,*(l:n)}).string *.offset('0')}); // | | | | '3' || | | | | ||| // | | | '--4-----'| | | 7 | ||| // | | '----5------------' '-6--' '--8------'|| // | | '----------------9---------------------'|| // | '----------------10-------------------------'| // '------------------------11----------------------' ``` 1. Import the value [`one`](https://modules.ceylon-lang.org/repo/1/ceylon/whole/1.3.3/module-doc/api/index.html#one) from the package `ceylon.whole`, and give it locally the name `l` (small L, not the digit `1` – though I choose this alias for its similarity to 1). (This alias import costs two bytes here, but saves two bytes for each of the two usages). 2. Define a function `q` from `Integer` to `Integer`, which maps each parameter `n` to the result of the following expression (calculated in steps 3 to 11). Top-level functions always need a type declaration. For local ones we could replace the return type by `function`, which wouldn't have saved anything here. (For inline functions, we sometimes can omit both types and the keyword, if they can be inferred from context.) 3. This is a short syntax for [`measure(one, n)`](https://modules.ceylon-lang.org/repo/1/ceylon/language/1.3.3/module-doc/api/index.html#measure), which returns either the empty sequence `[]` if `n` is non-positive, or a `Range<Whole>` starting from `one` and having size `n` (i.e. all numbers from 1 to n, assuming n is a positive integer). Type: `[]|Range<Whole>`, which is a subtype of `{Whole*}` (possibly empty iterable of Whole). 4. This is an [iterable enumeration](https://www.ceylon-lang.org/documentation/1.3/reference/expression/iterable/), with `one` as the first element and then all the elements of `one:n` (the `*` here expands the iterable). This has type `{Whole+}`, and has the only purpose to make sure the compiler knows it is non-empty. We could have used `[...]` instead of `{...}` for a [tuple enumeration](https://www.ceylon-lang.org/documentation/1.3/reference/expression/tuple/) (which is non-lazy). No difference here apart from performance. We could have written this [`(l:n).follow(l)`](https://modules.ceylon-lang.org/repo/1/ceylon/language/1.3.3/module-doc/api/Iterable.type.html#follow), but that is longer. 5. Calculate the product of all those numbers, type `Whole`. [`product`](https://modules.ceylon-lang.org/repo/1/ceylon/language/1.3.3/module-doc/api/index.html#product) needs a non-empty iterable as a parameter to work (as the product of nothing is not defineable in a type-independent way). 6. Get the string representation of the result of step 5. (The `.string` attribute exists for all classes, and `Whole` implements it in the expected way, using decimal digits.) – type `String`, which is also a `{Character*}` (possibly empty iterable of characters). 7. The [`*.` operator](https://www.ceylon-lang.org/documentation/1.3/reference/operator/spread-invoke/) for iterables applies the the following attribute or method call to each element of the iterable and collects the result in a sequence. It can be seen as syntactic sugar for `.collect(c => c.offset('0'))`. This is non-lazily evaluated, there is also `.map(...)` which is lazy. 8. The [`offset`](https://modules.ceylon-lang.org/repo/1/ceylon/language/1.3.3/module-doc/api/Character.type.html#offset) method of `Character` just calculates the difference between the unicode code points, returning an `Integer`. This takes advantage of the fact that the ten decimal digits are sequential starting with `0` in ASCII (and thus unicode). 9. This whole thing has now type `[Integer*]` (possibly empty sequence of integers – because the string is possibly empty for the compiler). 10. Same trick again as step 4, we make it an `{Integer+}` (nonempty iterable) by prepending a `0` (which has no effect on the following sum). 11. [Sum](https://modules.ceylon-lang.org/repo/1/ceylon/language/1.3.3/module-doc/api/index.html#sum) it all up. [Answer] # [CJam](https://sourceforge.net/p/cjam), 11 8 bytes there is in fact a better way to get a list of digits ``` lim!Ab:+ ``` [Try it online!](https://tio.run/##S85KzP3/PyczV9ExyUr7/38TIwMA "CJam – Try It Online") Explanation: ``` li input, convert to integer m! factorial Ab convert to array of digits in base 10 :+ sum ``` --- Original solution: ``` lim!`1/:i:+ ``` Explanation: ``` li input converted to integer m! factorial ` convert to string 1/ split into pieces of length 1 :i convert back to integer :+ sum ``` ]
[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/24541/edit). Closed 4 years ago. [Improve this question](/posts/24541/edit) Your challenge is to divide two numbers using long division. The method we used to use in old days of school to divide two numbers. Example [here](http://en.wikipedia.org/wiki/Long_division) You should **NOT** use `/` or any other division operator in your code. Also, this is not [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") **Example:** ``` Input : 4 2 (4 divided by 2) Output : 2 0 (here 2 is quotient and 0 is remainder) ``` Another example ``` Input : 7182 15 (7182 divided by 15) Output : 478 12 (7170 is quotient and 12 is remainder) ``` The answer with most up-votes after 24 hours wins because this is a popularity contest. [Answer] ## C Not exactly a long division - this answer uses the method used in the *real* old days. ``` #include <stdio.h> #include <stdlib.h> int main() { int a,b; scanf("%d %d", &a, &b); int *p=calloc(b, sizeof(int)); int *q=p; while(a--) { (*p)++; if(p-q<b-1) p++; else p-=b-1; } p=q; int r=0, i; for(i=0; i<b; i++) r+=p[i]-p[b-1]; printf("%d %d\n", p[b-1], r); return 0; } ``` Explanation: Suppose you are given `a` number of sheep and you need to split them up into `b` number of groups. The method used here is to assign each sheep into a different group until the total number of groups reaches `b`, then start from the first group again. This repeats until there are no more sheep. Then, the quotient will be the number of sheep in the last group, and the remainder will be the sum of the differences between each group and the last group. An illustration for `8/3`: ``` |Group 1 | Group 2 | Group 3 ------------------------------------- | 1 | 2 | 3 // first sheep in group 1, second sheep in group 2, etc | 4 | 5 | 6 | 7 | 8 | ------------------------------------- total: | 3 | 3 | 2 ``` So the quotient is 2 and the remainder is (3-2)+(3-2)=2. [Answer] # Bash + coreutils Forget what you learned in school. Nobody uses long division. Its always important to chose the right tool for the job. [`dd` is known by some as the swiss army knife of the command-line tools](http://www.linuxprogrammingblog.com/dd-as-a-swiss-army-knife), so it really is the right tool for every job!: ``` #!/bin/bash q=$(dd if=/dev/zero of=/dev/null ibs=$1 count=1 obs=$2 2>&1 | grep out | cut -d+ -f1) r=$(( $1 - $(dd if=/dev/zero of=/dev/null bs=$q count=$2 2>&1 | grep bytes | cut -d' ' -f1) )) echo $q $r ``` Output: ``` $ ./divide.sh 4 2 2 0 $ ./divide.sh 7182 15 478 12 $ ``` --- Sorry, I know this is a subversive, trolly answer, but I just couldn't resist. Cue the downvotes... [Answer] # C Long division! At least how a standard computer algorithm might do it, one binary digit (bit) at a time. Handles negatives, too. ``` #include <stdio.h> #define INT_BITS (sizeof(int)*8) typedef struct div_result div_result; struct div_result { int quotient; int remainder; }; div_result divide(int dividend, int divisor) { int negative = (dividend < 0) ^ (divisor < 0); if (divisor == 0) { result.quotient = dividend < 0 ? INT_MIN : INT_MAX; result.remainder = 0; return result; } if ((dividend == INT_MIN) && (divisor == -1)) { result.quotient = INT_MAX; result.remainder = 0; return result; } if (dividend < 0) { dividend = -dividend; } if (divisor < 0) { divisor = -divisor; } int quotient = 0, remainder = 0; for (int i = 0; i < sizeof(int)*8; i++) { quotient <<= 1; remainder <<= 1; remainder += (dividend >> (INT_BITS - 1)) & 1; dividend <<= 1; if (remainder >= divisor) { remainder -= divisor; quotient++; } } div_result result; if (negative) { result.quotient = -quotient; result.remainder = -remainder; } else { result.quotient = quotient; result.remainder = remainder; } return result; } int main() { int dividend, divisor; scanf("%i%i", &dividend, &divisor); div_result result = divide(dividend, divisor); printf("%i %i\r\n", result.quotient, result.remainder); } ``` It can be seen in action [here](http://ideone.com/IiKDxM). I chose to handle negative results to be symmetrical to positive results, but with both the quotient and remainder negative. Handling of edge cases is done with best effort. Division by zero returns the integer of highest magnitude with the same sign as the dividend (that's `INT_MIN` or `INT_MAX`), and `INT_MIN / -1` returns `INT_MAX`. [Answer] ## Julia Here is an entry that not only is free from division but doesn't employ any multiplication either. It does the long division quite literally by using more string manipulation than arithmetic. It also prints out an ASCII version of what the long-division would look like on a sheet of paper (at least the way I learned it) ``` function divide(x,y) if y > x return 0, x end x = "$x" q = "" r = "" workings = "" for i = 1:length(x) r = "$(r)0" num = int(r) + int(x[i:i]) sum = 0 m = 0 while sum+y <= num m += 1 sum += y end r = string(num-sum) q = "$q$m" ls = length(string(sum)) workings *= repeat(" ", i-ls) * "-$sum\n" workings *= repeat(" ", i+1-ls) * repeat("-", ls) * "\n" workings *= repeat(" ", i+1-length(r)) * r * (i >= length(x) ? "" : x[i+1:i+1]) * "\n" end workings *= repeat(" ", length(x)-length(r)+1) * repeat("=", length(r)) * "\n" print(" $x : $y = $(int(q)) R $r\n$workings") int(q), int(r) end ``` Results (the `(q,r)` line at the end is just Julia printing the result of the function call): ``` > divide(5,3) > divide(4138,17) > divide(7182,15) 5 : 3 = 1 R 2 4138 : 17 = 243 R 7 7182 : 15 = 478 R 12 -3 -0 -0 - - - 2 41 71 = -34 -60 -- -- (1,2) 73 118 -68 -105 -- --- 58 132 -51 -120 -- --- 7 12 = == (243,7) (478,12) ``` I suppose I could get rid of the remaining arithmetic by using a unary number system, `repeat` and `length` but that feels more like multiplying than not using arithmetic. Don't even try dividing by zero! (Seriously, who would do long division for that?) Also don't try negative numbers. [Answer] ## Python ``` def divide(a, b): q = 0 while a >= b: a -= b q += 1 return (q, a) ``` [Answer] # C# Not exactly golfing, but IMO it's pretty easy to follow. It only uses the `/` operator after it has broken the dividend down into smaller sections. It performs division in the "old" way. For example, for `1907 / 12`, it takes `19` and divides it by `12`, then carries the remainder `7` over, divides `70` (from `707`) by `12`, etc. ``` string divisor = "12"; string dividend = "1907"; string output = ""; do { double dd = Convert.ToDouble(dividend.Substring(0, divisor.Length)); double dr = Convert.ToDouble(divisor); if (dd >= dr) { string s = (dd / dr).ToString(); output += s.Substring(0, s.Contains(".") ? s.IndexOf(".") : s.Length); dividend = dd % dr + dividend.Substring(divisor.Length); } else { double d2 = Convert.ToDouble(dividend.Substring(0, divisor.Length + 1)); string s = (d2 / dr).ToString(); output += s.Substring(0, s.Contains(".") ? s.IndexOf(".") : s.Length); dividend = d2 % dr + dividend.Substring(divisor.Length + 1); } } while (Convert.ToDouble(dividend) >= Convert.ToDouble(divisor)) for (int i = 0; i < dividend.Length - 1; i++ ) if (dividend[i].ToString() == "0") output += "0"; dividend = Convert.ToInt32(dividend).ToString(); Console.WriteLine("result: " + output + " r." + dividend); ``` [Answer] ## D Horribly roundabout method that has more steps than is probably necessary to divide a number, but there you are. ``` import std.stdio; import std.traits : isIntegral, isUnsigned; import std.conv : to; TNum divide( TNum )( TNum dividend, TNum divisor, out TNum remainder ) if( isIntegral!TNum ) { TNum quot = 0, rem = dividend, prod = divisor, t = 1, max = ( ( TNum.sizeof * 8 ) - 1 ) ^^ 2; while( t < max && prod < rem ) { prod = prod * 2; t = t * 2; } while( t >= 1 ) { if( prod <= rem ) { quot = quot + t; rem = rem - prod; } static if( isUnsigned!TNum ) { prod >>>= 1; t >>>= 1; } else { prod >>= 1; t >>= 1; } } remainder = rem; return quot; } void main( string[] args ) { if( args.length < 3 ) return; long dividend = args[1].to!long; long divisor = args[2].to!long; long remainder = 0; long result = divide( dividend, divisor, remainder ); if( remainder == 0 ) "%s / %s = %s".writefln( dividend, divisor, result ); else "%s / %s = %s (r %s)".writefln( dividend, divisor, result, remainder ); } ``` Obviously `/` appears in the code, but it's in a string and is just for output. There's no string interpolation in D, so it's not diving anything. [Answer] # 64 characters in Ruby ``` def d a,b;x=0;while((x+1)*b<=a);x+=1;end;puts"#{x} #{a-x*b}";end ``` Example: ``` pry(main)> d 31,6 5 1 => nil ``` [Answer] **C 371 with whitespaces** Includes cases for div by zero and divisor<0. Uses subtraction loop. ``` #include <stdio.h> int a, b, n, r; void e(int i, int j){ printf("Output: %d %d\n", i, j); } void g() { if (scanf_s("%d %d", &a, &b)) { r = 1; if (b < 0){ r = -1; b = r*b; } if (!b) e(0, 0); else{ if (b>a){ n = 0; } else{ n = 1; while ((a -= b) >= b){ n++; } } e(r*n, a); } } } int main(){ g();} ``` [Answer] ## Brainfuck *works only for numbers between 1 and 9* Do not fit the rules, so I don't expect to win but answers in brainfuck are always awesome. ``` ++++++++>,>,<<[>------>------<<-]>[->-[>+>>]>[+[-<+>]>+>>]<<<<<]++++++++[>>++++++>++++++<<<-]>>>.<. ``` [Based on `divmod` method](http://esolangs.org/wiki/Brainfuck_algorithms#Divmod_algorithm) Test it here (and try to change input) : <http://ideone.com/9L2yYf> Some tests : > > 74 returns 13 > > 82 returns 40 > > 92 returns 41 > > > [Answer] **Edited:170 with Excel VBA:** ``` Sub Long_Div(n As Integer, d As Integer) j = 1 If d <> 0 Then If (n * d) < 0 Then j = -1 End If Do While (Abs(n) >= Abs(d)) n = Abs(n) - Abs(d) i = i + 1 Loop MsgBox i * j & " " & n Else: MsgBox "can't divide by zero" End If End Sub ``` [Answer] # C Sorry for the bulky code, I am still a noob. The idea is to grab the first piece of bits from n such that k < bits, then extract each bit of n from that point on and update remainder and quotient along the way. ``` #include <stdio.h> unsigned int rightMostBit(unsigned int n){ unsigned int bitmask=0x1 << 31; int position=31; while((bitmask & n)==0 && position>=0){ position-=1; bitmask = bitmask>>1; } return position; } unsigned int extractBits(unsigned int n, unsigned int start, unsigned int end){ unsigned int unitMask=0x1; unsigned int mask=unitMask << start; for(int i=start;i<end;i++){ mask= (mask | (mask << 1)); } return ((mask & n) >> start); } void longDivision(unsigned int n, unsigned int k) { unsigned int q=0; unsigned int head=rightMostBit(n); int tail=head; unsigned int r=extractBits(n,tail,head); while(k>r && tail>=0){ tail-=1; r=extractBits(n,tail,head); } unsigned int pointMask= 0x1 << tail; while(pointMask>0) //scan all bits of n { if(k<= r){ //If k less than r, we can do division r-= k ; //subtraction q=q << 1; //make space q = q | 0x1; //add a 1 to quotient }else{ q=q << 1; //make space q= q | 0x0; //k > r, so add 0 to quotient } pointMask=pointMask >> 1; if(pointMask!=0){ if((pointMask & n)){ r=((r << 1) | 1); }else{ r=((r << 1) | 0); } } } printf("quotient: %d, remainder: %d \n",q,r); } ``` [Answer] # Python # Advantages: * Go as Precise as you want or can handle * Find out the repetitiveness from the quotient * Fast Late to the party but here you go: ``` def ManualDivision(Dividend, Divisor, acQPrecision, BreakOnRepetitive): Repetitive = False RepetitiveIndex = 0 bcQComplete = False acQComplete = False bcQ = '' #before comma Quotient acQ = '' #after comma Quotient history = [] a = 0 b = 0 while (not bcQComplete or not acQComplete): if not bcQComplete: for digit in map(int, str(Dividend)): a = int(str(a) + str(digit)) if a in history: if not Repetitive: Repetitive = True RepetitiveIndex = len(history) - len(bcQ) if BreakOnRepetitive: break else: history.append(a) if a < Divisor: b = 0 bcQ += '0' else: pQ = 0 result = a - Divisor while result >= 1: pQ += 1 result -= Divisor b = pQ * Divisor bcQ += str(pQ) a -= b bcQComplete = True if not acQComplete: acQPrecision -= 1 if acQPrecision <= 0: acQComplete = True a = int(str(a) + str('0')) if a in history: if not Repetitive: Repetitive = True RepetitiveIndex = len(history) - len(bcQ) if BreakOnRepetitive: break else: history.append(a) if a < Divisor: b = 0 acQ += '0' else: pQ = 0 result = a - Divisor while result >= 1: pQ += 1 result -= Divisor b = pQ * Divisor acQ += str(pQ) a-=b return '{0}.{1} \nRepetitive: {2} from position {3} acQ \nHistory:{4}'.format(bcQ, acQ, Repetitive, RepetitiveIndex, history) ``` # Result ``` Quotient = ManualDivision(91,256,100,False) #Dividend = 91, Divisor = 256, precision= 100, breakonrepetitive=False print(Quotient) ``` > > 00.3554687499999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 > > > Repetitive: True from position 9 acQ > > > History:[9, 91, 910, 1420, 1400, 1200, 1760, 2240, 1920, 1280, 2560] > > > [Answer] ## Python Using recursion ``` def divide(a, b, q=0): if a < b: return (q, a) return divide(a - b, b, q+1) ``` ]
[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/11940/edit). Closed 5 years ago. [Improve this question](/posts/11940/edit) **The challenge is to display and scroll a sine waveform in the least number of characters.** **Restrictions:** * Total height of wave must be at least seven units (characters, pixels, etc). * The generated wave must scroll in-place. **Additional Rules/Information:** * The sine wave must be distinguishable from triangle and square waves. + "distinguishable" indicates sampling at least every π/8 **Additional Judgement Criteria:** * Appearance/Quality of the wave * Number of periods displayed Winning entries will have the fewest characters of code and generate a sine wave with the most samples per period. [Answer] ## Mathematica : 49 ``` Plot[Sin[x+a],{x,0,9},Axes->None]~Animate~{a,0,2Pi} ``` ![enter image description here](https://i.stack.imgur.com/VMRv3.gif) The flickering is a GIF-produced artifact. Runs smoothly on the screen. [Answer] ## APL (46) ``` {∇⍵+1⊣⎕DL÷9⊣⎕SM∘←↑⍵∘{0,⍵,⍨9+⌈9×1○9÷⍨⍺+⍵}¨⍳79}1 ``` It looks like this, and scrolls to the left: ![sine](https://i.stack.imgur.com/EoPVJ.png) In action: <http://frankenstein.d-n-s.org.uk/~marinus/sine.mp4> [Answer] ## Machine code x86 16-bit DOS, 40 bytes ░‼═►h áë←☺‼▀♥▐4┘■▐♀▐♦▀←i;@☺&ê◄■├uσBδ╪ ![Recorded from dosbox](https://i.stack.imgur.com/iUWRw.gif) Or in a more human readable format (typical hugi conventions followed) : ``` ; 40 byte version ; 00000000: 0A 00 B0 13 CD 10 68 00-A0 07 89 1B 01 13 DF 03 ......h......... ; 00000010: DE 34 D9 FE DE 0C DE 04-DF 1B 69 3B 40 01 26 88 .4........i;@.&. ; 00000020: 11 FE C3 75 E5 42 EB D8 ...u.B.. ; 42 byte version ; 00000000: 0A 00 B0 13 CD 10 68 00-A0 07 89 1B 01 13 DF 03 ......h......... ; 00000010: DE 34 D9 FE DE 0C DE 04-DF 1B 69 3B 40 01 26 88 .4........i;@.&. ; 00000020: 11 FE C3 75 E5 42 E2 FE-EB D6 ...u.B.... [bits 16] newscreen: or al,[bx+si] ; trade off vertical height for # of periods mov al,13h int 10h push 0a000h pop es iter: mov word [bp+di],bx add word [bp+di],dx fild word [bp+di] fidiv word [si] fsin fimul word [si] fiadd word [si] fistp word [bp+di] imul di,word [bp+di],320 mov [es:di+bx],dl inc bl jnz iter inc dx delay: loop delay ; can remove this to get 40 bytes, but wont look as good since it scrolls too fast jmp newscreen ``` [Answer] # q Quick and very ugly, 119 characters: ``` o:0; w:.:["\\c"]1; .z.ts:{-1@'{@[w#" ";where x=y;:;"0"]}[4-7h$4*sin o rotate(til w)%2*acos -1]'[til 9];o::o+1}; \t 100 ``` [Answer] # Processing, 99 Really just a butchered version of [this](http://processing.org/examples/sinewave.html). ``` float i,x,t;void draw(){clear();x=t+=0.02;for(i=0;i<75;ellipse(i++*5,50+sin(x+=0.418879)*25,3,3));} ``` [Try it online!](http://www.openprocessing.org/sketch/101967) Could've saved some characters at the cost of an uglier animation. Slightly more readable form: ``` float i,x,t; void draw() { clear(); x = t+=0.02; for(i=0; i<75; ellipse(i++*5, 50+sin(x+=0.418879)*25, 3, 3)); } ``` Magic numbers: * `0.02` kinda affects the scroll speed * `75` is the number of dots * `5` is the distance on x-axis * `50` is the y-position on screen (default window size is 100). * `0.418879` ≈ 2π/75\*5 * `25` is the amplitude * `3` is the size of the dots [Answer] ## Python 2.7 with Pygame (~~196~~ 178) ``` import math,pygame as p D=p.display x=0 s=D.set_mode((600,400)) while 1: i=0;x+=1;D.flip();s.fill([0]*3) while i<600:s.set_at((i,int(200*math.sin((i+x)*.01)+200)),[255]*3);i+=1 ``` Draws in pixels. Went for looks rather than characters. [Answer] # Ruby, 105 characters ``` d=0 loop{s=(1..9).map{" "*79} 79.times{|i|s[(Math.sin((i+d)*Math::PI/16)*4+4.5)][i]=?x} puts"^[[H",s d+=1} ``` The `^[` is a single escape character. (You can enter it with `Ctrl`-`V`,`Esc` in the terminal and Vim or `Ctrl`-`Q`,`Esc` in MCEdit and Emacs.) The animation is displayed from the 2nd line of top left corner of the terminal and scrolls from right to left at full speed (add `sleep 0.1;` before the last `}` to slow it down). Sample run: ``` bash-4.4$ ruby -e 'd=0;loop{s=(1..9).map{" "*79};79.times{|i|s[(Math.sin((i+d)*Math::PI/16)*4+4.5)][i]=?x};puts"^[[H",s;d+=1}' xxxxx xxxxx xx xx xx xx xx xx xx xx x x x x x x x x x x x x x x xx xx xx xx xx xx xx xx xx xx xx xx xxxxx xxxxx xxxxx ``` ### Ruby: 115 characters ``` d=0 while 1 s=(1..9).map{" "*79} 79.times{|i|s[(Math.sin((i+d)*Math::PI/16)*4+4.5)][i]=?x} $><<"\e[H"+s*$/ d+=1 end ``` The animation is displayed in the top left corner of the terminal and scrolls from right to left at full speed (add `sleep 0.1;` before the `end` keyword to slow it down). Sample run: ``` xxxxx xxxxx xx xx xx xx xx xx xx xx x x x x x x x x x x x x x x xx xx xx xx xx xx xx xx xx xx xx xx xxxxx xxxxx xxxxx bash-4.1$ ruby -e 'd=0;while 1;s=(1..9).map{" "*79};79.times{|i|s[(Math.sin((i+d)*Math::PI/16)*4+4.5)][i]=?x};$><<"\e[H"+s*$/;d+=1;end' ``` (I know, can be shortened by replacing `Math::PI/16` with its precalculated value of arbitrary precision. For example to 107 characters by using 0.2 multiplier. But the lower the precision, the uglier the output. May edit it in the future, I just keep it for now.) [Answer] ## Maple, 42 Characters This is very easy to do with Maple. ``` plots[animate](plot,[sin(x+a)],a=0..2*Pi); ``` What it does ![enter image description here](https://i.stack.imgur.com/FFRXB.gif) [Answer] # TI-BASIC, 22 bytes * Name this `prgmA`. It eventually overflows the stack by calling itself, throwing an `ERR:MEMORY`; this can be rectified in exchange for 4 bytes by adding `While 1` to the beginning and replacing the `prgmA` line with `End`. * It works pretty much perfectly, although I'm afraid not much can be done to improve its speed. * It's currently the winner by far, but can be 'golfed' to 18 bytes by removing the step argument (`,.01`) from the `For(` loop, lowering its "Number of periods displayed" score. --- ``` For(A,0,6,.01 ClrDraw DrawF 7sin(X+A End prgmA ``` [Answer] ## C (65) ``` main(int x){for(;;)printf("%*c\n",(int)(22+20*sin(x++/5.)),'x');} ``` Note: plots sine wave with X axis vertical and therefore scrolls vertically. [Answer] ## JavaScript: 265 characters + 59 HTML ``` <canvas id=c width=99 height=99></canvas> <script> var c=document.getElementById("c");var context=c.getContext("2d");context.beginPath();var s=0;setInterval(function(){c.width=c.width;s++;context.moveTo(0+50,50*Math.sin(s+0)+50);for(var e=1;e<99;e++){context.lineTo(e+50,50*Math.sin(s+50*e)+50)}context.stroke()},50) </script> ``` ## JavaScript (ungolfed) ``` <canvas id="canvas" width="500" height="99"></canvas> <script> var c = document.getElementById("canvas"); var context = c.getContext("2d"); context.beginPath(); var s=0; setInterval(function(){ c.width = c.width; s++; context.moveTo(0+50,50*Math.sin(s+0)+50); for(var x=1;x<99;x++){ context.lineTo(x+50, 50*Math.sin(s+50*x)+50); } context.stroke(); }, 50); </script> ``` See it on <http://jsfiddle.net/MartinThoma/uv5Xx/> [Answer] # Processing, 115 chars This one actually draws a pseudo-sine wave, not an actual sine wave: ``` int t,i,c;void draw(){clear();beginShape();for(i=-1,c=50;i<6;c=-c)curveVertex(50*i++-t,50+c);endShape();t=t%100+1;} ``` A more readable version: ``` int t, i, c; void draw() { clear(); beginShape(); for(i=-1, c=50; i<6; c=-c) curveVertex(50*i++ - t, 50+c); endShape(); t = t%100 + 1; } ``` [Answer] # Mathematica, 38 bytes ``` Animate[Plot[Sin[x+a],{x,0,10}],{a,5}] ``` Non-competeting, uses Mathematica 10 [Answer] # SmileBASIC The rules aren't entirely clear, so I'll post a few different answers: ## 34 bytes (vertical text): ``` LOCATE SIN(MILLISEC/9)*9+9,?.EXEC. ``` (It never specifically says this isn't allowed, but none of the other answers are vertical, so I'm not sure) ## 43 bytes (horizontal text): ``` LOCATE,SIN(MILLISEC/9)*9+9?0SCROLL-1,.EXEC. ``` ## 53 bytes (horizontal graphics): ``` GPSET 1,SIN(MILLISEC/9)*9+9GCOPY.,0,#R,30,1,0,1 EXEC. ``` ]
[Question] [ Given a number determine if it is a circular prime. A circular prime is a prime where if you rotate the digits you still get prime numbers. 1193 is circular prime because 1931 and 9311 and 3119 are all primes. ``` Input: Output: 1193 circular 11939 circular 1456 nothing 193939 circular 1111111 nothing 7 circular 23 nothing ``` Shortest code wins. [Answer] # J, 47 chars (w/ formatted output) ``` ('nothing';'circular'){~*/1&p:".(|."0 1~i.&#)": ``` # J, 23 chars (boolean only) ``` */1&p:".(|."0 1~i.&#)": ``` `":` is a string conversion; `i.&#` produces a range of integers [0,len), and `|."0 1~` is a rotation of the string by each successive integer of the range. `".` converts the list of rotations back into numbers, `1&p:` converts the list of numbers into booleans (i.e. "prime?" predicate), and `*/` is a multiply reduce over the booleans (i.e. and). [Answer] ## Python, 106 chars ``` p=input();n=`p` for i in n: n=n[1:]+n[0];e=2 while`e`!=n:p*=int(n)%e;e+=1 print'cniortchuilnagr'[p<1::2] ``` [Answer] # Mathematica ~~62~~ 61 ``` f@s_ := And @@ PrimeQ[FromDigits@StringRotateLeft[s, #] & /@ Range@9] ``` **Usage** ``` f["1193"] ``` > > True > > > ``` f["11939"] ``` > > True > > > ``` f["1456"] ``` > > False > > > ``` f["193939"] ``` > > True > > > ``` f["1111111"] ``` > > False > > > ``` f["7"] ``` > > True > > > ``` f["23"] ``` > > False > > > [Answer] ## Mathematica, ~~75~~ 64 ``` And@@PrimeQ[FromDigits/@NestList[RotateLeft,IntegerDigits@#,9]]& ``` [Answer] ## Ruby, ~~110~~ 109 chars ``` require'mathn' x=gets.chop.split'' puts (0..x.size).all?{|n|x.rotate(n).join.to_i.prime?}?:circular:'nothing' ``` [Answer] ### GolfScript, 47 characters ``` :s,,{)s/(+~:P{(.P\%}do(},!"nothing circular"n/= ``` Input must be given on STDIN without trailing newline ([online example](http://golfscript.apphb.com/?c=IjExOTMiCgo6cywseylzLygrfjpQeyguUFwlfWRvKH0sISJub3RoaW5nCmNpcmN1bGFyIm4vPQ%3D%3D&run=true)). [Answer] ## R, 139 ``` a=scan() p=0 A=nchar(a) S=substr for(i in 1:A){b=as.integer(paste0(S(a,i+1,A),S(a,1,i)));p=p+!sum(!b%%1:b)<3} c('nothing','circular')[!p+1] ``` [Answer] # Python3.3, 160C ``` def m(): s=input() r=range for i in r(len(s)): a=int(s) if all(a%i for i in r(2,a)):return 0 s=s[1:]+s[:1] return 1 print("cniortchuilnagr"[m()::2]) ``` [Answer] # APL, 53 ``` 'nothing' 'circular'[1+^/{⌊/⍵|⍨1↓⍳⍵-1}¨⍎¨{⍵⌽∆}¨⍳⍴∆←⍞] ``` [Answer] # Smalltalk, 195 chars ``` [:x|r:=[:n|(n\\10)*(10 raisedTo:n log floor)+(n//10)].s:=OrderedCollection with:x.[(m:=r value:s last)=x]whileFalse:[s add:m].^(s allSatisfy:[:each|each isPrime])ifTrue:['circular']ifFalse:['nothing']] ``` formatted ``` [:x| r:=[:n|(n\\10)*(10 raisedTo:n log floor)+(n//10)]. s:=OrderedCollection with:x. [(m:=r value:s last)=x]whileFalse:[s add:m]. ^(s allSatisfy:[:each|each isPrime])ifTrue:['circular']ifFalse:['nothing']] ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 23 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Would obviously be a hell of a lot shorter without the unnecessarily strict output requirement, which accounts for more than half the score here. ``` ÆìéX jÃ×g`Í(ˆg circÔ³`¸ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xuzpWCBqw9dnYM0oiGcgY2lyY9SzYLg&input=WwoxMTkzCjExOTM5CjE0NTYKMTkzOTM5CjExMTExMTEKNwoyMwpdLW1S) (includes all test cases) ``` ÆìéX jÃ×g`...`¸ :Implicit input of integer U Æ :Map each X in the range [0,U) ì : Convert U to digit array éX : Rotate right X times and convert back to integer j : Is prime? à :End map × :Reduce by multiplication g :Index into (0-based) `...` : Compressed string "circular nothing" ¸ : Split on spaces ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~22~~ 19 bytes ``` ?¨ÿċ◊¨¨ø±¨ΛoṗdSṀṙŀd ``` [Try it online!](https://tio.run/##ATIAzf9odXNr//8/wqjDv8SL4peKwqjCqMO4wrHCqM6bb@G5l2RT4bmA4bmZxYBk////MTE5Mw "Husk – Try It Online") -3 bytes from Jo King. (simplified using `Ṁ`) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 6 bytes *-1 thanks to @ovs!* ``` gL._pP ``` Outputs `1` if a circular prime, and `0` if not! :D [Try it online!](https://tio.run/##yy9OTMpM/f8/3UcvviDg/39DQ0tjAA) This is actually my first effortful code answer in this site! **Yey!** ## How? ``` g # Get the number of digits in the input number. L # Push a list of all numbers from 1 to the length. ._ # For each number 'n' in the list, rotate the input to to the left n times and push a list of all outcomes. p # Is each rotation a prime? If prime, convert that number to 1, else convert it to 0. P # Push the product of all 1's or 0's (if a rotation is not prime, the product should be zero). # Print the product automatically. ``` --- # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 16 bytes *Again -1 thanks to @ovs!* ``` gL._pP“‹ë“si“ÒŽ“ ``` This code follows the output standard suggested by the test cases. I wrote this just in case my previous answer is invalid. If it is not, please count 6B as my score! [Try it online!](https://tio.run/##yy9OTMpM/f8/3UcvviDgUcOcRw07D68G0sWZQOLwpKN7gdT//4aGlsYA) ## How again? ``` gL._pP # Works just like the previous answer. “‹ë“ # Push the string "nothing" from the 05AB1E dictionary. s # Bring back the number output again. i # If the number is 1... “ÒŽ“ # Push the string "circular" again from the 05AB1E dictionary. ``` Thanks to [@Kevin Cruijssen's tip on compressing strings](https://codegolf.stackexchange.com/a/166851/98140)! :) *Edit:* Wow, I noticed that both of my answers are currently the shortest (during the time of writing). That is kind of ironic for a first effortful answer. That means I won! ]
[Question] [ # Enterprise Quality Code! ### TL;DR * Answers will consist of a full program (**of length < 30k**) prints the the first N Prime numbers (as a base 10 representation without leading zeros unless the chosen language only supports unary or other based output) separated by newlines (optional trailing linefeed). * You may post cracks at any time, but you must wait one hour after posting each initial bowled submission * Leading or trailing whitespace is not acceptable (except for the trailing newline) * An answer's score is the number of bytes in the answer. A user's score is the total number of bytes of all uncracked answers. * An answer gets cracked when another user posts an answer (in the same language) which is a permutation of any subset of the characters used in the original answer. * The user with the highest score will receive an accepted tick mark on his /her highest scoring post (although it doesnt really matter which specific post gets the tick) --- [The Inspiration for this challenge](https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition) --- At Pretty Good consultants there is a focus on writing "quality" verbose code that is sufficiently engineered. Your boss has decided to test you on your skills. --- Consider the set of all [programming languages](http://meta.codegolf.stackexchange.com/a/2073/46918) in existence before the posting of this challenge. For this challenge there will technically be one individual "winner" in each language, however the boss will give a ~~promotion~~ accepted tick mark to only one answer based on your score. --- # Detailed Spec The goal of this challenge is to [receive](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) an integer N strictly smaller than 2^8-1 and print the first N prime numbers (in less than 24 hours) separated by your platforms choice of new line (a trailing newline is optional). [OEIS sequence A000040](https://oeis.org/A000040) in as **many bytes** as possible in as many languages as possible. However, note that others vying for the promotion will try to "help" you by **golfing** down your score. (Please note that your prime generation function should *theoretically* work for integer N inputs strictly smaller than 2^16-1 given enough time, the bounds for N have been reduced after realizing how slow some interpreters are (namely mine) hardcoding the list of primes is strictly forbidden) Sample output for an input 11 ``` 2 3 5 7 11 13 17 19 23 29 31 ``` --- ## How to participate Pick any language X, but please avoid selecting a language which is just another version or derivative of another answer. If there is no existing answer in language X than you will write a program (which must fit into a single post **I.E it must be less than 30k characters**) that solves this challenge. The length in bytes of the source (in any reasonable preexisting textual encoding) will be **added** to your score. You must avoid using any unnecessary characters for reasons that will soon become apparent. If language X already has been used to answer this question, then you must answer using any permutation of any proper subset of the characters used in the shortest answer (I.E take the shortest X answer and remove some (>=1) characters and optionally rearrange the resulting code). The previous holder of the shortest X answer will lose **all** of the bytes provided by his answer from his score, and the number of bytes of your submission will now be added to your score. The number of bytes golfed off gets "lost" forever. --- ### Rules for Languages You may only crack a submission by posting an answer in the same language (and version), but you are barred from posting an answer in language X if there exists a submission in a sufficiently similar language Y. Please do not abuse this rule posting an answer in a sufficiently similar language will receive disqualification. --- Below is a leader board which removes answers with "cracked" (with any case) in their header. ``` var QUESTION_ID=90593,OVERRIDE_USER=46918;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return a-r});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)^(?:(?!cracked)\i.)*[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15410 bytes ``` 0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘b⁹‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ḤỌ;”€vj⁷ ``` Crack of [@Dennis's entry](https://codegolf.stackexchange.com/a/90668/53748) His was: taking `0`; incrementing to 25383 using `‘`; doubling to 50766 using `Ḥ`; converting to base 256 with `b⁹` to get [198, 78]; then casting to characters with `Ọ` to yield ÆN Mine is: taking `0`; incrementing to 15360 using `‘`; converting to base 256 with `b⁹` to get [60, 0]; incrementing to [99, 39] using `‘`; doubling to [198, 78] using `Ḥ`; then casting to characters with `Ọ` to yield ÆN [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25,394 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ([cracked](https://codegolf.stackexchange.com/a/90693/12012)) ``` 0‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘Ḥb⁹Ọ;”€vj⁷ ``` Let's hope I didn't miss something obvious... [Try it online!](http://jelly.tryitonline.net/) You have to copy-paste the code yourself; the URI cannot hold. [Answer] # [MATL](http://github.com/lmendo/MATL), 5 bytes Note sure I get how this challenge works, but here it goes. ``` :Yq"@ ``` [Try it online!](http://matl.tryitonline.net/#code=OllxIkA&input=MTA) [Answer] # Ruby, 25209 bytes ``` require"_________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________".size.*(1331).to_s 35 puts Prime.take gets.to_i ``` [Demo at ideone](https://ideone.com/smXDN0). That's a string consisting of 25153 underscores and nothing else (25153\*1331 base 35 is "mathn"), the site formatting might mess with it a bit. [Answer] # Mathematica, 32 bytes ``` Map[Print,Prime[Range[Input[]]]] ``` I mean, there's not much secretive bowling that can be done in this language. [Answer] # C#, 27573 bytes - [cracked!](https://codegolf.stackexchange.com/a/184936/84206) Cracks [Jonathan Allan's answer](https://codegolf.stackexchange.com/questions/90593/enterprise-quality-code-prime-sieve/91005#91005) by 18 characters, namely: `00ijjfff++==;;;;()`. ``` static void Main(){int n=int.Parse(System.Console.ReadLine()),v=30*" ... 27387 '[' characters ... ".Length,c=0,p=0,f,j;while(c<n){j=f=0;while(++j<v)if(p%j==0)f++;f--;if(--f==0){System.Console.WriteLine(p);c++;}p++;}} ``` Test it on [**ideone**](https://ideone.com/FxnIIZ)! The characters are saved as follows: 1. `j=0;j++;f=0;` is rearranged to `j=f=0;j++`, giving `0;` (2 saved) 2. `j++;while(j<v){if(p%j==0)f++;j++;}` is rearranged to `while(++j<v)if(p%j==0)f++;`, taking both the `j++`s into the `while` statement, making it one statement, which allow me to remove the `{}`. This step gives me `j;j++;` (6 + 2 = 8 saved), leaving the `{}` for later use. 3. The two sequential `if(f==0)` statements are merged with the remaining `{}`, giving a full `if(f==0)` (8 + 8 = 16 saved). 4. `f--;if(f==0)` is changed to `if(--f==0)`, giving the last `f;` (2 + 16 = 18 saved). [Answer] # R, 87 bytes ``` f=function(n){u=t=1;while(t<n+1){u=u+1;if(which(!u%%1:u)[1+1]==u){cat(u,"\n");t=t+1}}} ``` Loops through numbers until it has found n primes. [Answer] # Python 3, 117 bytes ``` def p(i): r=[] d=2 while i: if all(d%e for e in r): r+=[d] i-=1 d+=1 print('\n'.join(str(e)for e in r)) ``` A shorter version of [@JonathonAllan's answer](https://codegolf.stackexchange.com/a/90672/55526). `all` evaluates to `True` for empty generator expressions, so `r` can initially be defined as the empty list and `d` as `2`, rather than `r=[2]` and `d=3` in the original. However, this leads to one too few primes being printed, so `i>1` can be changed to just `i`. [Try it on Ideone](http://ideone.com/mWDqQG) [Answer] # Octave, 65 bytes ``` for k=primes((true+true)^(z=input('')))(1:z),disp(num2str(k)),end ``` Here's an example run. The first `10` is the input, the numbers after that are the output. [![enter image description here](https://i.stack.imgur.com/4VIJb.png)](https://i.stack.imgur.com/4VIJb.png) [Answer] # Java, ~~204 205 204~~ 203 bytes [**cracked!**](https://codegolf.stackexchange.com/a/91222/53748) Crack of one of [Rohan Jhunjhunwala's submission](https://codegolf.stackexchange.com/a/90702/53748)s. ``` class y{public static void main(String[]b){int n=2,l=870119,i,f,j;i=new java.util.Scanner(System.in).nextInt();while(i>0){f=0;for(j=1;j<l;j++){if(n%j==0){f++;}}if(f==2){System.out.println(n);i--;}n++;}}} ``` The spec said it only needs to work up to the 2^16-1 = 65535th prime (821603). We can remove the `string x="z...z"` and the loop to increment this value and set `l` to be a working value greater than or equal to 821603. In removing that we can also remove the initialisation of `i`, so we get ne numeric characters `0791819` to use. The smallest valid, working value for `l` is now 870119. Test it on [**ideone**](http://ideone.com/dCNntx) [Answer] # C#, 27569 bytes ``` static void Main(){int n=int.Parse(System.Console.ReadLine()),c=0,p=0,f,j;while(c<n){j=f=0;while(++j<30*"27387 '[' characters".Length)if(p%j==0)f++;f--;if(--f==0){System.Console.WriteLine(p);c++;}p++;}} ``` Cracks [Scepheo's answer](https://codegolf.stackexchange.com/a/91135/84206). Bytes shaved off: `vv=,` [Try it online!](https://tio.run/##7d2xSsNgFAXgVykFIbFNiDq2mVxbEB0cnEL8YxNqEpqgSOmzx1acnHyA74N7hsN9h1MOSdkdwlTui2GYbY/TMBZjXc4@uvp1ti3qNoqPdTvO2vyc6UNxGEL09DWM4T2979qh24f0MRSvm7oNURwvyzxb9uerls3qc1fvQ1Su2/jY5FWe/RaLRbO@y67nLwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8D/zdBPat3EX11XUXzV5nsXVYrGqkmR1bpKkujTHPzNbz4d6DD87W328Ks/vp/4Sp@k03dx@Aw "C# (.NET Core) – Try It Online") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 3794 bytes I either missed something on my first run through or the specs changed while I was working on this, but it Turns out this is an invalid submission. I will be following up with a working one. (Hopefully) [Try It Online!](http://brain-flak.tryitonline.net/#code=KHt9PCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgpKCkpKCkpKCkoKSkoKSgpKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSgpKCkpKCkoKSko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KSkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKSgpKCkoKSgpKSgpKCkpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSgpKCkoKSgpKSgpKCkoKSgpKSgpKCkoKSgpKCkoKSgpKCkpKCkoKSgpKCkpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSkoKSgpKCkoKSkoKSgpKCkoKSgpKCkpKCkoKSkoKSgpKCkoKSl7KHt9PD4pPD59PD4-KXsoe31bKCldPCh7fTw-KTw-Pil9e317e319PD57KHt9PD4pPD59PD4&input=MjU1) ``` ({}<(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((()())())()())()())()()()())()())()()()())()())()()()())()()()()()())()())()()()()()())()()()())()())()()()())()()()()()())()()()()()())()())()()()()()())()()()())()())()()()()()())()()()())()()()()()())()()()()()()()())()()()())()())()()()())()())()()()())()()()()()()()()()()()()()())()()()())()()()()()())()())()()()()()()()()()())()())()()()()()())()()()()()())()()()())()()()()()())()()()()()())()())()()()()()()()()()())()())()()()())()())()()()()()()()()()()()())()()()()()()()()()()()())()()()())()())()()()())()()()()()())()())()()()()()()()()()())()()()()()())()()()()()())()()()()()())()())()()()()()())()()()())()())()()()()()()()()()())()()()()()()()()()()()()()())()()()())()())()()()())()()()()()()()()()()()()()())()()()()()())()()()()()()()()()())()())()()()())()()()()()())()()()()()()()())()()()()()())()()()()()())()()()())()()()()()())()()()()()()()())()()()())()()()()()()()())()()()()()()()()()())()())()()()()()()()()()())()())()()()()()())()()()())()()()()()())()()()()()()()())()()()())()())()()()())()()()()()()()()()()()())()()()()()()()())()()()())()()()()()()()())()()()())()()()()()())()()()()()()()()()()()())()())()()()()()()()()()()()()()()()()()())()()()()()())()()()()()()()()()())()()()()()())()()()()()())()())()()()()()())()()()()()()()()()())()()()()()())()()()()()())()())()()()()()())()()()()()())()()()())()())()()()()()()()()()()()())()()()()()()()()()())()())()()()())()()()()()())()()()()()())()())()()()()()()()()()()()())()()()())()()()()()())()()()()()()()())()()()()()()()()()())()()()()()()()())()()()()()()()()()())()()()()()()()())()()()()()())()()()()()())()()()())()()()()()()()())()()()()()())()()()())()()()()()()()())()()()())()()()()()()()()()()()()()())()()()()()()()()()())()()()()()()()()()()()())()())()()()()()()()()()())()())()()()())()())()()()()()()()()()())()()()()()()()()()()()()()())()()()())()())()()()())()()()()()()()()()()()()()())()()()())()())()()()())()()()()()()()()()()()()()()()()()()()())()()()())()()()()()()()())()()()()()()()()()())()()()()()()()())()()()())()()()()()())()()()()()())()()()()()()()()()()()()()())()()()())()()()()()())()()()()()())()()()()()()()())()()()()()())()()()()()()()()()()()())()()()())()()()()()())()())()()()()()()()()()())()())()()()()()())()()()()()()()()()())()())()()()()()()()()()())()())()()()()()())()()()()()()()()()()()()()()()()()())()()()())()())()()()())()()()()()())()()()()()())()()()()()()()())()()()()()())()()()()()())()()()()()()()()()()()()()()()()()()()()()())()())()()()()()()()()()())()()()()()()()())()()()()()()()()()())()()()()()())()()()()()())()()()()()()()())()()()()()()()()()()()())()()()())()()()()()())()()()()()())()())()()()()()())()()()()()()()()()()()())()()()()()()()()()())()()()()()()()()()()()()()()()()()())()())()()()())()()()()()())()())()()()()()())()()()())()())()()()())()()()()()()()()()()()())()())()()()()()())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())()()()()()())()()()()()())()()()()()()()())()()()()()()()()()()()()()()()()()())()()()()()()()()()())()()()()()()()()()()()()()())()()()())()())()()()())()()()()()())()()()()()()()())()()()())()())()()()()()())()()()()()()()()()()()())()()()()()()()()()())()())()()()())()())()()()())()()()()()())()()()()()()()()()()()())()()()()()()()()()()()())()()()()()()()())()()()()()()()()()()()())()()()()()())()()()())()()()()()())()()()()()()()())()()()())()()()()()()()())()()()())()()()()()()()()()()()()()())()()()())()()()()()())()())()()()()){({}<>)<>}<>>){({}[()]<({}<>)<>>)}{}{{}}<>{({}<>)<>}<> ``` Here's a breakdown of the characters for you: * `[]`: 1 * `<>`: 11 * `{}`: 11 * `()`: 1874 Good luck. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` j.fP_ ``` [Try it online!](http://pyth.herokuapp.com/?code=j.fP_&input=255&debug=0) I still don't understand this challenge. How come in this [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") it is not that we must have a crack ourselves? Like, I would expect that we are to post a longer version that does the task, and then the robber would golf the code. [Answer] # SQLite, 170 bytes ``` WITH c(i)AS(SELECT 2 UNION SELECT i+1 FROM c LIMIT 1609),p AS(SELECT i FROM c WHERE(SELECT COUNT()FROM c d WHERE i<c.i AND c.i%i=0)=0)SELECT*FROM p LIMIT(SELECT n FROM i) ``` The input N is taken from a table; create it with, e.g., `CREATE TABLE i AS SELECT 42 AS n;`. [SQLFiddle](http://www.sqlfiddle.com/#!5/651e0/2) [Answer] ## Haskell, 238 bytes ``` p n m 2=compare n m==LT p n m d=if compare n m==LT then False else if mod n m==0then p n(m+1)(d+1)else p n(m+1)d d z y x=if z==x then return()else if p y 1 0then do putStrLn(show y) d(z+1)(y+1)x else d z(y+1)x main=do n<-readLn d 0 1n ``` This is a shorter version of [@Laikoni's answer](https://codegolf.stackexchange.com/a/90631/34531). I've just replaced `getLine` and `(read n)` by `readLn` and `n`. [Answer] # Haskell, 246 bytes, [cracked](https://codegolf.stackexchange.com/a/90661/56433) ``` p n m 2=compare n m==LT p n m d=if compare n m==LT then False else if mod n m==0then p n(m+1)(d+1)else p n(m+1)d d z y x=if z==x then return()else if p y 1 0then do putStrLn(show y) d(z+1)(y+1)x else d z(y+1)x main=do n<-getLine d 0 1(read n) ``` [Try it on Ideone.](http://ideone.com/vHSlhc) I tried to provide as few operators as possible to prevent more sophisticated shorter solutions. Hopefully I didn't overlook some unnecessary white space. [Answer] ## Pyke, 19 bytes ``` 821603S#_P)FoQ<I))K ``` [Try it here!](http://pyke.catbus.co.uk/?code=821603S%23_P%29FoQ%3CI%29%29K&input=5) The timeout on the website is too small to run in under 5 seconds so you can decrease the first number to get it to work online [Answer] # [S.I.L.O.S](https://esolangs.org/wiki/S.I.L.O.S), 163 bytes ``` readIO : a = 2 lblM b = i b - y if b c GOTO E lblc d = 2 lblI c = a c - d c - 1 if c d y + 1 printInt a GOTO i lbld z = a z % d d + 1 if z I lbli a + 1 GOTO M lblE ``` Nothing in particular was done to arbitrarily lengthen this code, but it should remain safe. (Emphasis on "should") Feel free to [try this code online!](http://silos.tryitonline.net/#code=cmVhZElPIDoKYSA9IDIKbGJsTQpiID0gaQpiIC0geQppZiBiIGMKR09UTyBFCmxibGMKZCA9IDIKbGJsSQpjID0gYQpjIC0gZApjIC0gMQppZiBjIGQKeSArIDEKcHJpbnRJbnQgYQpHT1RPIGkKbGJsZAp6ID0gYQp6ICUgZApkICsgMQppZiB6IEkKbGJsaQphICsgMQpHT1RPIE0KbGJsRQ&input=MTAyMw) [Answer] # Python 3, ~~119~~ 120 bytes [cracked!](https://codegolf.stackexchange.com/a/90677/53748) ``` def p(i): r=[2] d=3 while i>1: if all(d%e for e in r): r+=[d] i-=1 d+=1 print('\n'.join(str(e)for e in r)) ``` For all those struggling robbers... ``` % * 1 ' * 2 ( * 5 ) * 5 + * 2 - * 1 . * 1 1 * 3 2 * 1 3 * 1 : * 3 = * 5 > * 1 [ * 2 \ * 1 ] * 2 a * 1 d * 5 e * 6 f * 4 h * 1 i * 9 j * 1 l * 3 n * 5 o * 3 p * 2 r * 8 s * 1 t * 2 w * 1 <newline> * 8 <space> * 24 ``` [Answer] # C#, 27591 bytes [**cracked!**](https://codegolf.stackexchange.com/a/91135/53748) ``` static void Main(){int n=int.Parse(System.Console.ReadLine()),v=30*" ...between the quotes is a total of 27387 '[' characters... ".Length,c=0,p=0,f,j;while(c<n){j=0;j++;f=0;while(j<v){if(p%j==0)f++;j++;}f--;f--;if(f==0)System.Console.WriteLine(p);if(f==0)c++;p++;}} ``` 30 \* 27387 = 821610. The 2^16-1th prime (the specified limit) is 821603, this code checks to see if there are exactly 2 factors in the range [1, 821609] until n primes have been written to the console. Test it on [**ideone**](https://ideone.com/Bq6CBq) Character set: ``` ' ' :3 '"' :2 '%' :1 '(' :9 ')' :9 '*' :1 '+' :10 ',' :5 '-' :4 '.' :6 '0' :8 '3' :1 ';' :11 '<' :2 '=' :12 'C' :2 'L' :3 'M' :1 'P' :1 'R' :1 'S' :2 'W' :1 '[' :27387 'a' :4 'c' :4 'd' :2 'e' :12 'f' :10 'g' :1 'h' :3 'i' :13 'j' :6 'l' :4 'm' :2 'n' :10 'o' :5 'p' :4 'r' :2 's' :6 't' :8 'v' :3 'w' :2 'y' :2 '{' :3 '}' :3 ``` [Answer] # Java, 197 bytes Another crack of one of [Jonathan Allan's answers](https://codegolf.stackexchange.com/a/90703/54142) ``` class y{public static void main(String[]b){int n=2,l=870119,i=new java.util.Scanner(System.in).nextInt(),f,j;while(i>0){f=0;for(j=1;j<l;j++)if(n%j==0)f++;if(f==2){System.out.println(n);i--;}n++;}}} ``` Saves 6 characters (namely `{{}}i;`) by removing extraneous curly brackets around the `for` loop and following `if`, and by moving the assignment to `i` into its declaration. Test on [**ideone**](http://ideone.com/d0BRne). [Answer] # Bash, ~~166~~ 133 bytes ``` a=2 while((l<$1));do if((b[a])) then((c=b[a]));else((c=a,l++));echo $a;fi;((d=a+c)) while((b[d]));do((d+=c));done ((b[d]=c,a++));done ``` (no trailing newline) Pass primes count as `$1` [Answer] # Prolog (SWI), 109 bytes ``` p(N):-q(N,2). q(N,X):-N=0;Y is X+1,(A is X-1,\+ (between(2,A,B),0is X mod B),writeln(X),M is N-1;M=N),q(M,Y). ``` [Online interpreter](http://swish.swi-prolog.org/p/OSwiIzrk.pl) [Answer] # Java (Cracked) ``` class y{public static void main(String[]b){int i=0,n=2,f,j,l;String x="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz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zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";l=x.length();for(;i<791819;i++){l++;}i=new java.util.Scanner(System.in).nextInt();while(i>0){f=0;for(j=1;j<=l;j++){if(n%j==0){f++;}}if(f==2){System.out.println(n);i--;}n++;}}} ``` Add 58 Z's to get this to run properly [Answer] # [Tcl](http://tcl.tk/), 111 bytes ``` set i 2 while \$i<$n {set p 1 set j 2 while \$j<$i {if $i%$j==0 {set p 0 break} incr j} if $p {puts $i} incr i} ``` [Try it online!](https://tio.run/##TYoxDoAgEAR7XrHF2YM1/sRGCcZDQ4hgLIhvRzSaWM1mdpJZS7QJHkrKZzFaccy8WvTEmjzybQOUuOl@r9PEyDyBuCHXdfJLpRg3OyynYG82uMraBOSwp1jj1/NZygU "Tcl – Try It Online") --- # tcl, 116 ``` set i 2 while \$i<$n {set p 1 set j 2 while \$j<$i {if ![expr $i%$j] {set p 0 break} incr j} if $p {puts $i} incr i} ``` [demo](http://www.tutorialspoint.com/execute_tcl_online.php?PID=0Bw_CjBb95KQMNXdVUFVlcWx3UHM) --- # tcl, 195 before it was golfed: ``` for {set i 2} {$i<$n} {incr i} { set p 1 for {set j 2} {$j<$i} {incr j} { if {[expr $i%$j] == 0} { set p 0 break } } if $p {puts $i} } ``` [demo](http://www.tutorialspoint.com/execute_tcl_online.php?PID=0Bw_CjBb95KQMZ242b1BGTUpfVjg) — You can set the value of `n` on the first line [Answer] # [JavaScript (Node.js)](https://nodejs.org), 116 bytes ``` i=>{r=[] d=2 while(i){if(r.map(e=>d%e).filter(x=>x).length==r.length){r.push(d);i--}d+=1} console.log(r.join('\n'))} ``` [Try it online!](https://tio.run/##LcyxDoIwEADQnf8w3GHaBCYTc/yIOjT0So/UlhRUEsK3Vwe3N73JvM0yZJlXFZPl4qgI9Xum26Oy1FUfL4FBcBcHWT/NDEy9PTFqJ2HlDBv1G@rAcVw9Uf4L96zn1@LB4lWUOuyZ2qMaUlxSYB3S@MumJBHqe6wRj@Kga5qLarF8AQ "JavaScript (Node.js) – Try It Online") ## Charset: ``` "1": 1, "2": 1, "i": 7, "=": 8, ">": 3, "{": 3, "r": 6, "[": 1, "]": 1, "\n":4, "d": 4, "w": 1, "h": 4, "l": 6, "e": 7, " ": 7, ")": 7, "f": 2, ".": 7, "m": 1, "a": 1, "p": 2, "%": 1, "t": 3, "x": 2, "n": 4, "g": 3, "u": 1, "s": 2, ";": 1, "-": 2, "}": 3, "+": 1, "c": 1, "o": 4, "j": 1, "'": 2 ``` [Answer] # APL ([NARS2000](http://www.nars2000.org/download/Download.html)), 72 UCS-2 [chars](http://meta.codegolf.stackexchange.com/a/9429/43319) = 144 bytes ``` {⍵(⍵=⍵)⍴((⍵=⍵)=+/[⍵=⍵](⍵|⍵)=((⍵=⍵)+⍳+/⍵⍴⍵)∘.|(⍵=⍵)+⍳+/⍵⍴⍵)/(⍵=⍵)+⍳+/⍵⍴⍵} ``` [TryAPL online!](http://tryapl.org/?a=%7B%u2375%28%u2375%3D%u2375%29%u2374%28%28%u2375%3D%u2375%29%3D+/%5B%u2375%3D%u2375%5D%28%u2375%7C%u2375%29%3D%28%28%u2375%3D%u2375%29+%u2373+/%u2375%u2374%u2375%29%u2218.%7C%28%u2375%3D%u2375%29+%u2373+/%u2375%u2374%u2375%29/%28%u2375%3D%u2375%29+%u2373+/%u2375%u2374%u2375%7D11&run) ]
[Question] [ [Base](https://codegolf.stackexchange.com/questions/224730/base-ically-god): part 1 This is part 2, Strongly suggest you go try out the first one if you haven't tried it. ## Story As one of the solvers, You've managed to get to the door of the base heaven. In front of the door stands the base guard @lyxal, they were angry that you all just left the encoded text on the ground, they demand that you clean (decode) the ground before joining the party, those who are irresponsible get no ticket! ## Task You will get 2 inputs * First being `X` which is a non-negative integer in base of base list. * Second being base which is a list of bases. * bases range from 1 ~ 10 * The base will contain at least one not `1` base * answer should be in the base 10 Example: ``` X, [bases] -> answer 110 ,[2] -> 6 30 ,[2,4] -> 6 2100 ,[2,3] -> 30 0 ,[any bases] -> 0 You may want to look at part 1 for more detail ``` # Rule * No loopholes * Input/Output in any convenient, reasonable format is accepted. Satisfy Lyxal with the shortest code, because a long code indicates that you are lazy and not doing your best! [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 6 bytes [SBCS](https://github.com/abrudz/SBCS) ``` ⍴⍨∘≢⊥⊢ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9S75VHvikcdMx51LnrUtfRR1yIA&f=M1JIUzAEQgMuEwUjINsYyDIGs4xAokCekYIJkGcAAA&i=AwA&r=tryAPL&l=apl-dyalog&m=train&n=f) An anonymous tacit infix function taking the base in reverse as left argument and `X` as a list of digits as right argument. `⊢` X `⊥` evaluated in base… `⍴⍨∘≢` base cyclically reshaped to the length of `X` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes Takes the bases in reverse order as the first argument and the digits as the second argument. ``` ṁżṛḅ@ƒ0 ``` [Try it online!](https://tio.run/##y0rNyan8///hzsajex7unP1wR6vDsUkG/w8v13/UtOb//2iu6GijWB2FaEMdQx2D2FgdIN9EByxiDOMbQ/hGIBUIMTMdS5AolG@qY6JjDDHHCKgcKBYLAA "Jelly – Try It Online") ## Explanation ``` ṁżṛḅ@ƒ0 Main dyadic link ṁ Reshape the list of bases like the list of digits ż Zip with ṛ the list of digits ƒ0 Reduce with initial value 0 under: ḅ Convert from base @ [with swapped arguments] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ṁḊ1;×\ḋ ``` [Try it online!](https://tio.run/##y0rNyan8///hzsaHO7oMrQ9Pj3m4o/v/4eX6j5rW/P8frRBtFKujEG2oowBCsQogjkK0iY4CWNhAR8EYJmaMEDMAqzaCyYDYIIUgSaAYAA "Jelly – Try It Online") -1 byte thanks to Jonathan Allan ``` ṁ Mold bases to the shape/length of the digits, repeating if necessary Ḋ Drop the first base 1; and prepend 1 in its place ×\ Cumulatively reduce the bases by multiplication ḋ Dot product with the digits ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 16 bytes ``` JEs*L*F<t*JlQ~hZ ``` [Test suite](http://pythtemp.herokuapp.com/?code=JEs%2aL%2aF%3Ct%2aJlQ%7EhZ&test_suite=1&test_suite_input=%5B0%2C1%2C1%5D%0A%5B2%5D%0A%5B0%2C3%5D%0A%5B4%2C2%5D%0A%5B0%2C0%2C1%2C2%5D%0A%5B3%2C2%5D%0A%5B0%5D%0A%5B1%2C2%2C3%5D&debug=0&input_size=2) Inspired quite heavily by [hyper-neutrino](https://codegolf.stackexchange.com/users/68942/hyper-neutrino)['s Jelly answer](https://codegolf.stackexchange.com/a/225568/78186). Takes reversed list of digits of X on line 1 and reversed list of bases on line 2 of input. Explanation: ``` JEs*L*F<t*JlQ~hZ | Full program JEs*L*F<t*JlQ~hZQ | with implicit variables ------------------+------------------------------------------------------------------- | Call the first line of input Q (implicit) JE | Call the second line of input J L Q | Map the following over each d in Q: *F | Find the product of < ~hZ | the first Z (starts at 0, increments with each pass) elements of *JlQ | J, repeated the length of Q times t | with the first element removed (product of an empty list is 1) *L | and multiply it with d s | Sum the resulting list | Print (implicit) ``` [Answer] # [Haskell](https://www.haskell.org/), 32 bytes ``` (x:y)?(h:t)=x+h*y?(t++[h]) _?_=0 ``` [Try it online!](https://tio.run/##LY1BDoIwFET3PcVfuAAppoBxARQu4A0IIST/R4hISalaTo8F2c3Lm8x07fykYVhXz6aLX3pdanxpg@68lJ4JgqqrfdaUjRTrq@1HiYpBZS1H5A1Xqs7Dr9I456fiQebej8RgIANWamrxMr01OaXpQ3omsDbDXQBipv5JucFJ96PxbIlSKu62ufIZbHdrFAmo4hrCAm4sEeCAXw@MI7FJnuycCOYo4o6PhvgB "Haskell – Try It Online") The relevant function is `(?)`, which takes as input `X` as a list of digits (least significant first) and the list of bases. # [Haskell](https://www.haskell.org/), 35 bytes ``` (foldr(\(i,d)n->d+i*n)0.).zip.cycle ``` [Try it online!](https://tio.run/##LY1BbsIwEEX3PsUsukjaSeSQqhtITsANAFVRZkKtuh7LCWA4fF1D2f2nN/P/1zB/s7Vp6vapmMRSKPaFQSpd1dObeXWlrsv6Znw9XkfL6WcwriNRsIsRifATRQ6b6iKB5s1Lf@RlaxwrsLxA7AIPVPtT4KwCnznMDDGu6SGAaC3/SXKhD8YtxQSU/zrB3I5SKrgPpqbRsFsdoOrhQ7UaMuD7E1eNvktsH9xqlanBzM8L/TtOdjjOqRq9/wM "Haskell – Try It Online") Same algorithm in point-free style. Takes the list of digits first and then `X`. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `s`, 8 bytes ``` •Ḣ1p⁽*r* ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=%E2%80%A2%E1%B8%A21p%E2%81%BD*r*&inputs=%5B0%2C%200%2C%201%2C%202%5D%0A%5B3%2C%202%5D&header=&footer=) ``` •Ḣ1p⁽*r* Full Program • Mold bases like digits Ḣ Pop first base off 1p Prepend 1 r Cumulative reduce over ⁽* Multiplication * Vectorized multiplication with digits s (flag) Sum ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 9 8 bytes ``` δṁ*G*1t¢ ``` [Try it online!](https://tio.run/##yygtzv7//9yWhzsbtdy1DEsOLfr//3@0sY5R7P9oAx0DHUMgCwA "Husk – Try It Online") Same idea as hyper-neutrino's answer. -1 byte from Leo. [Answer] # [JavaScript (V8)](https://v8.dev/), ~~60~~ ~~55~~ 52 bytes ``` n=>b=>(g=r=>x in n?g(n[x]+r*b[++x%b.length]):r)(x=0) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/z9YuydZOI922yNauQiEzTyHPPl0jL7oiVrtIKylaW7tCNUkvJzUvvSQjVtOqSFOjwtZA839BUWZeiUaaRrShjqGOQaymRrRRrKYmF1zYGCqoY4IibARSDZMyRpGCChqCdfwHAA "JavaScript (V8) – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 90 bytes ``` $ ; +`(\d+,)(.*,)?(\d+)(\d); $2$1$3;$4 +`(.*,)?(\d+,)(\d+);(\d) $2$1$.($2*$3*_$4*); .*,|; ``` [Try it online!](https://tio.run/##PcsxDsIwDAXQ3ecwUpx@VbEdhspDx14CiSLBwMKAGLl7SEBisa3/n5@31/1x0XZI296YgqY9na4TJM0Zso5b@pAgNlb24DrIv4R8SQzzI3Niy@z5zDX3ty7fQa0ZVAsZKnwsh2kptGDk5D0@Qs1IUT4 "Retina – Try It Online") Link includes test cases. Takes `X` as the last argument. Explanation: ``` $ ; ``` Append a marker to keep track of the current digit. ``` +`(\d+,)(.*,)?(\d+)(\d); $2$1$3;$4 ``` Cyclically rotate the list of bases according to the number of digits. ``` +`(.*,)?(\d+,)(\d+);(\d) $2$1$.($2*$3*_$4*); ``` Cyclically rotate the list of bases back again as each digit is converted from the next base. ``` .*,|; ``` Remove the list of bases and the marker. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes ``` IΣE⮌θΠ⊞O…ηκIι ``` [Try it online!](https://tio.run/##JcuxCoMwEIDhVwlOJ6Rg7eiYuTS0ozgc8SBi2qSXRPDpT2n/@fudR3YRg4jl5VPAYC7wqm@4Y4InbcSZ4NtqZTnO1RWwNftHIsYSGczuAhkfE3it1lP99qX9N4iMTX/tukarsdfqNk1y2cIB "Charcoal – Try It Online") Link is to verbose version of code. Takes `X` as a string. Explanation: ``` θ First input (X) ⮌ Reversed E Map over characters ι Current character I Cast to integer ⊞O Push to list η Second input (list of bases) … Cyclically chopped to length κ Current index Π Take the product Σ Take the sum I Cast to string Implicitly print ``` Although it only takes 1 byte to multiply the current character by the product of the list Charcoal's product returns None for an empty list and it would cost 2 bytes to correct this, so it's easier to push the value to the list so that the product is always defined. [Answer] # [JavaScript (V8)](https://v8.dev/), 45 bytes ``` (b,i)=>g=X=>X&&X%10+b[i=b[++i]?i:0]*g(X/10|0) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvtfI0knU9PWLt02wtYuQk0tQtXQQDspOtM2KVpbOzPWPtPKIFYrXSNC39CgxkDzf0FRZl6JRppGtFGspoahoYGmJhdCSMcEKGiMJmYMFDMyNEARBQoB@f8B "JavaScript (V8) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 70 bytes ``` a;i;r;f(x,b,l)int*b;{for(a=1,r=i=0;x;x/=10)r+=x%10*a,a*=b[i++%l];x=r;} ``` [Try it online!](https://tio.run/##bZPbjpswEIbv8xQjJCQMjhZzWGnX6/ai6lMkqOJgttbS7ApHqtWIV286YCA43Ugw8f/NP/KMhnr/WtfXa8kV73kbGFrRjqjTOaz4pX3vg1Iw2gslYm64eRAsJn0kjM/isKRlKKqDiiK/K7gRPR@uHz1ag9FeUsAAHYELYB0YRVAgIOYYXqDjEEWKwORoA8/XfuPRQH31KHjPnkcolAdVEA7DbrT@KtUpILvLDvA3Cmepz/GhwIqXZOCrxGaJZhsxWcR0I6ZWfKJbe2bFlGY038i5Iy93CCemLZvuQ@0dbEhsSG3IbNjYp/OPztq1@iPf22CqQh7mU2iPFDaUuZS5NHFp4tLUpalLM5dmLs1dmpP7RoxthDGcQopPwmJ8MxwGS3AU8SZfmg9Zn2VjHY8UHq1ltCbxLbf@WfYhvmX9JntMhjHdO5rvydE8fcMnH7dlc0692XlbuVMjzbx209@XpanlEre@VmXazTEbt3cqt1x8rDQ3O/GCb3FYzVh/RqFbzN2nWCNePkCXSCTryO6t6wfUUDjgOAy5Y0FFoSP/GwrYfwG/AV8fT@jTdB20FEIXs2PYDde/dduVr/q6//0P "C (gcc) – Try It Online") Inputs a non-negative integer in base 10, a pointer to the array of bases, and the array's length (since C pointers don't carry any length info). ]
[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/3397/edit). Closed 5 years ago. [Improve this question](/posts/3397/edit) Write a program which prompts a user to input two integers A and B, the program should determine whether A is greater than or lesser than B without the use of greater than [>] or less than [<] operators (and similar operators or methods like .compare) and should output : ``` Integer A is greater than B. Rules : No Brainfuck. ``` Should work for negative numbers. Signed int. Code's for equality isn't necessary. Edited Again. [Answer] ## Javascript Here's the basic format of all the solutions. This case returns `true` if `a>b` and `false` otherwise: ``` function greaterThan(a,b){ c=a;//Copy a while(true){ if(b==a){ return false; } if(b==c){ return true; } a++;//Approaches b if a<b c--;//Approaches b if a>b } } ``` **Warning:** Since we didn't need to support the `A==B` case, the next 3 solutions will lock up for those inputs. Thus, don't fill in equal or empty numbers at the prompts in the test fiddles, unless of course you like pushing red buttons that say "Do **NOT** push!!!" **149 chars** - [Fiddle](http://jsfiddle.net/briguy37/aEDX6/): Conforms EXACTLY to specs ;) `for(A=B='A',C='B',a=c=prompt(A),b=prompt(C);b!=c++||(B=C),b!=a--||(A=C),A==B;);alert("Integer "+B+" is Greater than "+A+".\n\n\nRules : No Brainfuck.")` **74 chars** - [Fiddle](http://jsfiddle.net/briguy37/DxpwK/): Prompts user for 2 numbers, alerts '-1' if 1st<2nd, '1' if 2nd>1st: ``` for(A=0,a=c=prompt(),b=prompt();b!=c++||(A=-1),b!=a--||(A=1),!A;);alert(A) ``` **54 chars** - [Fiddle](http://jsfiddle.net/briguy37/SK3X2/): Function that takes 2 parameters and returns `true` if `A > B`, `false` if `A < B`, and, of course, locks up if `A==B`. ``` function a(a,b){for(c=a;b!=++a&&b!=--c;);return b!=a;} ``` [Answer] # Python ``` from sys import argv as s a,b=int(s[1]), int(s[2]) if a==b: print 'They are the same!' else: print 'Integer A is greater than B.' if (abs(a-b)==a-b) else 'Integer B is greater than A.' ``` # Python - 73 characters if inputs as arguments is acceptable as 'input', it is only 73 characters: ``` def c(a,b): if a==b: return 'They are the same!' else: return 'Integer A is greater than B.' if (abs(a-b)==a-b) else 'Integer B is greater than A.' ``` if the weak inequality is all we care about, and we don't have to take input, it's shorter (33 characters): ``` print a if (abs(a-b)==a-b) else b ``` [Answer] ## C ``` #include<stdio.h> int main(int argc, char** argv) { int a, b; long long c; double d; printf("A: "); scanf("%d", &a); printf("B: "); scanf("%d", &b); c = (long long)a - (long long)b; if (c == 0) { puts("Integer A is equal to B."); } else { d = *(double*)&c; if (d == d) { puts("Integer A is greater than B."); } else { puts("Integer B is greater than A."); } } return 0; } ``` It was golfed but then I realized this wasn't a golf. So now it's not. ;) To understand how this works, you have to understand how numbers are integers and floats are represented, bitwise, and how the CPU operates on them. I'm starting out by getting two 32-bit signed integers. They are stored as ints to bound the input. I then cast them to long longs, basically converting them to 64-bit integers, and then subtract. This subtraction is important. If A is larger than B, the result will be positive. If they're equal, the result is 0, and if B is larger than A, the result is negative. The negative case is the key, here, because of how it's represented as an integer in memory. A negative integer is stored as a 2's complement, and since these are 64-bit integers, we'll have at least one DWord of 1s in the MSBs in memory. I then store that into a 64-bit double variable, turning it into a double value with the same bit encoding. If it is negative, this double value is a NaN. By IEEE floating point rules, comparing a NaN with itself will always result in `false`, which indicates that A < B. And of course, a simple zero check can add an equivalence check to the algorithm. **EDIT:** This now works for very large and very small ints. It requires a 64-bit compiler, where `long long` is defined as having a size of 8 bytes. Unfortunately, gcc in Cygwin didn't do the trick, so I had to use Visual Studio. But, it works. This, I found, does not work for very large and very small 32-bit integers. I will be investigating a solution. [Answer] ## Python ``` r="less" try:(input()-input())**.5;r="greater" except:pass print "Integer A is",r,"than B" ``` [Answer] Since most of the questions about the spec have been answered, here's a solution in C#. If the size of the ints isn't 32-bit then `int` needs changing for a suitable type. ``` namespace Sandbox { class Program { private static int _Compare(int a, int b) { if (a == b) return 0; int sgnA = (a & int.MinValue) == int.MinValue ? -1 : 1; int sgnB = (b & int.MinValue) == int.MinValue ? -1 : 1; // If they have different signs then the negative one is smaller. if (sgnA != sgnB) return sgnA; // If they're both non-negative then the difference won't overflow. // If they're both negative, then the different won't overflow. Worst case is (-1) - int.MinValue = int.MaxValue return ((a - b) & int.MinValue) == int.MinValue ? -1 : 1; } public static void Main(string[] args) { if (args.Length == 0) { // Test mode. int[] cases = new int[] { int.MinValue, int.MinValue + 1, int.MinValue + 2, int.MinValue / 2 - 2, int.MinValue / 2 - 1, int.MinValue / 2, int.MinValue / 2 + 1, int.MinValue / 2 + 2, -2, -1, 0, 1, 2, int.MaxValue / 2 - 2, int.MaxValue / 2 - 1, int.MaxValue / 2, int.MaxValue / 2 + 1, int.MaxValue / 2 + 2, int.MaxValue - 2, int.MaxValue - 1, int.MaxValue, }; foreach (int _a in cases) { foreach (int _b in cases) { int _cmp = _Compare(_a, _b); Console.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}", _a, _b, _cmp, _cmp == _a.CompareTo(_b) ? "OK" : "Error")); } } } eise if (args.Length != 2) { Console.Error.WriteLine("Expected two arguments."); } else { int a, b; if (!int.TryParse(args[0], out a) || !int.TryParse(args[1], out b)) { Console.Error.WriteLine("Both arguments must be integers"); return; } int cmp = _Compare(a, b); Console.WriteLine(cmp == -1 ? "Integer A is less than B" : cmp == 0 ? "Integer A equals B" : "Integer A is greater than B"); } } } } ``` All of the test cases pass. [Answer] ## Scala Based on the revised question: ``` object G extends App { def g(i:BigInt,j:BigInt)= { def q(a:BigInt,b:BigInt):String= { if(a==0) "Integer B is greater than A." else if(b==0) "Integer A is greater than B." else q(a+1,b-1) } if(i!=j)q(i-j,i-j)else"A and B are equal" } val(a,b)=(readLine("A: ").toInt,readLine("B: ").toInt) println(g(a,b)) } ``` [Answer] ## Javascript: (108 chars without spaces) ``` function C(a,b) { var d=a-b, z=!!(d/Math.abs(d)+ 1), m=z?a:b, n=z?b:a; return 'Integer '+m+' is greater than '+n; } ``` tests: ``` console.log( C (1, 3) ); // Integer 3 is greater than 1 console.log( C (3, 2) ); // Integer 3 is greater than 2 console.log( C (-3, -8) ); // Integer -3 is greater than -8 console.log( C (-9, 0) ); // Integer 0 is greater than -9 ``` Code for equality is not required, so I didn't do it. [Answer] ## Scala: ``` object G extends Application { def g (a: Byte, b: Byte) = (a & -128, b & -128) match { case (0, 0) => if (((a - b) & -128) != 0) "<" else ">" case (x, 0) => "<" case (0, x) => ">" case _ => if (((b-a) & -128) != 0) ">" else "<" } val r = g (readByte, readByte) println ("A is " + (if (r==">") "greater than" else "less than") + " B") } ``` Since `ints` vary from language to language, I choosed Bytes here, because it allowed me to do exhaustive testing. Of course it can easily be adapted to short/int/long, with Int.MIN\_VALUE etc. instead of -128. The 4 cases test for * both values are positive * only first * only second * none of them It took me 60 minutes to golf it down to 297 chars, until I noticed, that it isn't a golf! And another 10 minutes for hitting 80x `undo` (real programmers don't do backups). [Answer] ## Ada, 76 Characters ``` function C(A,B:Integer)return Integer is begin return (A-B)/abs(A-B);end C; ``` returns -1 for A smaller than B, and 1 for A bigger than B. for A=B an exception will be raised, but the behaviour in this case isn't specified in the task description. [Answer] ## D (51 chars) ``` int d(int a,int b){return a-b?(a-b)&-1<<31?-1:1:0;} ``` using signed representation returns `-1`,`0`,`1` for `less than`, `equals to` and `greater than` resp. with reading from user: **91 chars** ``` import std.stdio;void main(){int a,b;readf("%d %d",&a,&b);writeln(a-b?(a-b)&-1<<31?-1:1:0);} ``` [Answer] ## PHP PHP's too verbose for a task this simple, but I'm in PHP mode so I'll go ahead: ``` function d($a,$b){return $a-$b;} // Returns a negative number if $a < $b, positive if $a > $b, 0 if $a == $b ``` If you need it to always return the same values, then ``` function d($a,$b){return ($d=$a-$b)?$d/abs($d):0;} // Returns -1 if $a < $b, 1 if $a > $b, 0 if $a == $b ``` If you want it to output text, you could do something like: ``` function d($a,$b){$d=$a-$b;echo !$d?'equal':(abs($d)==$d)?'greater than':'less than';} ``` [Answer] ## Objective-C - 161 chars + full string This solution prompts the user, gets the value, and then returns the full string. Usage - self-explanitory, it requests a with 'a?' and then once inputted, requests b with 'b?'. ``` int a,b,x;char c='A';NSLog(@"a?");scanf("%i",&a);NSLog(@"b?");scanf("%i",&b); x=(a-b/abs(a-b)==1);NSLog(@"Integer %c is greater than integer %c.",c+!x,c+x); ``` And readable version (with whitespace) ``` int a,b,x; char c = 'A'; NSLog(@"a?"); scanf("%i", &a); NSLog(@"b?"); scanf("%i", &b); x = (a-b/abs(a-b) == 1); NSLog(@"Integer %c is greater than integer %c.", c+!x, c+x); ``` Output: ``` Computer: a? Me: 2 Computer: b? Me: 3 Computer: Integer B is greater than integer A. ``` [Answer] ## C ``` void AgB(int a, int b) { (( 2 * a + 1) / (2 * b + 1) == 0) ? printf("Integer B is greater than A\n") : printf("Integer A is greater than B\n");} ``` [Answer] ## Python alt-way ``` #!/usr/bin/python import sys a, b = map(int, sys.argv[1:3]) s = '==' if (a == b) else '<' if (str(a-b)[0] == '-') else '>' print 'a(%d) %s b(%d)' % (a, s, b) ``` [Answer] If equility is not matter, just doing `sorted([A,B]) != [A,B]` should do, so ``` a=[input(),input()];print"A is "+["less","great"][sorted(a)!=a]+"er than B" ``` Tests ``` >>> a=[input(),input()];print"A is "+["less","great"][sorted(a)!=a]+"er than B" 1 2 A is lesser than B >>> a=[input(),input()];print"A is "+["less","great"][sorted(a)!=a]+"er than B" 2 1 A is greater than B >>> a=[input(),input()];print"A is "+["less","great"][sorted(a)!=a]+"er than B" -1 -2 A is greater than B >>> a=[input(),input()];print"A is "+["less","great"][sorted(a)!=a]+"er than B" -2 -1 A is lesser than B ``` [Answer] ## Python, 152 characters Conforms to the letter with the specification. No cheating with conditionals of any kind, including equality. The `abs` call probably has a conditional hidden, if I weren't golfing I would do `x/=int(math.sqrt(x*x))` as the third line. ``` i=input x=i("A")-i("B") x/=abs(x) print "Integer",chr((131-x)/2),"is greater than",chr((131+x)/2)+".\n\n\n\nRules : No Brainfuck." ``` [Answer] ## BF, handles negative zero I figured it would be fun to invent a language for the job, using characters `<` and `>` for something completely unrelated to inequality comparison. ``` # parse first number (space delimited) +>,--------------------------------------------- [<->[->+<]]<[->+>,---------------------------------------------<<]> >+++++++++++++[ <<[->>>+<<<]>>---------------- [-<<+>>]>[-<<<++++++++++>>>]< ,--------------------------------] # parse second number (newline delimited) +>,--------------------------------------------- [<->[->+<]]<[->+>,---------------------------------------------<<]> >+++++++++++++++++++++++++++++++++++[ <<[->>>+<<<]>>-------------------------------------- [-<<+>>]>[-<<<++++++++++>>>]< ,----------] # handle minus signs <[<<[-<[->+<]>>[-<<+>>]<[->+<]>>-<<]>>[-<[-]<<+>>>]] <<[-<[-]>>+<] # compare <+>>+[-<<-[>]>] # report >[[-]++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++.<] <<<[[-]+++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++.>] ``` For a brief summary of operators: `<` and `>` move the cursor backward/forward; `+`/`-` increment/decrement the value of the number pointed to by the cursor (hereafter referred to as "the accumulator"); `[]` iterate while the accumulator is non-null; `,` reads a byte from input to the accumulator; `.` writes the accumulator to the output. Anything else is ignored, which provides a cool way to implement comments, that can even be made to look like comments in other scripting languages. Handles negative numbers by checking for the following cases: * if both numbers are signed negative, swap them * if only one number is negative, zero it out and increment the other one * else just leave them alone This lets us compare zero with negative zero (`-0 < 0`). Equality is not handled. Funny how I/O takes more than twice the space the math does. [Answer] # Python, 86 ``` a,b=input('A,B') print 'Integer A is %s than B.'%('less'if abs(a-b)-a+b else'greater') ``` [Answer] ## Haskell, 150 characters ``` main=putStr.g.f.map read.words=<<getLine f[a,b]|b`elem`dropWhile(/=a)[(minBound::Int)..]="BA"|0<1="AB" g[x,y]="Integer "++x:" is greater than "++y:"." ``` I could use `Integer` and do subtraction, but I felt like dealing with overflow problems that arise from using `Int`. Note there is a `<` in the code, but it is used to compare a constant expression (one character less than writing `True`). [Answer] ## FORTRAN 77 I guess good old Fortran arithmetic if does not violate the requirements of the question. Here it is ``` PROGRAM TEST READ *, A READ *, B IF (B-A) 99,100,101 99 PRINT *, 'Integer A is greater than B' GOTO 102 100 PRINT *, 'they are equal' GOTO 102 101 PRINT *, 'Integer B is greater than A' 102 STOP END ``` [Answer] C# approach with 44 chars. I just subtract a from b and check if there is a minues in the result string: ``` bool c(int a, int b){return ("" + (b - a))[0] == 0x2d;} ``` [Answer] ## Haskell - 18 characters ``` main=print.compare ``` Returns GT if a > b, LT if a < b. Or since this question's output is completely unspecified, I can do ``` main=print.(-) ``` which returns a negative number if a < b, or a positive number if a > b. EDIT: I didn't see what the exact output has to be (see below) ``` main = print.f f x y|q==GT=g b|q==LT=g c where q=compare x y a="Integer A is " b="greater than" c="less than" e=" B." g x=a++x++e ``` BTW, this golf sucks. [Answer] # *C (K&R) - 49 chars* This is indeed trivial... ``` a,b;main(){scanf("%d%d",&a,&b);printf("%d",a-b);} ``` negative result if a > b, positive if a < b, 0 if equal **EDIT:** This answer corresponds to the very first specs of the question, when golfing was required and the output was not restricted to specific phrases. [Answer] ## Perl ``` for(0..9){ $s.=("2"x$_)."1".("0"x(9-$_)) } for(0..9){ $a=$_; for(0..9){ $c[$a][$_]=chop$s } } $_=<>; $b=<>; $l=length; $_="0"x length$b.$_; $b="0"x$t.$b; for(1..$l){ $e.=chop;$f.=chop$b } $g="Integer A is"; $h=" than Integer B"; for(1..$l){ $t=$c[$_][$b]; if($t==2){die"$g less$h"} if($t==0){die"$g greater$h"} } ``` This creates a look-up array for all of the comparisons of each digit. It then takes two unsigned integers as input. It makes them the same length. It then compares them one digit at a time using the look-up array. I am sure it could be made a lot shorter. [Answer] ## JavaScript (65) Enter in Mozilla Firefox's Web Console: ``` 'Integer A is '+(eval(prompt())>>>31?'less':'greater')+' than B.' ``` The user should separate the two signed integers (which should each fit in 31 bits) with " - ". The program takes the difference and checks the sign bit. ]
[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/20379/edit). Closed 3 years ago. [Improve this question](/posts/20379/edit) # Goal Use any graphics library or environment that can use colours and animation to create a rainbow. # Rules * The rings should emerge one by one in some kind of animation or succession * The rainbow must have at least 7 colours. # Winning Criteria Fewest bytes wins. [Answer] # HTML + CSS + JavaScript (~~447~~ ~~440~~ ~~439~~ ~~432~~ ~~428~~ ~~434~~ ~~390~~ ~~388~~ 383 bytes) (Byte size went up at one point in order to fulfill “appear one by one” requirement) (Some credit to [Fez Vrasta](https://codegolf.stackexchange.com/a/20463/668)’s answer for reminding me of the existence of `document.write`) ``` <script>for(d=document,i=0;k=i>>1,k<7;setTimeout(function(w){d.getElementById(w).id="x"+w},555*k,i++))d.write("<b id="+i+"><style>b{width:0;height:0;transition:width 2s,height 2s;border-radius:50ex 50ex 0 0;position:fixed;bottom:-4ex}#x"+i+"{left:"+(9+4*k)+"ex;width:"+(80-6*k)+"ex;height:"+(40-3*k)+"ex;box-shadow:"+(i%2&&"inset 0")+" 0 6ex hsl("+50*k+",99%,50%)}</style>")</script> ``` ## Screenshot (see [JSFiddle](http://jsfiddle.net/EJzzj/2/) for the full animation) ![rainbow picture](https://i.stack.imgur.com/AXJE7.png) ## Explanation The rainbow is created by having 7 pairs of `<b>` elements, which are all positioned using `position:absolute` and a `width`, `height`, `left` and `bottom`. Within each pair, they have the same position and size, but one has an “outer” (standard) `box-shadow`, the other an `inset` one, thus creating the nice fuzzy bands. The colors are calculated using `hsl()`, allowing us to vary only the hue but having the same saturation (99%) and lightness (50%) for all. The `<b>` tags are nested inside each other, but this doesn’t matter because all of their positioning is relative to the page. In the beginning, they all have IDs `0`, `1`, etc., and a styling rule that applies to *all* `b` elements sets their width and height to `0`, making them invisible. The code also outputs styling rules for elements with ID `x0`, `x1`, etc., which initially do not apply. A `setTimeout` is then used to successively change their IDs from `0` to `x0`, from `1` to `x1` and so on. This triggers a CSS transition which causes them to appear one by one. ``` <script> for (d = document, i = 0; // i loops from 0 to 14 k = i >> 1, k < 7; // k loops from 0 to 7 setTimeout( function(w) { // Code to change the element IDs, triggering the CSS transition d.getElementById(w).id = "x" + w }, 555 * k, // 555 milliseconds delay between the appearance of each band i++ // This argument is passed into the timeout function ) ) // For-loop body; creates a <b> element and a <style> element d.write( // The <b> element (with its initial ID) "<b id=" + i + ">" + "<style>" + // CSS rules that apply to all elements (esp. transition!) "b{width:0;height:0;transition:width 2s,height 2s;" + "border-radius:50ex 50ex 0 0;position:fixed;bottom:-4ex}" + // CSS rules for this specific element "#x" + i + "{" + "left:" + (9+4*k) + "ex;" + "width:" + (80-6*k) + "ex;" + "height:" + (40-3*k) + "ex;" + // “i%2” is either 0 or 1; therefore, // “i%2 && "inset 0"” is either 0 or "inset 0" "box-shadow:" + (i%2 && "inset 0") + " 0 6ex " + // 99% is shorter than 100% ;-) "hsl(" + 50*k + ",99%,50%)" + "}" + "</style>" ) </script> ``` [Answer] # Bash + ImageMagick, 226 bytes ``` r=400 s="" for c in 008 40c 03f 07f 0c0 ee0 f80 c00 do s="-stroke '#$c' -draw 'circle 250,280 $r,$r' $s" eval "convert -size 500x220 xc:'#008' -fill none -strokewidth 10 $s r$r.png" r=$[r+7] done convert -delay 50 r*.png r.gif ``` Produces the following GIF animation: ![an animated rainbow](https://i.stack.imgur.com/UTRY3.gif) [Answer] # BBC BASIC, ~~101~~ 106 Bytes ``` FORC=1TO7GCOLC:A=GET:R=700-C*50FORX=-R TO R:LINE640+X,SQR(R^2-X^2)-200,640+X,SQR((R+50)^2-X^2)-200NEXTNEXT ``` EDIT: added A=GET: so that user must press a key to make each ring appear, to comply with animation requirement. Deleted one unnecessary white space after LINE. The original code can still be seen on the screenshot. Runs at the command line in Mode 6. Emulator at www.bbcbasic.co.uk ![program screenshot](https://i.stack.imgur.com/kCPKN.png) I posted this to show how concise BBC basic was. No complicated libraries to include, all you had to do was type MODE6 and away you went. Also to demonstrate the drawing of a circle using pythagoras theorem. Ungolfed version: ``` FOR C=1 TO 7 A=GET :REM wait for user to press a key GCOL C :REM change graphics colour to C R=700-C*50 :REM select the inner radius FOR X = -R TO R :REM scan through X values LINE 640+X,SQR(R^2-X^2)-200, 640+X,SQR((R+50)^2-X^2)-200 NEXT NEXT ``` The centre of the circle is at 640,-200. For the inner circle, the Y coordinate (before subtracting 200) is the square root of R^2-X^2, so we are using Pythagoras theorem. It was specified that the rings be drawn "one by one" so for each X value the program draws a line directly upwards from the inner radius of the current colour to the outer radius. The Y coordinate for finishing the line is the square root of (R+50)^2-X^2 so the radius is 50 more. Unfortunately the algorithm cannot reach the last bit of the left and right sides of the outer circle, because if we try to go there, the calculation for the inner circle gives a negative square root and the program crashes. The easiest workaround was simply to put the centre of the circle off the bottom of the screen. You can still see a little bit of the uncoloured area at the sides, though. [Answer] # Python 2 with Pygame ## First version - 210 198 bytes ``` import pygame as p s=p.display.set_mode((720,360)) c=p.Color(0,0,0) for i in range(360,0,-1): c.hsla=(i,100,50,100) p.draw.circle(s,c,(360,360),i) __import__('time').sleep(0.1) p.display.flip() ``` This creates a window showing the drawing of a rainbow from the circumference to the center. It takes 36 seconds to complete the rainbow. ![enter image description here](https://i.stack.imgur.com/3SP6C.png) ## Alternative version - 235 ``` import pygame as p s=p.display.set_mode((720,360)) c=p.Color(0,0,0) for j in range(360,-45,-45): for i in range(j,0,-1): c.hsla=(j-i,100,50,100) p.draw.circle(s,c,(360,360),j-i) __import__('time').sleep(0.01) p.display.flip() ``` This alternative version draws some rings with a cooler animation. ![enter image description here](https://i.stack.imgur.com/tzbqp.png) [Answer] # Mathematica, 177 I doubt this is the shortest *Mathematica* way to do it. ``` ListAnimate@Table[Graphics[{Thickness[0.1], Table[{ColorData["Rainbow"]@i, Circle[{0, 0}, 7 i]}, {i, 0, m, 1/7}]}, PlotRange -> {{-8, 8}, {0, 8}}], {m, 0, 1, 1/7}] ``` ![rainbow](https://i.stack.imgur.com/5JDbS.gif) [Answer] # GLSL - 234 ~~200~~ (heroku flavor) At the cost of 34 characters, added animation ``` precision lowp float;uniform vec2 resolution;uniform float time;void main(){float f=distance(gl_FragCoord.xy/resolution,vec2(.5,0))*9.;gl_FragColor=f>2.4&&f<8.?vec4(sin(f+time)+.5,sin(f+2.+time)+.5,sin(f+4.+time)+.5,1):vec4(0,0,0,0);} ``` <http://glsl.heroku.com/e#14103.1> ## non-animated answer: ``` precision lowp float;uniform vec2 resolution;void main(){float f=distance(gl_FragCoord.xy/resolution,vec2(.5,0))*9.;gl_FragColor=f>2.4&&f<8.?vec4(sin(f)+.5,sin(f+2.)+.5,sin(f+4.)+.5,1):vec4(0,0,0,0);} ``` <http://glsl.heroku.com/e#14103.0> [Answer] ## JavaScript: ~~304~~ 239 ``` i=-1,s=85,t=20;(function r(){if(++i<7){document.write('<b style=position:absolute;width:80px;text-align:center;font-size:'+s+'px;top:'+t+'px;color:'+['f00','f90','cf0','3f0','0ff','06f','c0f'][i]+'>∩</b>');setTimeout(r,999);s-=5;t+=5}})() ``` ## JavaScript 232 **(thanks @Florent for the split idea)** ``` i=7,s=85,t=20;(function r(){if(--i){document.write('<b style=position:absolute;width:80px;text-align:center;font-size:'+s+'px;top:'+t+'px;color:'+'f007f907cf073f070ff706f7c0f'.split(7)[i-1]+'>∩</b>');setTimeout(r,999);s-=5;t+=5}})() ``` yea I know my rainbow sucks **>\_<"** ![rainbowsucks](https://i.stack.imgur.com/nfKln.png) to test it just run this code in the JS console (F12) [Answer] # Powershell: 270b (arbitrary width/height) / 307b (screen dimensions) For a rainbow spanning most of the screen, the following leaks like a sieve, but seems to work (for 307 bytes): ``` $d=@{};Add-Type -A System.Drawing -Pas|foreach{$d[$_.Name]=$_};$g=$d.Graphics::FromHwnd(0);$v=$g.VisibleClipBounds;$y=$h=$v.Height;$h/=9;$c=0;@(65281,11861886,16776961,16744448,256,23296,65536)|foreach{$g.DrawArc((New-Object $d["Pen"]($d.Color::FromArgb(-$_),$h)),-$h,$y-$h*$c++-$h,$v.Width+2*$h,$h,0,-180)} ``` ## Ungolfed ``` $d=@{}; Add-Type -A System.Drawing -Pas | foreach { $d[$_.Name]=$_ }; # import .NET naespace "System.Drawing" and copy its members into the $d array $g = $d.Graphics::FromHwnd(0); # build a Graphics object for the screen $v = $g.VisibleClipBounds; # determine the screen size $y = $h = $v.Height; # init start point for arcs and band height $h /= 9; # allow space for 7 bands + clear above and below $c=0 # counter @(65281,11861886,16776961,16744448,256,23296,65536) | foreach { # ARGB color values for bands (no clever calculation here, just Color.Red.ToARGB(), Color.Orange.ToARGB(), etc...) $g.DrawArc( (New-Object $d["Pen"]( $d.Color::FromArgb(-$_), # build a pen from the current color, using width = band-height $h )), -$h, # x-pos for start of arc (pushed slightly offscreen to avoid weird wide-pen effect) $y-$h*$c++-$h, # y-pos for start of arc (moves up each time because of counter increment) $v.Width+2*$h, # width of arc (pushed offscreen to avoid weird wide-pen effect) $h, # height of arc always the same 0,-180 # arc sweep clockwise between 0 and 180 degrees from x-axis) ) } ``` Of course, if you don't factor the screen size or the wide-pen effect, and just go with any arbitary width/height, you can lose the `VisibleClipBounds` stuff for approx 270 bytes, but your "animation" speed will be affected by the number of pixels it has to draw: ``` $d=@{};Add-Type -A System.Drawing -Pas|foreach{$d[$_.Name]=$_};$g=$d.Graphics::FromHwnd(0);$y=$h=300;$h/=9;$c=0;@(65281,11861886,16776961,16744448,256,23296,65536)|foreach{$g.DrawArc((New-Object $d["Pen"]($d.Color::FromArgb(-$_),$h)),0,$y-$h*$c++-$h,400+2*$h,$h,0,-180)} ``` ## Results Window-redraw makes it particularly difficult to get a screencap of the full-screen one in action, but the arbitrary-sized one (with the wide-pen awkwardness) looks like: ![Screencap of results](https://i.stack.imgur.com/cpLUK.png) Edit: OK, I've managed to get a fullscreen cap, but not before some of my screen redrew: ![Screencap of results](https://i.stack.imgur.com/EQF3V.png) [Answer] **Disclaimer:** The following solutions work only in Chrome Dev Tools! **Note:** The following solutions will draw a rainbow with an infinite radius, thus arcs are not curved! --- # JavaScript (ES6), 121 ``` i=0;'f43f82fd03c407d72eb2c'.replace(/.../g,p=>setTimeout("console.log('%c'+' '.repeat(99),'background:#"+p+"')",1e3*i++)) ``` Thanks to **@manatwork** for this one! # JavaScript, 126 ``` for(c='f43f82fd03c407d72eb2c',i=7;i--;)setTimeout("console.log('%c'+' '.repeat(99),'background:#'+c.substr("+i+"*3,3))",1e3*i) ``` Details: ``` for( // Colors: // - #f43 (red) // - #f82 (orange) // - #fd0 (yellow) // - #3c4 (green) // - #07d (blue) // - #72e (indigo) // - #b2c (purple) c='f43f82fd03c407db1c', // Iterate through each color i=6; i--; ) // Delay the arc emergence setTimeout( // Display a colored line into the console "console.log('%c'+' '.repeat(99),'background:#'+c.substr("+i+"*3,3))", // 1 second 1e3*i ) ``` Rainbow: ![rainbow](https://i.stack.imgur.com/v9qD9.png) ]
[Question] [ In speedcubing, an Ao5 (Average of 5) is computed for a set of five times by removing the fastest and slowest times, and then computing the mean of the remaining three times. A "rolling ao5" is computed for a sequence of at least five times by computing the ao5 for every set of consecutive five times (some sets will overlap). The best rolling ao5 is the lowest time out of all of these. Related very old and much more involved question: [Calculate the average and standard deviation, rubiks cube style](https://codegolf.stackexchange.com/questions/65806/calculate-the-average-and-standard-deviation-rubiks-cube-style) ## Input An array of between 5 and 100 times inclusive, where each time is a number with exactly two decimal places, between 0.01 and 60.00. The array may be given as input in any reasonable format (list, csv string, etc.) ## Output The best rolling Ao5, where the mean must be rounded to the nearest hundredth and outputted with exactly two decimal places (including trailing zeros). ## Test cases Input on first line, output on second line. ``` 7.16 5.04 4.67 6.55 4.99 5.53 ``` ``` 10.00 10.00 10.00 10.00 10.00 7.00 6.00 9.00 ``` ``` 34.87 33.24 33.31 33.63 27.04 29.14 29.74 31.65 27.42 30.13 28.31 32.50 32.61 36.38 28.60 33.85 28.42 36.00 32.41 35.35 29.47 31.02 28.87 35.08 28.77 ``` [Answer] # [Factor](https://factorcode.org/), 72 bytes ``` [ 5 clump [ 3 [1,b] [ < ] kth-objects mean ] map infimum "%.2f"sprintf ] ``` [Try it online!](https://tio.run/##XVC7TsNAEOzzFaNIdLC6t22goEM0NIgqSuFYdnJJ/MA@VyjfbnZNgUQzmp2Zfdw1ZZX6cfn8eHt/fUTTj22ZUuyOOI79PAiJPS712NVXsHVagcayO9bTL59SmeKUYjVhqr/muqvYedpsvpGRDvCkHByFDIG8Z1YUuLGpNSkFrf5j8UclZgqyGSyP8jCeQgHjyCrRcwfrKGfXknGCVgsGC5PJVs7oFQO7moIX3RlYRZoz@Zo35JVgYB7I5qIHJXPydWOhRJGuIDdx0nHSk/Uy2WUyWRnJyCX82hy3ZQeP6jq3A3aw2On7w57ZM/a4pNNDfzjXVeLvq8uOpbYcELsmtnOL7R2ZZjsNY@xSg/2SxvjCnWvNUSmXHw "Factor – Try It Online") ## Explanation: It's a quotation (anonymous function) that takes a sequence of numbers from the data stack as input and leaves a string on the data stack as output. * `5 clump` Split a sequence into groups of 5 with overlapping. This is the 'rolling' part. * `[ ... ] map` Apply a quotation to each element of a sequence, collecting the results into a sequence of the same size. * `3 [1,b] [ < ] kth-objects` Take the second, third, and fourth elements of a sequence (from a sorted standpoint). This is shorter than trying to sort it and then chop off both ends. * `mean` Take the mean. * `infimum` Take the smallest element from a sequence. * `"%.2f"sprintf` Return the result as a string rounded to two decimal places. [Answer] # R, ~~93~~ ~~88~~ ~~86~~ ~~80~~ ~~79~~ 77 bytes Simple reference solution. Uses `trim` feature of `min` as Giuseppe pointed out. ``` x=scan() sprintf("%.2f",min(sapply(5:sum(x|1),function(i)mean(x[i-0:4],.2)))) ``` -2 bytes by Giuseppe by replacing `length(x)` and cleaning up unnecessary character in sprintf. [Try it online!](https://tio.run/##NYtBCsMgEADv@4yUwgpmWYMaEuhLQg8hVBCqlZiAhf7deOmc5jCz1/LI2xpRwEjKgiHWoMmOYMmYZtMEiokZ6u0f5rT7eDjs7jS4TgYfMa8pvb9o5nwGLD8lpDvjdvhPRC/Cq21l8T3P@ilpEI1aLw "R – Try It Online") ## ~~80~~ 78 bytes Similar answer but with a for loop. ``` x=scan() a={} for(i in 5:sum(x|1))a=min(a,mean(x[i-0:4],.2)) sprintf("%.2f",a) ``` [Try it online!](https://tio.run/##NcqxCsIwEADQ/b6itAg5iEdakpQW8iXicEijAXtK2iEgfnvs4vaGl2sJ241FIYzUe3BkLFjyI3hy7tA0QW/IGKjdP3L4fCG@skpNksbNz0Xu@0MVRA5rEsV6XY5YLulsZnvVNCDC9s5J9qjaU0dDbDVjrT8 "R – Try It Online") [Answer] # JavaScript (ES6), 97 bytes ``` f=a=>Math.min(([,x,y,z,q]=[a.pop(),...a.slice(-4)].sort((a,b)=>a-b),x+y+z)/3,q?f(a):z).toFixed(2) ``` [Try it online!](https://tio.run/##XY8/b8IwEMV3PsWJBVuYq@N/SYpCp7K1S0fKYIIDqUISklABVT87tZHaocvT6d3P754/7Kft865sh1ndbN3tVmQ2W7zYYY@HsiZkxc7swq7suM5WFtumJZQhosW@KnNHZoqusW@6gRDLNjRb2NmGsvP0Mr3SB8mOTwWx9PFKcWiW5dltiaC3zh1PZefIpOgnFDtnt8uycm@XOic8gG9DV9Y7QrFvq3Ig4/d6TLFoumeb70kP2QK@RgCVG8BCBv0vBp462Ja8ng4b19G5Z/Km7pvKYdXsSCjizW86v8UYGdDIFSg0MRjU2k9pOooi5Bwi/l/Tv3EkUpQxSB@hQWg0KQiFkoP3EwVSYeK3EoUKKqOgRoKIwzXPRHc1fhuh0cFXAiTHyDPJnReoeVDjZ4MyCb7hISe5X0x5cMIrE1p5UnlSo9QhWcUhmYvAhCb@l8kP "JavaScript (Node.js) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 20 bytes ``` 5YCS6LY)YmX<'%.2f'YD ``` [Try it online!](https://tio.run/##y00syfn/3zTSOdjMJ1IzMjfCRl1VzyhNPdLl//9ocz1DMwVTPQMTBRM9M3MFMz1TUyDL0jIWAA) Or [verify all test cases](https://tio.run/##XY@9DsIwDIR3nsILqlgsx39JJDY6ssFAVVWChQk23r/YHRhYTqfzl7Pzfnxe63216XTx83SY3rfjsEd@DtO4jtd1rlgcDElB0Ss4moXrfdnNpSARFPrX/rMBcUepIFFjwIbegRWFIPKmIIotpoKsqVJSXYBrbgymbOoxLeiWuTIIYQmmbTyjUaqHd5SWuVP2tG1jp0zyleddQWqQhmLZrDWbiZPJS@KnW4PQ8gU). ### Explanation ``` % Implicit input 5YC % Matrix with sliding blocks of length 5 as columns S % Sort each column 6L % Push [2 1j-1]. When used as an index, this is interpreted as "2:end-1" Y) % Index the rows as specified. This removes first and last rows Ym % Mean of each column X< % Mininum '%.2f' % Push this string: format specification, 'sprintf'-style YD % Convert to string with specified format % Implicit display ``` Direct translation to an anonymous function in Octave (with the Image package): ``` @(x)sprintf('%.2f',min(mean(sort(im2col(x,[1 5]))(2:end-1,:)))) ``` [Answer] # [R](https://www.r-project.org/), ~~86~~ 82 bytes ``` function(x,l=sum(x|1))sprintf("%.2f",min(apply(matrix(x,l+1,5),1,mean,.2)[5:l-5])) ``` [Try it online!](https://tio.run/##TY7BasQwDETv/gqzULCpV0i25ThL@yWlh7DUENi4IclCCv331Mqpl0GMnkazHEW/XY/yrPdt/K5md4/39TmZ/ZesXedlrFsxlxfw5eKmsZphnh8/Zhq2ZdwFfiXH1pGbvobqwNsPvj2u/GntUQzdCK0qZr0P1VirfA@h06EDYu0ZUq99hIC6@TnqECG3bQAfRQOJpqB9BxiFoVNT2xIkFj96HRCoMfnkPTCKpjYnCFn8hJKTz489iiNXCfAkYyMZAkty7CQZvTDShAGz@le/9U6qmVFFSJ1KwNymvleELe34Aw "R – Try It Online") R's `mean` function helpfully can be used to calculate a trimmed mean. Outgolfed by [qwr](https://codegolf.stackexchange.com/a/224484/67312). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 83 bytes ``` \. \d+ $* M!&`\b(1+,){4}1+ %(O`1+ ^1+|,|1+$ )M`1{2,3} O#` 1G` +`^..?$ 0$& ..$ .$& ``` [Try it online!](https://tio.run/##XU@7bgMxDNv1F0WdQ1ILguSHzp46ZgryA4fALdKhS4eiW5Jvv0o3dOhCExRNUd8fP59fb@tufxzrQgDLNUJ4gdPTNJb3vUQ83MpDIuz252HPReId7xIDwOE05JYwP@D8PECOA@K4EL0G4DABUQAK07rOJIqVuGAhnVGpVmO9gwgxo/B/7H8UUqc8Y7aIiqmSdkyFMqPprWAu1GyaKRXHLI6aMc2@zTyyodpUSKvrxfoyiXna5k9U2VGNK@XmurLntG1jZ1f8l3orcxZzVsrVk8vsyZzc403syvYL "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \. ``` Multiply the input by 100. ``` \d+ $* ``` Convert to unary. ``` M!&`\b(1+,){4}1+ ``` Extract all overlapping sets of five consecutive values. ``` %(` )` ``` For each set, ... ``` O`1+ ``` ... sort in order, ... ``` ^1+|,|1+$ ``` ... delete the fastest and slowest times, ... ``` M`1{2,3} ``` ... and take the mean, rounding to nearest, converting to decimal. ``` O#` ``` Sort the means. ``` 1G` ``` Take the fastest. ``` +`^..?$ 0$& ..$ .$& ``` Divide it by 100. [Answer] # [Python 2](https://docs.python.org/2/), ~~103~~, ~~89~~, ~~76~~, 73 bytes Saved **14 bytes** thanks to qwr! Saved **7 bytes** thanks to okie's suggestion to use a list comprehension. Saved another **6 bytes** by switching to a `lambda` function. Saved **3 bytes** after removing the extra brackets and comma and fixing the first slice. Thanks to caird, okie, and att! Also removed a pair of extra parentheses. ``` lambda t:"%.2f"%min(sum(sorted(t[i:i+5])[1:4])/3for i in range(len(t)-4)) ``` The program iterates through all the consecutive runs of 5. The runs of 5 are `sorted` and the first and last elements are removed using slicing. The program `sum`s the values remaining in the run and divides by `3` to find the average. Finally, percent formatting is used return the `min` value. [Try it online!](https://tio.run/##HchBCoMwEEDRqwRBmNA21Zh0EehJUhcpxnZAR4njoqdPQzaPz99//N1I5/B85SWs7ykIdk2r9Ny0KxIc5wrHljhOwB4dXuwofe/MKO/DvCWBAkmkQJ8ISyRgeTNS5j0hMQRA2k8GWY7vVdddha4OyhZNbVt9FMc/ "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes ``` ṡ5ṢṖḊƊ€ÆmṂ×ȷ2+.ḞDṙ-2;”.ṙ2 ``` [Try it online!](https://tio.run/##XY8xSkVBDEX7v4r0Ysgkk7wZbF2D4AJs5LsAO/mFwl@AYqGgtZUIvsHygbiN@RsZk1dY2FwuN2duMpcX2@31GL29aG@vvd33ef@9P@zeltur3nbLw88nH2Gfn097ezzmk8PNE7rj0b8@@vx@ttyt9PkYEyYDRcqQ0SYwVHVX6yYlJIJE/7X@2Q1XlAnEKxRY0SpwRiHwvGSQjMWngpxDJYWaAE@xzZm0qvk0oWnkmUEIkzNl5RmVQs29oZTIjaKnrBsrRRKvLK5yMjupKBrNeYpm4mDiEv9l@QU "Jelly – Try It Online") Note to self: add formatting options to my new golfing language to avoid this ^ clownery [Answer] # [J](http://jsoftware.com/), 30 bytes ``` 0j2":[:<./5(3%~1#.1 2 3{/:~)\] ``` [Try it online!](https://tio.run/##VZDNSkNBDIX3PsWhItdCm2Ymk8wPuhJcuXKrXYlFuvEBCn31a3K5Ci7mcDj5ksnMed7QdMLjwIQdGMPPnvD0@vI88zlvxtt4oIPey9013VJChlwO47p9P87bm8@Pr29MSioT9gMnVEoGJS4oZBVGqu56X8nExLyiKbnHkvzT/mfXptxIfptyJ6kQv0aRlawjF69G3gqkUPOqUC6hkkJNkGts5Exa1LyayDTy4u9hSs60hc@kHGrujaRFbhxz2nJj50iiy2JPJ4uTSqIxudSYzDmY2MR/os0/ "J – Try It Online") [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), 140 bytes ``` o<esc>qq15wlh0y15wO<esc>pj0d3w@qqdk@qqt:s/ /\r/g <c-o>:.,.4$sor n :.,.4j d3w$3bhd$:s/ /+/g C<c-r>=(<c-r>")/3 <esc>k0@tq@t:%s/^\n :sor n {0C<c-r>=printf("%.2f",<c-r>") <esc>o<esc>d} ``` [Try it online!](https://tio.run/##LY5dbsIwEITfcworChJVYbPx2o4T0ShSD9ALoD5ASilUhPwIVFU9e7rr8DJrzX4z3ts0tZuPYV91XWbv30f84fEWnOsJG7rXXdecWcZySFW67dPPaLNft1UJKzDJ0PbqEoX3KWI6od2xSQL6zOQro331sgwjfkopCs1nrMeuHsvFkL5vOT63/OIDv/Zfl/GwjBegD/HqkZ2T863N3zTpAihXlENmlbbgCqUNECr2vVFkwPOWQBtRykQdKZ0DGmGyoI63GTgrvtGKEDJmfOA1WBR1/HZAXnyH0uPDjwWKIykHGEjDpAWy0mxyaUYtjFxiAf20vv0D "V (vim) – Try It Online") I was lucky that vim had `printf` for this challenge, I'd finished most of it before I realized the output spec (phew) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 18 bytes ``` 2⍕2⌷⌊⌿3+/↑∧¨5,/⎕÷3 ``` [Try it online!](https://tio.run/##XY8xTgNBDEX7PYV7iOOxx96Z40TaXZoIKCjgAhBFC1KKnCHcICUS3GQusthbUNB8fX2/@fbsHveb4WW3f7jbjM9P4/0wDks7vE0Lt/czt/na5mObv@Rm215P7XD5/tTbbfs4/1wluGXqekwGipQho/VgqOqu1m7qUkIiSPRf6591iCtKD@I1CqxoFTijEHheMkjG4lNBzqGSQk2A@9joTFrVfJrQNPLMIITJmbLyjEqh5t5QSuRG0VPWjZUiiVcWdzmZnVQUjebcRzNxMHGJ/7T8Ag "APL (Dyalog Extended) – Try It Online") Full program. Example with the second testcase: `⎕÷3` input divided by 3: ``` 3.667 3.333 3.333 3.333 3.000 3.333 ``` `5,/` groups of 5 adjacent values: ``` ┌─────────────────────────┬─────────────────────────┐ │3.667 3.333 3.333 3.333 3│3.333 3.333 3.333 3 3.333│ └─────────────────────────┴─────────────────────────┘ ``` `↑∧¨` sort each group and arrange the result in a matrix: ``` 3 3.333 3.333 3.333 3.667 3 3.333 3.333 3.333 3.333 ``` `3+/` in each row, take sums of 3 adjacent values: ``` 9.667 10 10.33 9.667 10 10 ``` `⌊⌿` get the minimum for each column: ``` 9.667 10 10 ``` `2⍕2⌷` select the second value and format with 2 decimal places: ``` 10.00 ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 109 bytes This doesn't work on Tio because their version of Pari/GP is apparently too old to have the vital function strsplit(). But it works as advertised on mine, version 2.13.0 ``` A(s)=s=[eval(x)|x<-strsplit(s," ")];printf("%.2f",vecmin(vector(#s-4,i,vecsum(vecsort(s[i..i+4])[2..4])/3))) ``` [Try it online!](https://tio.run/##XY/LagMxDEX3@QrhUrDpjOqnxqbNot8RsgglCYY8hvE0ZNF/T6UpdNHNlbg6vpLH3VT74/h4fOhm1m292d92J3033/f3vs1TG0911q1ToMz2bZzqZT5o9Yz@oLrb/vNcL5rLfJ30U@tjV8VsX2cx23Xil5uKWF/i1mw8IpfXYIxZyTo1oCNIaCNEpAEIU@KuFGVWPHUOrQVn/2v5a385XzAMEDgsgU9IBXzEYIH9HCFEzDwN6KNocKIUwA@ylxm3KPHUISXxo4dg0TGTF95jsqLEPWHI4pOVnLxsLFYceUVyGpORyYQhSXIcJNl6YeQS/m/mw38A "Pari/GP – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 55 bytes ``` Min@BlockMap[#~TrimmedMean~.2&,#,5,1]~NumberForm~{4,2}& ``` [Try it online!](https://tio.run/##JY4/b8IwFMT3fgpLICb3yf9jFoQ6dAtUKluUwYAlLHASpc5QIfLVQ/wyne7ud36OLt18dClc3PTr07FLoW3@qvVxSN2QKPlu@7k9/XeefO7Ikuas/vjpQ5OqqQzN/uvRXu6l66rVeOpDjP5aeteMIDZ0RTXl9XgY4tn3eTg@FRWvzbQnT6nAFpRICUKhSI5iJCWiADaHYgt8kSIjHIzGTonZMeCZtMtOgGYoJjsD0mJnGL5pNTrcGWALqTKpQWq8oAq8wASS@DMNzL7q6Q0 "Wolfram Language (Mathematica) – Try It Online") Technical note: the TIO link includes `SetOptions[$Output, FormatType -> OutputForm]` in the header. I am not including this in the score, because it's not necessary in an actual Mathematica notebook: those are in `OutputForm` by default. ## Explanation `BlockMap[f,#,5,1]` applies `f` to every block of 5 consecutive numbers. Here, `f` is `#~TrimmedMean~.2&`, which takes the mean after dropping the lowest and highest 20%. We take the minimum of the results, and then `~NumberForm~{4,2}` puts the answer in the required format: at most 4 digits of precision, with 2 digits after the decimal. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes ``` 5l⟑sḢṪṁ;g:∆τ⌊3+Ḟ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI1bOKfkXPhuKLhuarhuYE7ZzriiIbPhOKMijMr4bieIiwiIiwiWzE3LjE2LDE1LjA0LDE0LjY3LDE2LjU1LDE0Ljk5LDE3LjE2XSJd) ## How? ``` 5l # apertures, width 5 ⟑ # map over each: s # - sort Ḣ # - drop head Ṫ # - drop tail ṁ # - average ; # end map g # minimum : # dup ∆τ # log10 ⌊ # floor 3+ # plus 3 Ḟ # format to that many decimals ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` ﹪%.2f∕⌊EE⁻Lθ⁴✂θι⁺⁵ι¹⁻Σι⁺⌊ι⌈ι³ ``` [Try it online!](https://tio.run/##NY7NasMwEIRfRQQKCmwXSSvJMr3mWEMgx5CDcdxE4NjNj0Pf3t1VWoGG5ZvZkbpze@umdliW7S2PD91Mx3mY9OoN3dcK1CY/87HXTR7zZb7opv1@3TzOd/3Zj6fHWV/XoDzf3ZC7Xl9BZVDbgf3AI3O7Znlt7LhDULH/SwU07c/fLAcUsX4sy37vaqQKqEIbwAWMNTiPZIB58kAeE7uEzouSFY0ErkLjJWOLRnYtxiDcOyCDljOp5B0GIxp5jkhJeDTSk8qLtREiWxFNSXpOBqQgzb6SZuMkIz8JaNLhsLw/h18 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array L Length ⁻ Subtract ⁴ Literal 4 E Map over implicit range θ Input array ✂ Sliced ι From current index ⁺⁵ι¹ Take five consecutive values E Map over slices ι Current slice Σ Sum ⁻ Subtract ι Current slice ⌊ Minimum ⁺ Plus ι Current slice ⌈ Maximum ⌊ Take the minimum ∕ Divide by ³ Literal `3` ﹪%.2f Round to two decimal places Implicitly print ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~131~~ ~~128~~ ~~125~~ ~~124~~ ~~154~~ ~~138~~ 120 bytes ``` x=>Math.min(...x[f='slice'](0,-4).map((_,i)=>x[f](i,i+5).sort((a,b)=>a-b)[f](1,4)).map(([a,b,c])=>(a+b+c)/3)).toFixed(2) ``` Too long. Will golf. # Explanation ``` x=> // declare function Math.min(... // smallest of x[f='slice'](0,-4) // slice of last 4 to avoid NaN / undefined, defining f as 'slice' to save bytes .map((_,i)=> // for each, by index (current value doesn't matter for now) x[f](i,i+5) // remember f is slice, so replace each with its chunk of 5 (x is untrimmed, slice doesn't modify original .sort((a,b)=>a-b) // sort numerically [f](1,4) // remove first and last ).map(([a,b,c])=> // for each, taking all 3 elements (a+b+c)/3 // take average ) ) // end of min, so now have smallest ).toFixed(2) // round + add 0s ``` [Try it online!](https://tio.run/##LY7LboMwEEV/JbvYwkz9xizIsrt@AUKVIdC6IjgKqOLvqT10dTQ@93rmx//6dXiF51Yu8T4eU3Psze3Db9/wCAsBgL2dmus6h2G8doSzUlN4@CchnyzQ5pZsRwILhaGwxtdGiGd9evdlT7MSTNP/QpsMG7okiS/6YqBvKqktvod9vBNJjyEua5xHmOMXmUgra1AVu6gKhGEXacDWCRoUT6jB6eQ0uBxRIDVCCYRVKVIB15gUJ2yOCLAGnZZp4iBy0p09CYYjbJ4sKIfOcvzTnUfUHB@xboGfBZ0LBpTBRbrCRVxiEg80wF1H6fEH "JavaScript (Node.js) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 106 bytes ``` printf"%.2f".g g(h:t)|length t<4=99|y<-h:take 4t=min((sum y-maximum y-minimum y)/3)$g t import Text.Printf ``` [Try it online!](https://tio.run/##XY9La8MwEITv@hVLSMGGeCvrZTvYOfXYQ6E99uImsiPiF7ZCE8hvrys5kEMuw8fsaHZ1LKeTbprZtEM/WvjSF4sfo@lsRariex4WXL0gq1ZYkzo4bm14a3RX2yPYXBRZdrvmkXPLkwZhi9Z0QTCdW7hGbXkx7Z1Md6fwlYfrGiyJoud1c1uarjj0BEzung7BqMvDdvtp3bSOdm/9@afRIf7242HK17ta23fTaQJ9Hj14uTaowBRFvzEbB5s@JOCb5wRjBRKpAIEqAYVSOsoyIlFyEsdIKcT0WbMHkruyDHkC3LVJYBJVBkwgp@D8VAAXmLopRya88tir4sASv9hl4kWVm8aopPcFA04xdpl0yTOU1KtyrJCn3lfU96TLxox6x79S/jaXFC4pkUvfLBLfTJnP@Evch1Pim@nfvmrKepqj/TD8Aw "Haskell – Try It Online") The relevant function is `f`, which takes as input the array of times as a list of `Double`s. `f` returns a string representation of the best rolling AoE. Having to import `Text.Printf` for this seems... *wrong*..., but I couldn't find any shorter way. [Answer] # [Red](http://www.red-lang.org), 153 bytes ``` func[b][head insert at tail to""round/to 100 * first sort collect[loop(length? b)- 4[keep average copy/part next sort copy/part b 5 3 b: next b]]1 -2"."] ``` [Try it online!](https://tio.run/##XVC7TsQwEOzzFaNUgITP7yTX8A@0kYs8nLuIKI58PgRfH7wBIYSL0WpmdnbX0Y/7qx9bV0xn7NN9HdretVffjZjXm48JXULq5gUplGUM93U8pQDBOZ4wzfGWcAsxFUNYFj@kdglhe1j8eknXF/SPz9Dtm/cbuncfu4vHELbP09bl3NV/pIJ6/3A9DBT68yGid07gWZasdPsUou@GK@J9RVsgv7ZiwsIwrqGZrWCZMblqGvctC8HykoL/x@a3/DHKhqkKKscZSMNsA6mZ4sh8raE0q7OqmNSEShBaBVnR5OwRB9qsCmYN8VpCcSaypz78khlOaHNtmaqJt5xy6mNiw4mhLku7ZafOTsOUoWRdUTKX5KFN8sW1K1y7xXlNmOhH3P4F "Red – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~58~~ 56 bytes ``` ->a{"%.2f"%a.each_cons(5).map{|b|b.sort[1,3].sum/3}.min} ``` [Try it online!](https://tio.run/##bZDBasMwEETv/QoRCLTgTiWttJYO7Y8YU@xQ0xychDg@lCTf7q7WlPbQ03i1b3YGn@f@axlel@e37rrZwg@bbYePbvf5vjsepsf4hLE7XW/9rcd0PF8aV1GLaR5f6I5xf7gvp/kymaFpajiuTIQNlQngujKMGMt3zm378IM5B2sr4@w/kn@HPw6fQXKNJEDO@QjOIgEkrOyS5FFAKgjBBxVyKkyC1FpJSLcKF8SBo@6Cl8nCFTKtPo9oVbhMDEq6Y6s301oiW31UO2tvMYRiiKCoQaHWIOuV1ILye1LbLt8 "Ruby – Try It Online") ### Explanation It's quite straightforward actually: * get all sets of 5 consecutive elements using `each_cons(5)` * sort them, then get the 3 elements in the middle to discard min and max * calculate average * get minimum average value and format with 2 decimal places [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) +4 bytes for the dumb output format :/ ``` ã5 ®ÍÅÔÅx÷3Ãrm x2 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=4zUgrs3F1MV49zPDcm0geDI&input=WzI5LjM3IDM3LjE1IDI1LjY5IDI0LjMwIDI5Ljg0IDM0Ljg3IDMzLjI0IDMzLjMxIDMzLjYzIDI3LjA0IDI5LjE0IDI5LjY0IDMxLjY1IDI3LjQyIDMwLjEzIDI4LjMxIDMyLjUwIDMyLjYxIDM2LjM4IDI4LjYwIDMzLjg1IDI1LjkwIDI4LjQyIDM2LjAwIDMyLjQxIDM1LjM1IDI5LjQ3IDMxLjAyIDI4Ljg3IDM1LjA4XQ) ``` ã5 ®ÍÅÔÅx÷3Ãrm x2 :Implicit input of array ã5 :Sub-arrays of length 5 ® :Map Í : Sort Å : Slice off first element (the minimum) Ô : Reverse Å : Slice off first element (the maximum) x : Reduce by addition ÷3 : Divide by 3 à :End map r :Reduce by m : Minimum x2 :Force to 2 decimal places ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=sum,min,max -a`, ~~81~~ 67 bytes ``` printf"%.2f",(min map{sum(@b=@F[$_..$_+4])-min(@b)-max@b}0..@F-5)/3 ``` [Try it online!](https://tio.run/##dZBPa8MwDMXv/RQidNCyRJP/yU5HIaeetuNO2ygprBBo0tBkMBj76vOk3Hf52Tw9P8kaP26XkPN464b5XNyhPRflpu8G6Nvxe/rsN81p3xxe10fE9fHev28rKYooZ/vVnH4IsTlUYfvg8uMSUrwNRY5oGAKSB48cgTEEudX1yhASwX@MChasbI0ugpOcADYg12A9OgLRkwfnMUnVofVKZ5TswEZtKR6zkKVqkIPq3oIjNOJJi99iICXLndEl1Zk0Jy0da1JFX@k86vTiDOiCJvuoyWTVo5PIV9PvdZy76zDl6vmpm@bd7mXuLntZYSkbK2VbuWr/AA "Perl 5 – Try It Online") ]
[Question] [ ### The Challenge Your challenge is to write a program that evaluates the following function: f(x, t) = d^x / dt^x (sin t) That is, the x-th derivative of sin t. In case you aren't familiar with calculus, here is a table of derivatives for the sine function: ... f(-1, t) = -cos t f(0, t) = sin t f(1, t) = cos t f(2, t)= -sin t ... The sequence repeats these 4 functions. ### The Inputs Your program should take in an integer to be used as the x value in the function, and a float to be used at the t value in the function. Your program may use radians or degrees for the sine function. ### The Output Your program should output the value of f(x, t) given the integer x and float t. ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins. [Answer] ## Python, 42 bytes ``` from math import* lambda x,n:sin(x+pi/2*n) ``` Uses the fact that differentiating shifts the function by `pi/2` left. [Answer] ## Actually, 5 bytes ``` ╦*½+S ``` [Try it online](http://actually.tryitonline.net/#code=4pWmKsK9K1M&input=MAox) Takes input as `t\nx`. Explanation: ``` ╦*½+S ╦* pi*n ½ half that + add t S sine ``` [Answer] # C (gcc), 30 bytes ``` #define f(x,n)sin(x+n*acos(0)) ``` [Answer] ## Haskell, 16 bytes ``` x%n=sin$x+pi/2*n ``` Defines a binary operator `%`. ``` λ 2.0 % (-3) -0.4161468365471426 ``` Uses the fact that differentiating shifts the function by `pi/2` left. Making it point-free was longer (takes `n x`): ``` (sin.).(+).(pi/2*) ``` [Answer] # Convex (IDE version only), 6 bytes ``` P½*+ms ``` [Try it online!](http://convex.tryitonline.net/#code=aVxpXFDCvSorbXM&input=&args=NA+NQ) After futher investigation, with the help of Dennis in chat, it was found that the command-line version of Convex (what TIO uses) has a bug that breaks the code (the link above contains a workaround). However, the IDE version of Convex, avaliable on GitHub before the challenge was posted, does not have this bug. Here is a link to the IDE version that was avaliable before the challenge was posted: [Convex IDE](https://github.com/GamrCorps/Convex/blob/a1cc4af43bcb9246b4a988615205722b54bc29bc/out/builds/convex-dev/convex_ide/convex-ide.jar). [Answer] # Mathematica 14 bytes With help from Martin Ender, ``` Sin[#2+Pi/2#]& ``` [Answer] # J, 17 bytes ``` 4 :'1&o.d.(4|x)y' ``` Computes the (x%4)th derivative of sine, and then apply to right argument. ## Usage: ``` >> f =: 4 :'1&o.d.(4|x)y' >> _1 0 1 2 3 (f"0 0) 0 << _1 0 1 0 _1 ``` where `>>` is STDIN and `<<` is STDOUT. [Answer] # Julia, 17 bytes ``` x\t=x*π/2+t|>sin ``` [Try it online!](http://julia.tryitonline.net/#code=eFx0PXgqz4AvMit0fD5zaW4KCmZvciAoeCwgdCkgaW4gKCgwLCDPgC82KSwgKDEsIM-ALzYpLCAoMiwgz4AvNiksICgzLCDPgC82KSkKICAgIEBwcmludGYoIiUxMS44ZlxuIiwgeFx0KQplbmQ&input=) [Answer] ## R, 26 bytes ``` function(t,x)sin(t+pi/2*x) ``` Exactly what it says on the tin... [Answer] # C (gcc), ~~53~~ ~~46~~ 45 bytes ``` #import<math.h> #define f(x,n)sin(x+M_PI/2*n) ``` Probably Ideone doesn't have glibc, says `M_PI` is undeclared. [Answer] # JavaScript (ES6), 29 bytes ``` x=>t=>Math.sin(t+Math.PI/2*x) ``` Usage: ``` f=x=>t=>Math.sin(t+Math.PI/2*x) f(x)(t) ``` [Answer] ## Lua 5.x, 37 bytes ``` x,n=...return math.sin(x+math.pi/2*n) ``` usage: ``` > print(loadfile('sine.lua')(1,0)) 0.8414709848079 > print(loadfile('sine.lua')(math.pi,0)) 1.2246467991474e-16 > print(loadfile('sine.lua')(math.pi,1)) -1.0 > print(loadfile('sine.lua')(math.pi,2)) -2.4492935982947e-16 > print(loadfile('sine.lua')(math.pi,3)) 1.0 ``` [Answer] ## Matlab, 19 bytes ``` @(x,t)sin(t+x*pi/2) ``` [Answer] # [SQF](https://community.bistudio.com/wiki/SQF_syntax), 29 bytes Using the file-as-a-function format: ``` params["x","y"];sin(x+pi/2*y) ``` Call as `[x, t] call NAME_OF_COMPILED_FUNCTION` [Answer] # SmileBASIC, 25 bytes ``` INPUT X,N?SIN(X+N*PI()/2) ``` Probably shorter in some BASIC dialect that has a constant named `PI` rather than `PI()`. (Yes, `PI()` is not actually a function, those parentheses are a lie.) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žq*;+Ž ``` Port of [*@Mego♦*'s Actually answer](https://codegolf.stackexchange.com/a/89741/52210). [Try it online](https://tio.run/##yy9OTMpM/f//6L5CLWvtw62H9v7/b8xlAAA) or [verify some more test cases](https://tio.run/##ASkA1v9vc2FiaWX/NSg1xbjDo3Z5PyIg4oaSICI/eWD/xb5xKjsrw4XCvf8s/w). **Explanation:** ``` žq # Push PI * # Multiply it with the first (implicit) input `t` ; # Halve it + # Add the second (implicit) input `x` Ž # Take the Sine of that (and output it implicitly) ``` ]
[Question] [ **This question already has answers here**: [List Prime Numbers [duplicate]](/questions/70001/list-prime-numbers) (26 answers) [List of first n prime numbers most efficiently and in shortest code [closed]](/questions/6309/list-of-first-n-prime-numbers-most-efficiently-and-in-shortest-code) (21 answers) Closed 7 years ago. Your challenge is to write a program (full program, not a function), that will take an integer and output all prime numbers up to (including) the given integer. Output is any readable list containing all integer primes (array, string, 1 prime per line, whatever you want) and must run to stdout or equivalent. Simple? Here's the twist: You may not use literals in your program. These include: * Literal numbers (0 through 9) * Literal strings (in quotes) You may not use built in prime checks EDIT: A *prime check* is a built in function that * Returns if a number is a prime number * Returns a prime number * Returns a list of prime numbers You may code your own functions that do the above Prime factorisation functions are allowed As this is code-golf, shortest answer in bytes wins [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~7~~ 6 bytes ### Six byte solution Since prime factorisation is now allowed, this is my six byte solution: ``` LDÒ€gÏ ``` Explanation: ``` L # Create the list [1, ..., input] D # Duplicate this list Ò # Get the prime factorisation of each number €g # Get the length of each prime factorisation (length 1 = prime) Ï # Keep the numbers for which is the index is equal to 1 ``` Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=TETDkuKCrGfDjw&input=MTAw). --- ### Previous solution Uses [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem). Code: ``` LÐ<!n%Ï ``` Explanation: ``` L # Generate the list [1, ..., input]. Ð # Triplicate the list. < # Decrement the last one by one. ! # Take the factorial. n # Square each. % # Modulo the list by [1, ..., input]. Ï # Take the values for which the indices are equal to 1. ``` Visual explanation for input **n = 9**: ``` Command - Stack L # [1, 2, 3, 4, 5, 6, 7, 8, 9] Ð # [1, 2, 3, 4, 5, 6, 7, 8, 9] × 3 < # [1, 2, 3, 4, 5, 6, 7, 8, 9] × 2, [0, 1, 2, 3, 4, 5, 6, 7, 8] ! # [1, 2, 3, 4, 5, 6, 7, 8, 9] × 2, [1, 1, 2, 6, 24, 120, 720, 5040, 40320] n # [1, 2, 3, 4, 5, 6, 7, 8, 9] × 2, [1, 1, 4, 36, 576, 14400, 518400, 25401600, 1625702400] % # [1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 1, 0, 1, 0, 1, 0, 0] ``` Which leaves us (using `Ï`): ``` [1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 1, 0, 1, 0, 1, 0, 0] 2 3 5 7 ``` Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=TMOQPCFuJcOP&input=MTAw). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ ~~9~~ ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) *1 byte saved thanks to Dennis.* ``` Ṗ!²%ḊT‘ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmWIcKyJeG4ilTigJg&input=&args=MjA) This is my first (working) Jelly program. I have no idea what I'm doing. :P Also uses Wilson's theorem. [Answer] # 05AB1E, 2 bytes ``` !f ``` Allowing prime factorization makes this a bit too easy... [Try it online!](http://05ab1e.tryitonline.net/#code=IWY&input=Ng) ### How it works ``` ! Compute the factorial of the input. f Find its prime factors. ``` [Answer] # Pyth, 11 bytes ``` f!%h.!tTTtS ``` [Try it online.](http://pyth.herokuapp.com/?code=f!%25h.!tTTtS&input=20&debug=0) Uses Wilson's theorem. Not my own idea (suggested to [DenkerAffe](https://codegolf.stackexchange.com/a/80776/30164) by [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun) & used already by [Adnan](https://codegolf.stackexchange.com/a/80781/30164)), so I'm making it a community wiki. [Answer] # Ruby, 53 ``` $..upto(gets.to_i){|i|($....i).one?{|f|i%f<$.}&&p(i)} ``` This uses the `$.` magic variable in place of numeric literals, since it starts off as `0` and is incremented when we call `gets` to read from standard input. We can then define a prime number as a number that has exactly one factor less than it (`$....i` means the range from `1` to `i` excluding `i`) to avoid erroneously printing 0 and 1. [Answer] ## JavaScript (ES6), 98 bytes ``` alert([...Array(-~(n=prompt())).keys()].filter(n=>n>!!n&&[...Array(n)].ev‌​ery((_,i)=>i==!!i||n%i))) ``` ``` f=n=>[...Array(-~n).keys()].filter(n=>n>!!n&&[...Array(n)].every((_,i)=>i==!!i||n%i)) ``` ``` <input id=i oninput=o.value=f(i.value)><input id=o> ``` [Answer] # Retina, ~~29~~ 27 bytes ``` !&`(?!.$|(?<k>..+)\<k>+$).+ ``` [Try it online!](http://retina.tryitonline.net/#code=ISZgKD8hLiR8KD88az4uLispXDxrPiskKS4r&input=MTExMTExMTExMTE) Input/output in unary. ## How it works: It matches, with overlapping (`&`), the substrings of the input that are not 1 (`(?!.$`) and are not composite numbers (`(?<k>..+)\<k>+$`), then output all matches linefeed-separatedly (`!`) [Answer] # Pyth, 13 bytes ``` fqh!Z/%LTSTZS ``` [Try it here!](http://pyth.herokuapp.com/?code=fqh!Z%2F%25LTSTZS&input=12&debug=0) ## Explanation Using the shortest (but most inefficient) way to check for primes. ``` fqh!Z/%LTSTZSQ # implicit: Q = input f SQ # Filter [1...Q] with T L ST # Map over [1...T] % T # T module the lambda var / Z # Count number of zeroes qh!Z # If ^ is 2, it's a prime ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` :t!\~sqq~f ``` [Try it online!](http://matl.tryitonline.net/#code=OnQhXH5zcXF-Zg&input=MTA) It could be shortened to **9 bytes** using `H` (which produces predefined literal `2`). But it feels like cheating: ``` :t!\~sH=f ``` [Try it online!](http://matl.tryitonline.net/#code=OnQhXH5zSD1m&input=MTA) ### Explanation ``` : % Implicitly take input N. Generate row vector [1 2 ... N] t! % Duplicate and transform into column vector \ % Modulo operation, element-wise with broadcast ~ % Logical negate. Transform zeros to 1, non-zeros to 0 s % Sum of each column qq % Decrement by 1, twice. Zeros correspond to primes ~f % Indices of zeros. Implicitly display ``` [Answer] # [Perl 6](http://perl6.org), ~~51 48~~ 47 bytes ``` ~~.say for grep {!first $\_%%\*,[\*]^.. .sqrt},[\*]^..get~~ ~~.say for grep {!first $\_%%\*,[\*]^..^$\_},[\*]^..get~~ .say for grep {!grep $_%%*,[*]^..^$_},[*]^..get ``` ### Explanation: `[*]` / `[*] ()` multiply all of the elements of an empty list, which results in `1`. `$_ %% *` is a WhateverCode that returns True if `$_` is divisible by its only argument. ``` .say # call the .say method on: for # every value from: grep # only those that match: { # bare block with $_ for parameter # ( this block returns True when the value is prime ) ! # negate: ( True for Nil, False for a number ) first # return the first value that is $_ %% *, # divisible by one of the following # 「2 .. $_.sqrt.floor」 [*] # 1 ^.. # Range that ignores the first value .sqrt # the square root of the value we are checking for primality }, # 「2 .. get」 [*] # 1 ^.. # Range that ignores the first value get # read a line from $*IN ``` The 48 byte example tests against a Range that is from 1 up to the value to check for primality, excluding both end points. --- That will run slower as the prime numbers increase, as it checks against all values up to the square root of the number it is testing. It will be more performant if you cache the primes as you go, and only test against them. ( There may be a point where the previous code will be more performant if you run out of memory, and it has to page the cache out to disk ) ``` my @p;.say for grep {push @p,$_ if !first $_%%*,@p},([*])^..get ``` --- The normal way to write something that prints out primes would be: ``` .say for grep *.is-prime, 2..get ``` ( I would probably use `@*ARGS[0]` instead of `get` so that it gets input from the command line instead of STDIN ) [Answer] # J, 22 bytes ``` ([:>:@I.>:|*:@!)@i.@x: ``` Also uses Wilson's theorem. ## Usage ``` f =: ([:>:@I.>:|*:@!)@i.@x: f 9 2 3 5 7 f 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 ``` [Answer] # Python 2, 74 bytes ``` lambda n:[-p for p in range(-n,n/-n)if all(p%i for i in range(-~True,-p))] ``` [Answer] # JavaScript (ES6), 110 bytes ``` f=n=>{p=true;q=[];for(i=p+p;i<=n;i++){for(j=i/i;++j<i;p=i%j?p:p>p);p?q.push(i):i;p=true}alert(q)};f(+prompt()) ``` Thanks to @LeakyNun for helping me shorten my solution. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` $!$pd. ``` Saved a crapload of bytes thanks to @LeakyNun, who pointed out that you can use prime factorization built-ins. [Answer] # Python 2, 102 bytes ``` p=input() q=p/p print[i if min([i%l for l in range(q+q,i)]+[q])>q-q else None for i in range(q+q,p+q)] ``` [Answer] # Python 2, ~~59~~ 58 bytes ``` n=input();k=p=n/n while k<n: p*=k*k;k=-~k if p%k:print k ``` Test it on [Ideone](http://ideone.com/AX7nTj). [Answer] # Perl 5, 37 bytes 36, plus 1 for `-nE` instead of `-e` ``` {/^.?$|^(..+?)\1+$/||say;s/.//;redo} ``` Input and output are in unary. [Answer] ## Mathematica, 43 bytes ``` Select[Range@Input[],Tr@Rest@Divisors@#==#&] ``` Selects from a range of integers between 1 and `Input[]` those, the sum of whose divisors, except the first one (in ascending order) is equal to the number itself. [Answer] # J, 7 bytes ``` ~.@q:@! ``` `~.` unique `@` of `q:` prime factors `@` of `!` factorial [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 14 [bytes](http://meta.codegolf.stackexchange.com/a/9411/43319) ``` ((⊢~∘.×⍨)≢↓⍳)⎕ ``` Fully parenthesised: ``` (⊢ ~ ((∘.×)⍨)) (≢ ↓ ⍳) ``` Every triple of functions applies the right and left monadic functions separately to whatever is outside of the parenthesis, and then the two results become the arguments of the middle function, thus `(f g h)A` is `(f A) g (h A)`. This repeat itself until the following tree structure: ``` ┌──────┴──────┐ ┌──┼────┐ ┌──┼──┐ ┌┴┐┌┴┐┌──┴──┐ ┌┴┐┌┴┐┌┴┐ │⊢││~││∘.× ⍨│ │≢││↓││⍳│ └─┘└─┘└─────┘ └─┘└─┘└─┘ ``` `⎕` prompt for numeric input Let's assume the user inputs `6`: `≢` tally the input (giving `1`) and `⍳` indices until the input (giving `1 2 3 4 5 6`) `1 ↓ 1 2 3 4 5 6` drop 1 from the list (giving `2 3 4 5 6`) `⊢` pass through (`2 3 4 5 6`) and `∘.×⍨` multiplication table: ``` 4 6 8 10 12 6 9 12 15 18 8 12 16 20 24 10 15 20 25 30 12 18 24 30 36 ``` `2 3 4 5 6 ~ 4 6 8 10 12 6 9`… "without" (i.e. set difference), yielding `2 3 5` [TryAPL](http://tryapl.org/?a=%28%28%u22A2%7E%u2218.%D7%u2368%29%u2262%u2193%u2373%29200&run)! ]
[Question] [ Forgetting quotes can lead to certain problems. For example, in Scala the two expressions: ``` "("+("+")+(")+(")+")" ("+("+")+(")+(")+") ``` differ only in starting and ending quotes, but they respectively yield the result: ``` (+)+() +()+()+ ``` But this expression in scala almost has the desired property: ``` def m="+m+" ""+m+"" ``` Your task is to **write the shortest expression surrounded with quotes**, such that if we remove the outer quotes, the **expression still returns the same string**. Key points: * Your language must support "..." as string literals * The program has to contain at least three characters * You are not allowed to define a context outside of the quotes themselves (as I did for m) * You are not allowed to use other delimiters for strings, e.g. no `"""`, no `'`. * Both expressions should *return strings*. * Shortest code wins (counting the quotes themselves) [Answer] # C (4 chars) The expression ``` """" ``` satisfies the minimal requirement of three characters. It encodes the empty string, no matter even if you omit one level of quotes: ``` "" ``` If you want the resulting string to be at least three characters, here is an expression of length 10 which results in three characters of string, namely three spaces: ``` "" " " " " ``` If you don't like spaces either, here are four printable characters in a length 12 expression: ``` ""/**/"/**/" "/**/"/**/ ``` Putting these expressions into a small program: ``` #include <stdio.h> #define CASE(s) printf("'%s'\n", s) int main() { CASE(""""); CASE(""); CASE("" " "); CASE(" " ); CASE(""/**/"/**/"); CASE("/**/"/**/); } ``` Output: ``` '' '' ' ' ' ' '/**/' '/**/' ``` [Answer] # Shell (3 chars) ``` "w" w ``` Both execute the [command `w`](http://linux.die.net/man/1/w). [Answer] # JavaScript, ~~28~~ ~~27~~ ~~15~~ 12 (6 if result can be non-string (still works with output)) This one's pretty interesting. ``` "+"*1+"+"+"" ``` The basic explanation is that `"string" * 1` is `NaN`, and `+"string"` is also `NaN`. Therefore, it results in the string `"NaN+"` with or without the outside quotes. For further explanation, it gets parsed as `("+" * 1) + ("+") + ("")` with the outside quotes, and `(+ "*1+") + "+"` without. The version that works if the output can be non-string: ``` "+"*"" ``` Which does work when outputting (as JavaScript is weakly typed): ``` alert("+"*"") // NaN alert(+"*") // NaN ``` --- Old version: ``` "+".replace(/./,NaN)+"+"+"" ``` With the quotes outside, it is parsed as ``` ("+".replace(/./, NaN)) + ("+") + ("") "NaN" + "+" + "" "NaN+" ``` Without the quotes, it gets parsed as ``` (+".replace(/./,NaN)+") + ("+") // +"any string" evaluates to NaN NaN + "+" "NaN+" ``` [Answer] ## Perl - 4 bytes ``` "$~" ``` Test program: ``` print"$~"; print$~; ``` Ouput: ``` STDOUT STDOUT ``` [Answer] # JavaScript, 40 ``` "(f=function (){return'(f='+f+')()'})()" ``` When you remove the quotes, it becomes an immediately invoked function expression, and this function happens to return `'(f='+f+')()'`, which is the entirety of the string. (Absuing `Function#toString`. `;)`) [Answer] ## [huh?](http://esolangs.org/wiki/Huh?), 7 ``` "Ouch!" ``` It works because both `"Ouch!"` and `Ouch!` are both invalid files, so the interpreter will return `Ouch!` [Answer] ## Update: Python (12 chars) program ``` ""+"+""+"+"" "+"+""+"+" ``` both giving ``` '++' ``` ## Python (28 chars) program ``` "".__str__()+".__str__()+""" ".__str__()+".__str__()+"" ``` both giving ``` '.__str__()+' ``` ## Python (38 chars) program ``` "".replace("+","+")+".replace("+","")" ".replace("+","+")+".replace("+","") ``` both giving ``` '.replace(,)' ``` [Answer] # Befunge 98 - 3, 4, 6, 17 In these programs, I'll assume you just want to get a string, but you don't care if the program terminates. In other words, you want a code snippet that can be placed in the code somewhere. (Note: in Befunge, whatever is on the stack is a string. It is also a number) This code snippet must be placed on the first part of the first line. ``` "g" ``` When the quotes are removed, `g` acts like `00g`, so it pushes a `g`. Either way, it pushes a `g`. ``` """" ``` Works in Befunge 93 as well; it always pushes nothing. This one is more interesting ``` ""z"z" ``` It will always push `z`. `z` is a no-op so although the IP executes the command, it does nothing (I could have used , but `z` is more interesting). This one only has one set of `"`, and is quine-like: ``` ">:0g\1+:f`1+jb<" ``` It always pushes the contents of the string, but when the quotes are removed, it does it in a quine-like way. This must be placed on the first part of the first line, but adjustments can be made to put it elsewhere [Answer] ## PowerShell, 4 chars ``` "$?" $? ``` Output: ``` TRUE TRUE ``` This uses the [automatic variable $?](http://technet.microsoft.com/en-us/library/hh847768.aspx), which is a Boolean containing the execution status of the last run command. The only effect of wrapping it in quotes is that it is converted to a string prior to being printed, which is a transparent operation. [Answer] ## GolfScript: 16 chars OK, since my 3-char solution `"1"` has been disqualified by a rules change, here's the straightforward solution in GolfScript: ``` "{`[46 126]+}.~" ``` With the quotes, this is just a double-quoted string literal. Without the quotes, it's a quine. The only slightly trickly part is that, to literally comply with the rule prohibiting alternative string delimiters, I have to encode the string `'.~'` as an array of ASCII codes `[46 126]` instead. [Answer] # Scala REPL (10 chars) ``` "0+"++"+0" 0+"++"+0 ``` are both returning: ``` 0++0 0++0 ``` **Explanation:** In the first case ++ treats the left string as a sequence of chars and concatenates the next sequence of chars and rebuilds a string. In the second case, + converts the first and last 0 to strings. Note that everything is even a palindrom. ## Other interesting solution using blocks (55 chars) ``` "{val o="*{val o=0;o}+".substring(9,12);val i="*0+";o}" {val o="*{val o=0;o}+".substring(9,12);val i="*0+";o} ``` return both smileys: ``` ;o} ;o} ``` **Explanation:** See the below decomposition ``` "{val o="*{val o=0;o}+".substring(9,12);val i="*0+";o}" --multiplied by 0=>"" --------- returns "" ----- result {val o="*{val o=0;o}+".substring(9,12);val i="*0+";o} -------- o equals ";o}"-------- -i ignored- o ``` [Answer] # Python (8 characters) ``` """""""" ``` and ``` """""" ``` both return empty string Is based on idea of MvG [Answer] # [Tcl](http://tcl.tk/), 1, 3 ``` 1 "1" ``` [Try it online!](https://tio.run/##K0nO@f@/oLSkWMGQC0wpGSr9/w8A "Tcl – Try It Online") Explanation: In Tcl, [*"quoting is a tool, not a rule"*](https://stackoverflow.com/a/1027366/383779) [Answer] ## TI-BASIC, 6 bytes ``` ""→Str1:" "→Str1: ``` Both of these end up storing an empty string to `Ans` (and to `Str1`). The second works because storing to a variable also stores to `Ans`. I also found another 6-byter: ``` "":":" ":": ``` Both of these will return `":"`. I have checked every shorter chain matching `"[":]{0-3}"`, and none meet the specifications. ]
[Question] [ Your task – if you choose to accept it – is to have your program print, literally, either one of the following: 1. `E=mc²` (if your language supports Unicode (so no HTML trickery, for instance)) 2. `E=mc^2` (if your language doesn't support Unicode) Here are the conditions: * Your program must consist of exactly two expressions (one representing the `m`, the other the `c`, in `mc²`), which, when fed into your language's representation of the formula `mc²`, and whose result is then printed, will show one of the above results. * Both expression may be assigned to variables before feeding them into `mc²`, but the expressions themselves are not allowed to use intermediate variables. * Both expressions must evaluate to an absolute value larger than 1 (e.g `abs(expression) > 1`). * You may assign the result of `mc²` to an intermediate variable, representing the `E`, before printing this `E`, but that is not necessary – you may print the result of `mc²` directly as well. * When printing the final result, you *are* allowed to use your language's libraries to convert the possibly numeric or binary result to it's string representation. * **Added condition**: no operator overloading in the final expression that represents `mc²`. The result *must* be the algebraic result of expression `m` times expression `c` squared. Here's an example template, of what I'm looking for, expressed in PHP: ``` $m = /* some expression */; $c = /* some expression */; $E = $m * pow( $c, 2 ); print $E; // should print on of the results mentioned at the beginning of this challenge ``` To be honest, I'm not even sure this challenge is doable, but my gut says it must be possible in at least one, or even a few, languages. Winning solution is the one with the shortest code, in characters, in a week from now. For clarification, it's perfectly fine to merely do something like this as well — if your language allows for it: ``` print( someExpression * someOtherExpression ** 2 ); // or something to that effect ``` ... in other words: without assigning anything to any intermediate variables. Just as long as the algebraic calculation remains intact. [Answer] # C, ~~66~~ ~~59~~ 57 bytes Ignore the compiler warnings. It should work OK as long as you compile it on a ~~big~~ *little*-endian machine. This code could probably be made a lot shorter on a 64-bit machine, but I'm unable to test: ``` main(){long long m=1130224008533LL,c=7,E=m*c*c;puts(&E);} ``` 9 fewer characters thanks to [@Adam Davis](https://codegolf.stackexchange.com/users/1686) and [@Michael](https://codegolf.stackexchange.com/users/16120) :-) [Answer] ## C, 57 53 50 40 39 bytes The rules are somewhat confusing, I do hope I read them correctly. Works on 32bit platforms only. ``` m="E=mc^2",c=-1u/2; main(){ puts(m*c*c); } ``` `c`c equals 2^31-1, so `c*c` equals 1 modulo 2^32. Therefore `m*c*c == m` (mod 2^32). The `-1u/2` constant and `puts` are hvd's suggestions. [Answer] # Java: ~~261~~ ~~241~~ ~~207~~ 206 characters Thanks to @V-X for helping me with ideas for optimizing this. Here it is, 206 characters: ``` import java.math.*;class N{public static void main(String[]y){BigInteger m=new BigInteger("12uy4kc5e",36),c=new BigInteger("5"),e=m.multiply(c).multiply(c);System.out.println(new String(e.toByteArray()));}} ``` Properly indented version: ``` import java.math.*; class N { public static void main(String[] y) { BigInteger m = new BigInteger("12uy4kc5e",36), c = new BigInteger("5"), e = m.multiply(c).multiply(c); // e = m * c * c System.out.println(new String(e.toByteArray())); } } ``` Older version, Java 8 only, with 261 characters: ``` import java.math.*;public class N{public static void main(String[]y){BigDecimal m=new BigDecimal("59324209849366147.77"),c=BigDecimal.TEN,e=m.multiply(c).multiply(c);System.out.println(new String(java.util.Base64.getDecoder().decode(e.toBigInteger().toByteArray())));}} ``` Ungolfed version: ``` import java.math.*; import static java.util.Base64.*; public class N { public static void main(String[] y) { BigDecimal m = new BigDecimal("59324209849366147.77"), c = BigDecimal.TEN, e = m.multiply(c).multiply(c); // e = m * c * c System.out.println(new String(getDecoder().decode(e.toBigInteger().toByteArray()))); } } ``` [Answer] # Perl - 32 characters ``` $m="E=mc²";$c=1.1;print$m x$c**2 ``` This is sort of cheating: in Perl's `x` operator, the right operand is converted to an integer, so both 1.1 and 1.21 (1.1\*\*2), despite having a value larger than 1, behave exactly as 1. [Answer] # APL, 27 ``` ⎕UCS(2÷⍨⎕UCS'E=mc²')×(√2)*2 ``` **Ungolfed:** ``` m←(⎕UCS 'E=mc²')÷2 c←√2 ⎕UCS m×c*2 ``` Start with the desired output string, convert it into an array of Unicode values, divide each number by 2, and assign the vector to **m**. Then assign √2 to **c**. Compute the formula and convert the resulting array back to a string. I can't tell whether the last operation is allowed by the rules, but it's akin to what most other solutions are doing, whether explicitly or implicitly. [Answer] ## TI-89 basic (needs CAS) - 17 ``` solve(√(e/m)=c,e) ``` Edited - it now works (according to my calculator): ``` e = c^2 * m and c >= 0 ``` [Answer] # Lua - 74 ``` c=rawset(_G,"print",function()io.write"E=mc^2\n"end)and 2 m=2 print(m*c^2) ``` A little cheaty, but not prohibited by the rules: * Exactly 2 expressions, one for `c`, another for `m`. * No intermediate variables * No operator overloading [Answer] # Smalltalk, 110 58 56 Version 2 below does it, but I guess version1 is interesting enough to not cut it. Read for your amusement (it's about fun here - isn't it) ### Version 1: code: ``` (Class name:#S subclassOf:String)compile:'*t^''E='',self,t';compile:'squared^self,''²'''.m:='m'as:S.c:='c'as:S ``` evaluate: ``` m*c squared ``` result: 'E=mc²' I really have a hard time to understand what you expect :-(, so I'll give some more detail than usual. Maybe it is of interest to others, even if it does not golf. First, you want the standard language syntax to be used, eg. in Smalltalk, I would write: ``` m := 100. c := 299792500. E := m * c squared. ``` to get "8987554305625000000". So you want this to be done symbolically. In ST we need a class which redefines the above used operators into string concatenations (any class would do, but I'll inherit from String for convenience, so I get the ,-operator): ``` Class name:#MyString subclassOf:String * thingy ^ self,thingy asString squared ^ self,'²' = thingy ^ self,'=',thingy ``` So now, I can write: ``` m := MyString fromString:'m'. "/ or 'm' as:MyString for short c := MyString fromString:'c'. (m * c squared) print ``` and get 'mc²' as output. However, and that's my problem: the assignment cannot be redefined, so saying: ``` E := (m * c squared). E print ``` would print the same. In Smalltalk, "=" is a comparison operator (not assignment). "=" was already redefined in the above code. However, as I am calling for a comparison of E against the right side, I need to preset E to something non-nil first: ``` E := MyString fromString:'E'. ``` So let's write: ``` (E = m * c squared) print ``` gives us (the requested?): 'E=mc²' As you wanted the result of m\*c squared, I'll push the 'E' into the multiplication operator: ``` * thingy ^ 'E=',self,thingy ``` to fullfill your requirements. PS: the second comment made it obvious; all I have to change is the assignment in the above class to generate the 'E'. ### Version 2: Obviously I was thinking way too complicated: ``` m:=36rEF7U6YC5.c:=7.E:=m*c squared.E digitBytes asString ``` also outputs: 'E=mc^2' Edit: The large number 1130224008533 is obviously shorter if written in a higher base - hex for example; but it is *much* shorter in base 36, which in Smalltalk is written as 36rEF7U6YC5. This saves me another 2 characters. PS: how to get to the magic numbers: `LargeInteger digitBytes:'E=mc^2' asByteArray` -> 55380976418117 `55380976418117 primeFactors` -> Bag('4728970747(\*1)' '7(\*2)' '239(\*1)') [Answer] # T-SQL - ~~86 bytes~~ 75 bytes I'm pretty proud of how competitive this one is for SQL the verbose blabbermouth. Found myself wishing SQL had a 64-bit binary data type so I could possibly find a bigger square root than 3, but this comes out as a pretty lean one-liner anyway. And it prints the pretty Unicode version! (Which is good, because there were no squares to factor out of the number for E=mc^2) And it *smokes* the Java entry. ;-) Jus' kiddin' - @Victor and I are kindred spirits, more interested in playing our best game than winning the prize. Here's to we the crazy ones! ### New Hotness, 75 bytes I was hoping for a larger improvement, but due to the vagaries of the query processor I have to explicitly declare @m as a BIGINT or SQL chooses the wrong bit size and the binary result is wrong. Still, better is better. ``` DECLARE @m BIGINT=33042591394;SELECT CAST(CAST(@m*3*3 AS BINARY(5))AS CHAR) ``` ### Original Submission, 86 bytes ``` DECLARE @c INT=3,@m BIGINT=33042591394;SELECT CAST(CAST(@m*@c*@c AS BINARY(5))AS CHAR) ``` [SQLFiddle Here.](http://sqlfiddle.com/#!6/d41d8/15056) Output: ``` E=mc² ``` [Answer] ## C# 180 176 171 170 165 ``` using System;namespace N{class P{static void Main(){var m=0x1072699BD55;var c=7;Console.Write(System.Text.Encoding.UTF8.GetString(BitConverter.GetBytes(m*c*c)));}}} ``` Concept like the Smalltalk version, just for C#. Output: `E=mc^2` Use the longer version `var m=0x391DAF9277DEA5D;` for `E=mc²` (actually followed by two spaces) Edits: 180 to 176: remove 4 spaces 176 to 171: inline usings 171 to 170: Use UTF8 encoding 170 to 165: WriteLine->Write, outline using System; (thanks for the comments) ]
[Question] [ (Inspired by the Keg utility of [this](https://codegolf.stackexchange.com/questions/197210/even-and-odd-numbers) challenge) Given a *non-empty* input string, e.g. `s c 1= e(a"E")`, split the input into even-odd chunks. ## Example (Feel free to suggest more) I can only think of this test case, fee free to suggest more. This input string, when mapped to its code points, yields the list `[115, 32, 99, 32, 49, 61, 32, 101, 40, 97, 34, 69, 34, 41]`. When applied modulo-2 for every item, this returns `[1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1]`. In this list let's find the longest possible chunk that is consistent with even and odd code points: ``` [1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1] ``` For the first chunk, this yields `[1, 0, 1, 0, 1]` because this is the longest chunk that follows the pattern ``` Odd Even Odd Even Odd Even ... ``` or ``` Even Odd Even Odd Even Odd ... ``` . Adding another codepoint into `[1, 0, 1, 0, 1, 1]` breaks the pattern, therefore it is the longest possible even-odd chunk that starts from the beginning of the string. Using this method, we should split the input into chunks so that this rule applies. Therefore the input becomes (the `;` here is simply a separator; this can be any separator that is not an empty string, *Including the string itself*): ``` s c 1;= e(a"E") ``` However, returning a list of strings is also permitted. ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest solution wins. Let it be known that flags don't count towards being in the pattern. They also don't count towards byte count in this challenge. * The input will only be in ASCII, and the mapping will *always* be in ASCII (as far as I can tell most golflangs use a superset of ASCII). ## Answering some of the comments * You may output strings as lists of codepoints. * "Any separator" **includes** the input string itself. * You **may** insert other characters like the MATL answer, such as alphanumeric characters. * You **may not** use integers as input instead of ASCII. Doing that will trivialize the challenge. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ ~~6~~ ~~4~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ç.¬+È ``` Input as a string, output as a 2D list of ASCII codepoint integers. -6 bytes thanks to *@Grimmy*. +1 byte now that the allowed I/O rules are finally settled.. [Try it online](https://tio.run/##yy9OTMpM/f//cLveoTXahzv@/y9WSFYwtFVI1UhUclXSBAA) or [try it online with output as a list of strings instead](https://tio.run/##yy9OTMpM/f9f79Aar8Pt/oc7ar3@/y9WSFYwtFVI1UhUclXSBAA). **Explanation:** ``` Ç # Transform the (implicit) input-string to a list of codepoint integers .¬ # Split this list of integers at: + # Sum the two codepoint at both sides of the potential split È # And check whether it is odd # (after which the resulting 2D integer list is output implicitly) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` óÈcv ¦Ycv ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=88hjdiCmWWN2&input=J3MgYyAxPSBlKGEiRSIpJw) ``` óÈcv ¦Ycv :Implicit input of string ó :Partition È :Between characters X & Y where c :Charcode of X v :Parity ¦ :Is not equal to Ycv :Parity of charcode of Y :Implicit output, joined by newlines ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~72~~ 71 bytes ``` lambda s:''.join(x+(ord(x)-~ord(y))%2*';'for x,y in zip(s,s[1:]))+s[-1] ``` [Try it online!](https://tio.run/##PckxDsIgFADQvaf4aWI@37YmdKzpaNI71A4oJWIqEOgADF4do4PTG55L@8OavqjxWjbxukkBYUA8Pa02LDbMeskide@viejQH/GMynqIbQJtIGvHQhtmPixETZg7vhTntdlBMQxwBz7CykR9qQmp@k31/0nkBJPdtBR5RSof "Python 2 – Try It Online") 1 byte thx to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` ⭆θ⁺×¶∧κ¬﹪⁺℅ι℅§θ⊖κ²ι ``` [Try it online!](https://tio.run/##NYyxDgIhEER7v2JDtSRYaGssLtHC4vQSLW0IbHQjtyhwxr9H1DjFvClmxl1tctGGWofEUvBYGi69vePDwBCmjCceKaM6izLQicebgX0s2Ec/hYjfyiF5FhuQtYF/7spOPL0@NxtyiUaSQm2tmwwsf@Dmq1ozOFisgdCqrdKzOn@GNw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input string ⭆ Map over characters and join ¶ Literal newline × Repeated by κ Current index ∧ Logical And ¬ Logical Not ι Current character ℅ Ordinal ⁺ Plus θ Input string § Indexed by κ Current index ⊖ Decremented ℅ Ordinal ﹪ Modulo ² Literal 2 ⁺ Concatenated with ι Current character Implicitly print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly) 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) (7 if we must return a list of strings - add `Ọ`.) ``` ḂI¬Żœṗ ``` A monadic Link accepting a list of integers which yields a list of lists of integers. **[Try it online!](https://tio.run/##y0rNyan8///hjibPQ2uO7j46@eHO6f///482NDTVUTA20lGwtITQJkDazBDCNjQAMkwMgJLmQAEToIQlhDaBKgBrMESVA6kF6QFrBikAmWZiiWoL0NpYAA "Jelly – Try It Online")** ### How? ``` ḂI¬Żœṗj⁷ - Main Link: list of characters (A) Ḃ - least significant bit (vectorises) I - incremental differences ¬ - logical NOT (vectorises) Ż - prepend a zero œṗ - at truthy indices (of left) partition (right=A) ``` --- ### Original challenge 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` żOḂMḊƲƝ ``` A full program using `2` as the separator. [Try it online!](https://tio.run/##y0rNyan8///oHv@HO5p8H@7oOrbp2Nz///@rFyskKxjaKqRqJCq5KmkqKGgCqUSNVAVbQ6BEsToA "Jelly – Try It Online") ### How? ``` żOḂMḊƲƝ - Main Link: list of characters, S e.g. ['4','5','7','4','0'] (from program argument '45740') Ɲ - for neighbours of S: ['4','5'] ['5','7'] ['7','4'] ['4','0'] Ʋ - last four links as a monad: O - to ordinal (vectorises) [52,53] [53,55] [55,52] [52,48] Ḃ - least significant bit (vectorises) [0,1] [1,1] [1,0] [0,0] M - maximal indices [2] [1,2] [1] [1,2] Ḋ - dequeue [] [2] [] [2] - } [[],[2],[],[2]] ż - (S) zip with (that) [['4',[]],['5',[2]],['7',[]],['4',[2]],['0']] - implicit, smashing print 4527420 ``` [Answer] # [C (clang)](http://clang.llvm.org/), 49 bytes ``` f(char*s){for(;*s;)putchar(*s)+*++s&1||puts("");} ``` [Try it online!](https://tio.run/##JYrBDoIwEAXvfMWmB9MCJqxWDWm46VcAh6YBIdFiWjgB316X9DSTec@czUfbdwg9N4N2qRdrPzmuUq/Eb5mPxilmaZb5E24bNc8ZE2oPo53hq0cLXKwJHE/w0@JMV7cV82AAK@i4btirYeLJVAI9jwdB7rp5cRYKleyhRrzlcL3kUJaRknjH6FiQyILGBwVJQxkpsf0D "C (clang) – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~18~~ 14 bytes ``` <;.1~1,2=/\2|] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/baz1DOsMdYxs9WOMamL/a3KlJmfkK6QpGBqaKhgbKVhagkgTSwUzQxDD0MBQwcRAwdJcwdhEwcwSRJoYwrQARS0tQDoMDQyQWCA9lub/AQ "J – Try It Online") *-4 bytes thanks to Bubbler* * `2|]` remainders mod 2 * `2=/\` consecutive pairs of those, are the equal? * `1,` start it off with a group * `<;.1~` cut into groups using the first element as a delimiter, ie, starting a new group whenever we consecutive items are equal, odd odd or even even [Answer] # [JavaScript (Node.js)](https://nodejs.org), 53 bytes ``` s=>s.flatMap((c,i)=>c-s[i-1]&1?l.push(c)&&[]:[l=[c]]) ``` [Try it online!](https://tio.run/##TcfNCgIhEADgV/EkM6CC/ewhcHuCnkA8yLSWMazSbL2@Radu3/fI7yz0rH2za7suo4QhYRZXOG@X3AHIVAwzWYnV@qT9mV1/yR0ItY7pFDlESgkHtVUaL47bDQpEb9TOqL1Rhz8cjZp@/XpKiOMD "JavaScript (Node.js) – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), ~~90~~ ... ~~67~~ 66 bytes ``` b;f(char*s){for(b=*s&1;*s;putchar(*s++))b^~*s&1?b=!b:putchar(59);} ``` [Try it online!](https://tio.run/##NcmxCsIwFEDR3a94ZpD3Uhw6OGgITkI/IghJbDRQ05LUwZb667EB3S732L3tdLjnbIRD@9CRJ5pdH9FInna14EkMr7EA8lRVROb6KXA2cmtOfzocSSz5qX1AgnkDAA5ZAgu1hBa1YhfFiJEoMkQfxpVV@I21Gz29oek7f9NTW/aSvw "C (clang) – Try It Online") Saved ~~9~~ ~~10~~ 11 bytes thanks to @ceilingcat!!! [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` "I@2\XI=f@ ``` Outputs each character on a different line. The separator is `1`. [Try it online!](https://tio.run/##y00syfn/X8nTwSgmwtM2zeH/f/XEpOQUIEpNVAcA) ### Explanation ``` " % Input: string (implicit). For each I % Push contents of clipboard I, initially 3 @ % Push current character 2\ % Modulo 2 of (code point) of that character. Gives 0 or 1 XI % Copy result into clipboard I = % Equal? This compares the current and previous contents of % clipboard I. Gives true or false f % Find. This outputs indices of true entries. Gives 1 or [] @ % Push current character % End (implicit) % Display stack (implicit), bottom to top. Each entry is displayed % on a different line. [] is not shown and doesn't start a new line ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~94~~ ~~97~~ 95 bytes +1 byte for allowing more than 1 cut. Had to completely rewrite my code but had a lot of help from [tsh's answer](https://codegolf.stackexchange.com/a/197364/79157) ``` s=>(r=[...s]).map(c=>c.charCodeAt()%2).flatMap((c,i,l)=>c-l[i-1]&1?b.push(r[i])&&[]:[b=[r[i]]]) ``` [Try it online!](https://tio.run/##hcuxCsIwFIXh3acIgjUXbCDVLkoUEcHFJwgZbtNUI9GUpAr68rUVOnVwPJzvv@ELow62btKHL01biTaKLQ1CMsaiAnbHmmqx1UxfMRw6sm8ozDJglcPm3J1UL@zCQUdSJ23KVcJ3Bauf8UqDtAqSRKq1LITsl1LQvjCQyIkg80g04YIYitPjFOabifaP6J1hzl9oRSMHmPx01usTft7k5J0t8WPGOBvwcoTJn3Q5pKs@RcQxWQ0k/5FCl6Yaqxyg/QI "JavaScript (Node.js) – 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/254127/edit). Closed 1 year ago. [Improve this question](/posts/254127/edit) Challenge: With any given number that has multiple digits, every digit in the number needs to repeatedly be summed together until the sum is a single digit number. To make things interesting, if there's a 0 in the number, then it must equal 26, because zero starts with the letter z, which is the 26th and final letter of the alphabet. Example: With an input of \$120\$: * \$1 + 2 + 26 = 29\$ * \$2 + 9 = 11\$ * \$1 + 1 = 2\$ The answer would be 2. Output: ``` 120 29 11 2 ``` Scoring: The code that's written in the fewest bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Do26SƲƬ ``` A monadic Link that accepts a non-negative integer and yields a list of non-negative integers. **[Try it online!](https://tio.run/##y0rNyan8/98l38gs@NimY2v@//9vaGQAAA "Jelly – Try It Online")** ### How? ``` Do26SƲƬ - Link: integer, n Ƭ - collect up (starting with X=n) while distinct applying: Ʋ - last four links as a monad: D - decimal digits (X) 26 - 26 o - logical OR (vectorises) S - sum ``` [Answer] # [Go](https://go.dev), 97 bytes ``` func f(n int){println(n) if n<10{return} k:=0 for;n>0;n/=10{if n%10<1{k+=26}else{k+=n%10}} f(k) } ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70oPX_BmoLE5OzE9FSF3MTMvKWlJWm6FjcT00rzkhXSNPIUMvNKNKsLioBUTp5GniZXZppCno2hQXVRaklpUV4tV7aVrQFXWn6RdZ6dgXWevi1QCqRE1dDAxrA6W9vWyKw2Nac4FcQECdbWcqVpZGty1UIs2ga2B2SxhqZCNVDK0MgALrlgAYQGAA) [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 8.5 bytes (17 nibbles) ``` /`.$+.`@~$?$$26@ ``` Returns just the final digit. If we can return the sequence (for instance, 120 29 11 2, as in the example) then we can drop the initial `/` and final `@` for 7.5 bytes (`/`.$+.`@~$?$$26@`) ``` `. # iterate while unique: `@ $ # convert to digits in base ~ # 10 (default) . # now map over each digit ?$ # if it's nonzero $ # then that digit 26 # otherwise 26 + # now sum the list / # finally, fold from right @ # each time returning right argument # (so returning the last element) ``` [![enter image description here](https://i.stack.imgur.com/4B1dP.png)](https://i.stack.imgur.com/4B1dP.png) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 14 bytes ``` {`0 998 . $* . ``` [Try it online!](https://tio.run/##K0otycxL/P@/OsGAy9LSgkuPS0WLS@//f0MjAwA "Retina 0.8.2 – Try It Online") Only outputs the final digit. Explanation: ``` {` ``` Repeat until the value doesn't change, i.e. it's a single digit `1-9`. ``` 0 998 ``` Replace `0`s with `998`, which has a digit sum of 26. ``` . $* . ``` Calculate the sum of the values of the digits by converting each digit separately to unary and then converting the total back to decimal. [Answer] # Excel (ms365), 83 bytes [![enter image description here](https://i.stack.imgur.com/TxKa6.png)](https://i.stack.imgur.com/TxKa6.png) Formula in `B1` for 117 bytes: ``` =TOCOL(SCAN(A1,ROW(1:9),LAMBDA(a,b,IF(b=1,a,LET(c,--MID(a,SEQUENCE(LEN(a)),1),d,SUM(IF(c,c,26)),IF(a=d,NA(),d))))),3) ``` Formula in `C1` for 83 bytes: ``` =REDUCE(A1,ROW(1:9),LAMBDA(a,b,LET(c,--MID(a,SEQUENCE(LEN(a)),1),SUM(IF(c,c,26))))) ``` --- **Note:** If Excel's 15 digits precision becomes a problem with huge numbers than `A1` should be text input. I have tried but never needed more than 9 iterations to get to a single digit. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` _ì xª26}hN â ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=X%2bwgeKoyNn1oTiDi&input=MTIw) ``` _ì xª26}hN â :Implicit input of integer U _ :Function taking an integer as argument ì : To digit array x : Sum of each ª26 : Logical ORed with 26 } :End function N :Starting with the array of all inputs (i.e., [U]) h :Run the function and push the result to N until length U â :Deduplicate :Implicit output joined with newlines ``` [Answer] # [Python 2](https://docs.python.org/2/), 56 bytes ``` f=lambda n:[n][n-9:]or[n]+f(sum(int(c)or 26for c in`n`)) ``` A recursive function that accepts a non-negative integer and returns a list of non-negative integers. **[Try it online!](https://tio.run/##FYtBCsIwFAX3nuIt/6cKNgvBgCcJgcZqNNC@lDQuPH2Mm2FmMdu3vjNNa/G2hPX@CKB19I6nq/W5dB2i7J9VEqvMmgvMJXbOSJw4qbZ/sReWtFcpga@nmFEVA9xozt4esJV@g0dEobYf "Python 2 – Try It Online")** --- # [Python 3](https://docs.python.org/3/), 60 bytes ``` f=lambda n:[n][n-9:]or[n]+f(sum(int(c)or 26for c in str(n))) ``` A recursive function that accepts a non-negative integer and returns a list of non-negative integers. **[Try it online!](https://tio.run/##FYxBCsIwEEX3nmKWM1TBRhAMeJKQRdoaDbQ/ZRIXnj42m8fnwX/7r34ybq3F5xq2aQkE6@AdLg/rsx5ziFy@GydUniUrmXs8OFMClaoMEWndoJs1lcoa8H6xGUVoIDeaq7cn2rUXcKbYL@0P "Python 3 – Try It Online")** [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 53 bytes ``` [ [ >dec "0" "J" replace 48 v-n Σ ] to-fixed-point ] ``` [Try it online!](https://tio.run/##TY/BasMwEETv@Yqpz7Xslh4aBwK5JLiUXEJPIRhFXtsisiSkTZp@T/@nv@TW9qW3HWaYN9tIxS4MH4dyvysQvdHM2rboJXfiRqMZZ@FliBTm@2q1cjVBuf6srZxCPhDzlw/aMi4ULBmsUO4LtM40i817uTkUWNekYK/9mcI6chhJeADddeQIbbGd5iAXy@UKkQgds49FltVORdFM7kgWLrSZcpbJcvbpQp1WVctV9Vf/@G@t6Lg3i6fnfDjiOMOTPEHyliCQN1IRXl5xSy1@vnECu7TRd6pT78YvToOSxkAMvw "Factor – Try It Online") The only mildly clever thing this does is replace `0` with `J` in the string representation of the number so it ends up as 26 after converting to digits. * `[ ... ] to-fixed-point` Call `[ ... ]` on the input until it stops changing. * `>dec` Convert a number to a string. * `"0" "J" replace` Replace the zeros with `J`. * `48 v-n` Subtract 48 from each code point in the string. * `Σ` Take the sum. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~12~~ ~~9~~ 7 bytes ``` ω(ṁ|26d ``` *Edit: -2 bytes by copying the logical-OR trick from [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/254150/95126)* [Try it online!](https://tio.run/##yygtzv7//3ynxsOdjTVGZin///83NDIAAA "Husk – Try It Online") Returns just the final digit. If we need to return the sequence (for instance, 120 29 11 2, as in the example) then exchange the initial `ω` for `U¡` for [8 bytes](https://tio.run/##yygtzv7/P/TQQo2HOxtrjMxS/v//b2hkAAA) (`U¡(ṁ|26d`). ``` ω( # Find fixed point by iterating: d # get decimal digits ṁ # map over each digit # and sum the result: | # second arg if truthy (1-9) 26 # otherwise 26 ``` [Answer] # [Python](https://www.python.org), ~~68~~ ~~66~~ 60 bytes \*-2 bytes thanks to [c--](https://codegolf.stackexchange.com/users/112488/c) ``` f=lambda n:n>9and[n]+f(sum(int(d)or 26for d in str(n)))or[n] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3bdJscxJzk1ISFfKs8uwsE_NSovNitdM0iktzNTLzSjRSNPOLFIzM0oBkikJmnkJxSZFGnqYmUBSoDmLG2oIikMo0DUMjA01NiBjMfAA) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 15 bytes ``` Wg QT=Qsm|sd26` ``` [Try it online!](https://tio.run/##K6gsyfj/PzydKzDENrA4t6Y4xcgs4f9/QyMDAA "Pyth – Try It Online") ### Explanation ``` implicit Q = eval(input()) WgQT while Q >= 10 (print Q when this is checked) =Q assign Q to s the sum of m ` map the digits of Q to |sd26 themselves, unless they are 0, then 26 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` <A?N:ßNpUì xª26)Ì ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=PEE/TjrfTnBV7CB4qjI2Kcw&input=MTIw) Explanation: ``` <A?N:ßNpUì xª26)Ì # At first iteration, U = input, N = [input] <A # Check whether U is less than 10 ? # If so: N # Output N : # Otherwise: Uì # Get the digits of U x # Sum them with this modification: ª # Replace 0 26 # With 26 Np ) # Append the result to N ß # Repeat the program with new U: Ì # The last number in N ``` [Alternate](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=qEGp305wVewgeKoyNinMCk4&input=MTIw) which avoids the ternary expression, but it's not shorter. [Answer] # [Ruby](https://www.ruby-lang.org/), 44 bytes ``` F=->n{(p n)>9?F[n.digits.sum{_1<1?26:_1}]:n} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN3XcbHXt8qo1ChTyNO0s7d2i8_RSMtMzS4r1iktzq-MNbQztjcys4g1rY63yaiF6lrlFGxoZxEI4MIMA) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~8~~ 7 bytes ``` f0₄V∑)↔ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJmMOKChFbiiJEp4oaUIiwiIiwiMTIwIl0=) Outputs the whole list. I may have forgotten there's a built in for 26 lol. ## Explained ``` f026V∑)↔ )↔ # Until applying the following doesn't result in a different value, collect intermittent values. f # flatten the function argument 026V # and replace 0s with 26 (the 0 and 26 are pushed separately) ∑ # sum the resulting list ``` [Answer] # [sed](https://www.gnu.org/software/sed/) `-E`, 79 bytes ``` :a /^a{10}*(A|$)/s/$/ABBBBB/ s/B/AAAAA/ s/(a+)\1{9}(.*)/\1\U\2/ ta s/A+/\L&/ ta ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlWbSSrqtS7IKlpSVpuhY3_a0SufTjEqsNDWq1NBxrVDT1i_VV9B2dQECfq1jfSd8RBEBMjURtzRjDastaDT0tTf0Yw5jQGCN9rpJEoJSjtn6MjxqIAzEWavqCmxWJAwQgDgAA) **Explanation:** ``` :a # check for divisibility by 10 # if it is divisible, then add 26 to sum # B = 5A, A = 1, ABBBBB = 26 /^a{10}*(A|$)/s/$/ABBBBB/ s/B/AAAAA/ # divide the number by 10 and add remainder to the sum s/(a+)\1{9}(.*)/\1\U\2/ ta # change the sum back to normal number s/A+/\L&/ # repeat till the number is single digit # uses the fact that division is performed only on numbers > 9 # and otherwise the sum is zero, thus no conversion back to normal number is performed ta ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` W⊖Lθ≔IΣEθ∨Iκ²⁶θθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDJTW5KDU3Na8kNUXDJzUvvSRDo1BTU1PBsbg4Mz1PwzmxuEQjuDRXwzexQKNQR8G/CCKUramjYGQGVAikCzWtuQKKMvNKgDqt//83NDL4r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Only outputs the final digit. Explanation: ``` W⊖Lθ ``` Repeat until the input only has one digit. ``` ≔IΣEθ∨Iκ²⁶θ ``` Cast each digit to integer, replace zeros with 26, take the sum, then cast back to string again. ``` θ ``` Output the final digit. [Answer] # [Gaia](https://github.com/splcurran/Gaia), 11 bytes ``` ⟨$⟨26∨⟩¦Σ⟩ª ``` [Try it online!](https://tio.run/##S0/MTPz//9H8FSpAbGT2qGPFo/krDy07txhErfr/39DIAAA "Gaia – Try It Online") Outputs the final result because that seems to be allowed. Uses a similar algorithm to the Jelly answer. ## Explained ``` ⟨$⟨26∨⟩¦Σ⟩ª ⟨ ⟩ª # Until the result doesn't change: $⟨26∨⟩¦ # logical or each digit of the argument with 26 Σ # digital sum ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 49 bytes ``` k;f(n){for(k=0;n;n/=10)k+=n%10?:26;n=k>9?f(k):k;} ``` The expression `n%10?:26` returns `n % 10` if it's not 0, otherwise 26, where `:?` is the [Elvis operator](https://en.wikipedia.org/wiki/Elvis_operator), a GNU extension to the language. This returns the last number in the sequence. [Try it online!](https://tio.run/##HY6xDsIgFADn8hUvmhqIVqmDiWLpZ7i4NCD6An00tupg@utidb274UxxNSYlrxwn8Xbxzn0lFSnaVKUUfllRXsr6sN0pqrze1457cfBqTHMkEx72Asd@sBjXN80Y0sDaBok/I1rB3iybCJBi2euG4QK8Nw05PsvtbAULEqBBCpZl3X3q/hwKDbk90@RpBb8nodiYyq38GBeaa5@KE8UC2y6gweEL "C (gcc) – Try It Online") [Answer] # JavaScript (ES6), 52 bytes Returns a comma-separated string. ``` f=n=>n>9?n+[,f((g=n=>n&&(n%10||26)+g(n/10|0))(n))]:n ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i7PztI@TztaJ01DIx3MV1PTyFM1NKipMTLT1E7XyNMHsg00NTXyNDVjrfL@J@fnFefnpOrl5KdrpGkYGgGluFDFTIFAU/M/AA "JavaScript (Node.js) – Try It Online") ### Commented ``` f = n => // f is a recursive function taking the input n n > 9 ? // if n has more than one digit: n + [, // append n, followed by a comma, f( // followed by the result of a recursive call: ( g = n => // g is a helper recursive function taking n: n && ( // stop if n = 0 n % 10 // otherwise, extract the least significant digit || 26 // replace it with 26 if it's 0 ) + // g( // add the result of a recursive call with ... n / 10 | 0 // ... floor(n / 10) ) // end of recursive call to g )(n) // initial call to g ) // end of recursive call to f ] // : // else: n // append the final n and stop the recursion ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ΔS0₂:O ``` Only outputs the final digit. [Try it online.](https://tio.run/##yy9OTMpM/f//3JRgg0dNTVb@//8bGhkAAA) Outputting each intermediate step including the first would be 1 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) longer: ``` Δ=S0₂:O ``` [Try it online.](https://tio.run/##yy9OTMpM/f//3BTbYINHTU1W/v//GxoZAAA) **Explanation:** ``` Δ # Loop until the result no longer changes, using the (implicit) input: S # Convert it to a list of digits 0₂: # Replace all 0s with 26s O # Sum the list together # (after which the resulting digit is output implicitly) = # Print the current integer with trailing newline (without popping) ``` [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 161 bytes ``` [S S S N _Push_0][S N S _Duplicate][T N T T _Read_STDIN_as_integer][T T T _Retrieve_input][S N S _Duplicate_input][N S S N _Create_Label_OUTER_LOOP][S N N _Discard_top][S N S _Duplicate_top][T N S T _Print_as_integer][S N S _Duplicate_top][S S S T S T S N _Push_10_(\n)][S N S _Duplicate_10_(\n)][T N S S _Print_as_character][T S S T _Subtract][N T T S T N _If_negative_jump_to_Label_EXIT][S S S N _Push_digitSum=0][S N T _Swap_top_two][N S S S N _Create_Label_INNER_LOOP][S N S _Duplicate][S S S T S T S N _Push_10][T S T T _Modulo][S N S _Duplicate][N T S T N _If_0_jump_to_Label_ZERO][N S S S S N _Create_Label_RETURN][S T S S T S N _Copy_0-based_2nd_(digitSum)][T S S S _Add][S N T _Swap_top_two][S S S T S T S N _Push_10][T S T S _Integer-divide][S N S _Duplicate][N T S N _If_0_jump_to_Label_OUTER_LOOP][N S N S N _Jump_to_Label_INNER_LOOP][N S S T N _Create_Label_ZERO][S N N _Discard_top][S S S T T S T S N _Push_26][N S N S S N _Jump_to_Label_RETURN] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. Outputs each intermediate step (since that's shorter than only outputting the final digit anyway). [**Try it online**](https://tio.run/##TY1BCoAwDATPm1fsE9QfiRT0Jij4/DSbVDGFZDtM02c/7nad69bcSVocGFSZ1YpRIArEsJRTziz4zs@LlraUpJZvBHTBz6sF9Ztc1NCCQWnu8zJ1) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** ``` Integer n = STDIN as integer Start OUTER_LOOP: Print n as integer to STDOUT Print '\n' If n is smaller than 10 (n-10 is negative): Stop the program with an error by jumping to nonexistent Label EXIT Integer digitSum = 0 Start INNER_LOOP: Integer d = n modulo-10 If d == 0: d = 26 digitSum = d + digitSum n = n integer-divided by 10 If n == 0: n = digitSum Go to next iteration of OUTER_LOOP Go to next iteration of INNER_LOOP ``` ]
[Question] [ In the video game *Minecraft*, the player can obtain experience points (XP) from various activities. In the game, these are provided as XP "orbs" of various sizes, each of which give the player various amounts of XP. The possible orbs are shown in the image below, along with the smallest and largest amount of XP that orb can contain: [![table of Minecraft XP orbs and their minimum and maximum experience amounts](https://i.stack.imgur.com/Q8Tq4.png)](https://i.stack.imgur.com/Q8Tq4.png) [Source](https://minecraft.wiki/w/Experience#Experience_orbs) In this challenge, you should output (as a finite sequence) the minimum units of XP that these orbs can contain; specifically, output the sequence ``` -32768 3 7 17 37 73 149 307 617 1237 2477 ``` Standard loopholes are forbidden. As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest program wins. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 37 bytes ``` n=>2.42*2**n-'21221452221'[n]|-!n<<15 ``` [Try it online!](https://tio.run/##FYnLDoIwFAX3fkVd8cgpcG8LhQT8EcKCIBANtkSMK/@9lsWcZOY8x@94TO/H/pHW3We/dN52N840p5ymVkZMzKRLDhv1dvjJq21bKv3k7OG2OdvcGvcFCAwFjRIVDGo0oGLIXuMeL0lyyXPRC6nYVDWEgjAQFFABE5R0E6QIVp2Z@DxYGyMG/wc "JavaScript (Node.js) – Try It Online") [Answer] # JavaScript (ES6), 39 bytes Expects an integer \$n\$ and returns the \$n\$-th term, 0-indexed. ``` n=>309<<n>>7^"50954381462"[n]^7||-32768 ``` [Try it online!](https://tio.run/##BcFJCoQwFAXAu7hSeErmATQXEYXgRDf6I23jyrvHqm@84zX9Pue/pjQvee0ydUEy37YUgh0LzbxW0nFlRNHTMNrnqaWwxuUp0ZX2pdnTVvYMHAISChoGFg4enA3NEc9yrar8Ag "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 46 bytes The obvious method that returns a hard-coded array. ``` _=>[-32768,3,7,17,37,73,149,307,617,1237,2477] ``` [Try it online!](https://tio.run/##DchBCoAgEADA7ySska64dbCPRISYRiEaGX3fnONc9rPFPef98pR3X4Opm5kXjpL0CAgEggAJCEGoCXAg0G2EbCcV0VpdTiVH38d8dKFjrP4 "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` “Ḣƈ¤’b6ḄƤ+.⁽Ṭḥ;Ḥ ``` [Try it online!](https://tio.run/##ASwA0/9qZWxsef//4oCc4biixojCpOKAmWI24biExqQrLuKBveG5rOG4pTvhuKT//w "Jelly – Try It Online") Outputs the full sequence, with trailing `.0`s due to a horrifyingly scuffed golf on the only way I could figure out how to compress `-32768` that doesn't only break even as chained. Based on the common doubling observation, this abuses the binary conversion builtin to compress a pattern in the *maxima* rather than the minima; before figuring out the `+.` trick `“Ŀ¶ƈR’Do-ḄƤ⁽ṬḥḤ¤;` tied (with `“Ḣƈ¤’b6ḄƤḤ‘⁽ṬḥḤ¤;`) by compressing the same pattern for the minima directly. ``` “Ḣƈ¤’ 12414254 b6 converted to base 6: “Ḣƈ¤’b6 [1, 1, 2, 2, 0, 2, 5, 2, 2, 2]. ḄƤ "Convert" each prefix "from binary"; Ḅ i.e. multiply and sum with powers of 2. +. Add 0.5 to each result, ⁽Ṭḥ; prepend -16384, Ḥ and double. ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 14 bytes (28 nibbles) ``` :-32768 +~ =\ `D6 *+@$~ 157332e ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboW-610jY3MzSwUtOsUbGMUElzMFLS0HVTqFAxNzY2NjVIhqqCKYZoA) Similar 'difference-from-doubling-sequence' concept to [leo848's answer](https://codegolf.stackexchange.com/a/266159/95126) & [unrelated string's answer](https://codegolf.stackexchange.com/a/266165/95126), but slightly different logic at each step. ``` :-32768 +~ =\ `D6 *+@$~ 157332e `D6 157332e # convert from base-6 # to get: # [2,1,2,2,0,2,5,2,2,2]; =\ # now scan across this, +@$ # adding each number to result-so-far * ~ # and doubling +~ # add 1 to every element :-32768 # and prepend -32768 ``` (Trivial compression would be [20.5 bytes](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWNzWsdI2NzM0sElyMTMwtFCxMLczMTM0SUyySLUwSLYzSUkwMk5OTUszSIOqh2mDaAQ)) [Answer] # [Rust](https://www.rust-lang.org), 49 bytes Trivial solution. Takes a number and returns the sequence at that index. ``` |i|[-32768,3,7,17,37,73,149,307,617,1237,2477][i] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY1BCoMwEEX3OcXUVQKjGCOORexFxEUXBgZsKho31ZykGxftCXqa3qaCXT148P5_vsZ58tvHOrhd2UkFi-g7Dxbq9-xtXH71ymsTm4yKEg0SakJDSAZ1fkaTEha70dnuspyobbj9hxdRCXsfgYEdpPPEjy5JdLofAAwjO9-7k4ysXDgoqGEJEYKVrFQlghDhWNm2gz8) # [Rust](https://www.rust-lang.org), 76 bytes Nontrivial solution. Relies on the fact that the numbers mostly double and then add to a fixed amount. This array could perhaps be golfed more, or be constructed in a different way. The `scan` also looks like it could be shortened somehow. Returns an iterator that contains the sequence. ``` ||[-32768,65539,1,3,3,-1,3,9,3,3,3].iter().scan(0,|s,x|{*s=*s*2+x;Some(*s)}) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dYyxCoMwAET3fEXq0iRGrYpWEf_AraOUIsXQgMZiIgSMX9LFof0o_6a2di033MG9u8ezH6Sal4IJ2FZcIAxH0NQKMpgDjwDDDfId7rZr5WNMnDA4xold-jRc5Xws_cbw7HJV9wgD4r0GxZxkKYwpN57GURSm9P_IlddKoAM1kmozEpkTSQJbZ6eurRGReMK_zz3IAFt51vWXurrekNHm3nOhGrFD1qgnC-MMgGnD53nzNw) # [Rust](https://www.rust-lang.org), 67 bytes Same approach, but uses `fold` to automatically exhaust the iterator. Yes, the extra `3` is there on purpose although the value of the number is irrelevant. The output is cluttered with line numbers and debug stuff though, I am not aware on the consensus of this for [sequence](/questions/tagged/sequence "show questions tagged 'sequence'"). ``` ||[65539,1,3,3,-1,3,9,3,3,3,3].iter().fold(-32768,|s,x|dbg!(s)*2+x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqLS4ZMHNmWl5CrmJmXkamgrVXDmpJQppCrZc-lpcNZk1Goa6mXq5QClDTU0tXWMjczML7WhDHWMg1AVRlmCmcaxeZklqkYYmV01NNESVjpmpqbGlDm6lesXJiXkaBjo1xToVNdVaxbZaxVpG2hXWwfm5qRpaxZq1mlxa-ktLS9J0LW46A43FZR6SiWn5OSkaUOvBxqYkpStqFGuCzNWEGLWKy5orTUPTmourFiKwYAGEBgA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •δ«иé•ηC·>žG(š ``` -1 byte thanks to *@CommandMaster*. [Try it online.](https://tio.run/##yy9OTMpM/f//UcOic1sOrb6w4/BKEHO786Htdkf3uWscXfj/PwA) **Explanation:** ``` •δ«иé• # Push compressed integer 1122025222 η # Pop and push a list of its prefixes C # Convert each prefix from a binary-string to a base-10 integer · # Double each > # Increase each by 1 žG # Push builtin integer 32768 ( # Negate it š # Prepend this -32678 to the list # (after which the list is output implicitly as result) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•δ«иé•` is `1122025222`. [Answer] # [ARBLE](https://github.com/TehFlaminTaco/ARBLE), 40 bytes ``` -2^15,3,7,17,37,73,149,307,617,1237,2477 ``` Ultra trivial solution. Outputs the first number with a trailing `.0` [Try it online!](https://tio.run/##DcjJCQAgDATAhlYwhy42Iyj482X/EDPPWW/fE1F0SoOBEMIIGsQHrBI9RzRPnYz4 "ARBLE – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes ``` ⁺-”)‴⧴1³∧◨¤›✂⊗&→⁵⊖;⁹WT∧ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCMgp7RYQ0lXSUdBydjI3MwiJs84Js88Js8QiI2B2BzINTSxBHIMgDwzkLChEUjCyMTcXElT0/r///@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Outputs the entire sequence. Explanation: Simply compressing the whole string would have taken 27 bytes, but removal of the leading `-` allows Charcoal to compress the remainder into a 22-byte string (21 without the trailing delimiter) and then two bytes are used to prefix the `-` again. Without string compression, the best I can do is ~~31~~ to port @UnrelatedString's Jelly answer for 26 bytes: ``` -32768¶IEχ⍘⪫11…122025222ι² ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjfjAooy80o0lHSNjczNLGLylDStuSBCzonFJRq-iQUahgY6Ck6JxanBJUDxdA2v_Mw8DSVDQyUdBefK5JxU54z8AiDfyMjAyNTIyAgonKmpqaNgpAkE1kuKk5KLoXatj1bSLcsByivp6qYkK8VChQE "Charcoal - Attempt This Online") Link is to verbose version of code. Outputs the entire sequence. Explanation: ``` -32768¶ Literal string `-32768\n` Implicitly print χ Predefined variable `10` E Map over implicit range 11 Literal string `11` ⪫ Join characters with 122025222 Literal string `122025222` … Truncated to length ι Current value ⍘ Converted from "base" ² Literal integer `2` I Cast to string Implicitly print ``` My previous 31-byte answer translated into a 40-byte ES6 solution, which has since been beaten by a couple of similar-looking answers: ``` f= n=>n--?(155<<n>>5)-"1221463333"[n]:n<<15 ``` ``` <input type=number min=0 max=10 oninput=o.textContent=f(this.value)><pre id=o> ``` Returns the `n`th value (`0`-indexed). [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 20 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` cE#37FY_x5ò_∞ï┴)3▬+] ``` [Try it online.](https://tio.run/##ASgA1/9tYXRoZ29sZv//Y0UjMzdGWV94NcOyX@KInsOv4pS0KTPilqwrXf//) **Explanation:** ``` c # Push -2 E # Push 15 # # Pop both, and push -2**15: -32768 3 # Push 3 7 # Push 7 F # Push 17 Y # Push 37 _ # Duplicate the 37 x # Pop and reverse it to 73 5ò # Loop 5 times, ò # using the following eight characters as inner code-block: _ # Duplicate the top ∞ # Pop and double it ï # Push the 0-based index ┴ # Check whether it's equal to 1 (1 if index=1; 0 otherwise) ) # Increase it by 1 (2 if index=1; 1 otherwise) 3 # Push a 3 ▬ # Pop both, and push 3**((index==1)+1) + # Add it to the doubled value ] # Wrap all values on the stack into a list # (after which the entire stack is output implicitly as result) ``` ]
[Question] [ Given a set of vectors all of the same positive finite dimension, output a falsey value if they are linearly dependent and a truthy value if they are linearly independent. A set of vectors v1, v2, ... is linearly dependent if for some scalars a1, a2, ... not all equal to 0, a1v1 + a2v2 + ... = 0. (0 is the zero vector.) Note: Using an inbuilt function to find the rank of a matrix or test vectors for linear dependence is not allowed. Note 2: All input will be formed from integers. Test cases (input -> output): ``` [[0,1],[2,3]] -> True [[1,2],[2,4]] -> False [[2,6,8],[3,9,12]] -> False [[1,2],[2,3],[3,4]] -> False [[1,0,0],[0,1,0],[0,0,1]] -> True [[0]] -> False [] -> True [[1,1],[0,1],[1,0]] -> False [[1,2,3],[1,3,5],[0,0,0]] -> False ``` [Answer] # Julia, ~~28~~ 27 bytes ``` X->X==[]||eigmin(X'X)>eps() ``` This is an anonymous function that accepts a 2-dimensional array with the vectors as columns and returns a boolean. To call it, assign it to a variable. For any real, [non-singular](https://en.wikipedia.org/wiki/Invertible_matrix) matrix **X**, the square matrix **X**T**X** is [positive definite](https://en.wikipedia.org/wiki/Positive-definite_matrix). Since a matrix is non-singular if and only if all of its column vectors are linearly independent and non-singular implies **X**T**X** is positive definite, we can declare the vectors to be linearly independent if the product is positive definite. A matrix is positive definite if and only if all of its [eigenvalues](https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors) are strictly positive, or equivalently when its smallest eigenvalue is strictly positive. So for an input matrix **X**, we construct **X**T**X** and get the minimum eigenvalue using `eigmin(X'X)`. To account for floating point error, we check this against the machine precision, `eps`, rather than 0, to declare positivity. Since we also want empty input to return `true`, we can simply add the condition `X==[]`. Saved 1 byte thanks to Dennis! [Answer] # Matlab - ~~19~~ 16 bytes ``` @(A)det(A*A')>.5 ``` If the product of the matrix and its transpose is singular, then the rows of the matrix are linearly dependent. The determinant is non-negative, and since the entries are integral (thank you Alex A.), the determinant is integral and can be compared to .5. It would have been nice to just do `@(A)~det(A*A')`, but unfortunately `det` can give almost-zero for singular matrices. [Try it on ideone](http://ideone.com/Dbh521) [Answer] # R, ~~72~~ 60 bytes ``` function(x,m,n)!is.null(x)&&all(pracma::rref(x)==diag(,m,n)) ``` This is a function that accepts the vectors as columns in a matrix as well as the dimensions of the matrix and returns a logical. To call it, assign it to a variable. It requires the `pracma` package to be installed but it doesn't have to be imported. The actual checking for linear independence is done by row reducing the matrix to echelon form and checking whether that's equal to an identity matrix of matching dimension. We just need a special case for when the input is empty. Saved 12 bytes with help from Luis Mendo! [Answer] # Mathematica - 29 bytes ``` #=={}||Det[#.Transpose@#]!=0& ``` Uses the property that the product of the eigenvalues of matrix A is equal to the determinant of A. Sample ``` #=={}||Det[#.Transpose@#]!=0&@{{1,2,3},{1,3,5},{0,0,0}} >> False ``` [Answer] # Julia, 14 bytes ``` M->det(M'M)>.5 ``` Based on [@Anna's MATLAB answer](https://codegolf.stackexchange.com/a/78095) and [@AlexA.'s Julia answer](https://codegolf.stackexchange.com/a/78128). Expects a matrix whose columns are the input vectors and returns a Boolean. `det` returns a float, so we cannot compare the result directly with **0**. However, since the entries of **M** are integers, the lowest possible positive determinant is **1**. ### Verification ``` julia> f = M->det(M'M)>.5 (anonymous function) julia> [f(M) for M in( [0 2;1 3], [1 2;2 4], [2 3;6 9;8 12], [1 2 3;2 3 4], [1 0 0;0 1 0;0 0 1], zeros((1,1)), zeros((0,0)), [1 0 1;1 1 0], [1 1 0;2 3 0;3 5 0] )] 9-element Array{Any,1}: true false false false true false true false false ``` [Answer] # NARS2000 APL, 12 bytes ``` (≡≤-.×)⊢+.×⍉ ``` ### How it works ``` (≡≤-.×)⊢+.×⍉ Monadic function. Right argument: M ⍉ Transpose M. ⊢ Yield M. +.× Perform matrix multiplication. For empty M, this yields a zero vector (for some reason). ( ) Apply this matrix to the matrix product: -.× Compute the determinant. This (mistakenly) yields 0 if M is empty. ≡ Yield the depth of M (1 is non-empty, 0 if empty). ≤ Compare. Since 0≤0, this corrects the error. ``` [Answer] # Octave, ~~32~~ 27 bytes *Thanks to @Suever for removing 5 bytes!* ``` @(x)~numel(x)|any(rref(x)') ``` The code defines an anonymous function. To call it assign it to a variable or use `ans`. The result is a non-empty array, which in Octave is truthy if all its entries are nonzero. [Try all test cases online](http://ideone.com/q8NrJg). This is based on the [reduced row echelon form](https://en.wikipedia.org/wiki/Row_echelon_form) of a matrix. A non-empty matrix is full-rank [iff](https://en.wikipedia.org/wiki/Rank_(linear_algebra)#Computing_the_rank_of_a_matrix) each row of its reduced row echelon form contains at least one non-zero entry. This is checked by condition `any(rref(x)'`, where `'` can be used to transpose instead of `.'` because the entries are not complex. The empty matrix is dealt with separately by the condition `~numel(x)` (which is the same as `isempty(x)` but shorter). [Answer] # JavaScript (ES6), 162 ``` M=>M.sort((a,b)=>P(a)-P(b),P=r=>r.findIndex(v=>v)).map(_=>M=M.map((r,i)=>(p=P(r))>q?(k=M[i],q=p,r):r.map((v,j)=>v*k[q]-k[j]*r[p]),q=-1))&&M.every(r=>r.some(v=>v)) ``` Reduce the matrix and check if every row has at least 1 non zero element. *Less golfed* ``` M=>( P=r=> P=r=>r.findIndex(v=>v)), // First nonzero element position or -1 // sort to have P in ascending order, but rows all 0 are at top M.sort((a,b)=>P(a)-P(b)), M.map(_=> // repeat transformation for the number of rows M=M.map((r,i)=>( p = P(r), p > q ? (k=M[i], q=p, r) // row transform // note: a 0s row generate a NaN row as p is -1 : r.map((v,j) => v*k[q] - k[j]*r[p]) ) ,q=-1 ) ), // return false if there are rows all 0 or all NaN M.every(r=>r.some(v=>v)) ) ``` **Test** ``` F=M=>M.sort((a,b)=>P(a)-P(b),P=r=>r.findIndex(v=>v)) .map(_=>M=M.map((r,i)=> (p=P(r))>q?(k=M[i],q=p,r):r.map((v,j)=>v*k[q]-k[j]*r[p]) ,q=-1))&&M.every(r=>r.some(v=>v)) console.log=(...x)=>O.textContent += x +'\n' ;[[[0,1],[2,3]] // True ,[[1,2],[2,4]] // False ,[[2,6,8],[3,9,12]] // False ,[[1,2],[2,3],[3,4]] // False ,[[1,0,0],[0,1,0],[0,0,1]] // True ,[[0]] // False ,[[0,0],[1,1]] // False ,[] // True ,[[1,1],[0,1],[1,0]] // False ,[[1,2,3],[1,3,5],[0,0,0]] // False ,[[1,2,3],[4,5,6]] // True ].forEach(m=>console.log(m,F(m))) ``` ``` <pre id=O></pre> ``` [Answer] # MATL, ~~13~~ 11 bytes ``` t!Y*2$0ZnYo ``` Thanks to Luis for golfing off two bytes. Based on Anna's MATLAB answer. # Explanation ``` t!Y*2$0ZnYo t duplicate input ! transpose Y* matrix product, yields X^T * X 2$0Zn determinant Yo round ``` [Answer] # Python 2 with NumPy - ~~85~~ ~~112~~ ~~103~~ 102 bytes ``` import numpy x=input(i) try:print reduce(lambda a,b:a*b,numpy.linalg.eigvals(x)) except:print(x==[])|0 ``` Hopefully can get a few off, FGITW. [Answer] # [MATL](https://github.com/lmendo/MATL), 33 bytes ``` |ssQt_w2$:GZy1)Z^!2$1!G*Xs!Xa~s3< ``` This uses [current release (16.1.0)](https://github.com/lmendo/MATL/releases/tag/16.1.0) of the language, which predates the challenge. Input format is ``` [0 1; 2 3] ``` or ``` [[0 1];[2 3]] ``` [**Try it online!**](http://matl.tryitonline.net/#code=fHNzUXRfdzIkOkdaeTEpWl4hMiQxIUcqWHMhWGF-czI8&input=WzAgMTsgMiAzXQ) ### Explanation This uses only integer opeations, so it is not subject to rounding errors (as long as the involved integers don't exceed `2^52`). It works by applying the definition. It suffices to test for integer scalars *a*1, *a*2, ... between −*S*−1 and *S*+1, where *S* is the sum of absolute values of all numbers in the input 2D array. In fact much lower values of *S* could be used, but this one requires few bytes to compute. All "combinations" (Cartesian product) of values *a*1, *a*2, ... between −*S*−1 and *S*+1 are tested. The input vectors **v**1, **v**2, ... are independent iff only *one* of the linear combinations *a*1**v**1+*a*2**v**2+... gives a **0** result (namely that for coefficients *a*1, *a*2, ... = 0). ``` |ssQ % sum of absolute values of input plus 1 t_w % duplicate, negate, swap 2$: % binary range: [-S-1 -S ... S+1] GZy1) % push input. Number of rows (i.e. number of vectors), N Z^ % Cartesian power. Gives (2S+3)×N-column array !2$1! % Permute dimensions to get N×1×(2S+3) array G % Push input: N×M array * % Product, element-wise with broadcast: N×M×(2S+3) array Xs % sum along first dimension (compute each linear combination): 1×M×(2S+3) ! % Transpose: M×1×(2S+3) Xa~ % Any along first dimension, negate: 1×1×(2S+3). True for 0-vector results s % Sum (number of 0-vector results) 2< % True if less than 2 ``` [Answer] # J, 18 bytes ``` 1<:[:-/ .*|:+/ .*] ``` This is a tacit verb that accepts a matrix with the vectors as columns and returns 0 or 1 depending on whether the vectors are linearly dependent or independent, respectively. The approach is based on Anna's Matlab [answer](https://codegolf.stackexchange.com/a/78095/20469) and Dennis' Julia [answer](https://codegolf.stackexchange.com/a/78134/20469). For a matrix **X**, the square matrix **X**T**X** is singular (i.e. has zero determinant) if the columns of **X** are linearly independent. Since all elements of **X** are guaranteed to be integers, the smallest possible nonzero determinant is 1. Thus we compare 1 ≤ det|**X**T**X**| to get the result. Examples (note that `|: >` is just for shaping the input): ``` f =: 1<:[:-/ .*|:+/ .*] f |: > 0 1; 2 3 1 f |: > 1 2; 2 4 0 f |: > 2 6 8; 3 9 12 0 f |: > 1 2; 2 3; 3 4 0 f |: > 1 0 0; 0 1 0; 0 0 1 1 f 0 0 f (0 0 $ 0) 1 f |: > 1 1; 0 1; 1 0 0 f |: > 1 2 3; 1 3 5; 0 0 0 0 ``` Made possible with help from Dennis! [Answer] # Jelly, ~~5~~ 2 bytes ``` ÆḊ ``` [Try it online!](http://jelly.tryitonline.net/#code=w4bhuIo&input=&args=W1sxLDAsMF0sWzAsMSwwXV0) ]
[Question] [ Write a program in brainfuck that accepts input of 4 ASCII characters as numbers (from 32 to 126) and outputs the numbers or ASCII equivalent sorted in ascending order. Requirements: Your program should prompt the user for 4 characters that will be sorted by their ASCII value. All the inputs will be distinct. Any sorting algorithm can be used. Every cell is one byte, and the shortest code wins. If there is a tie, the code that uses the least memory cells wins. Example input: ``` (i"G ``` Example output: ``` "(Gi ``` Helpful links: [How to compare 2 numbers with brainfuck](https://stackoverflow.com/questions/6168584/brainfuck-compare-2-numbers-as-greater-than-or-less-than) If you have any questions please ask them in the comments. I tried to write a program that solves this problem. It works, but it's so inefficient and lenghty (500+) that I don't want to post it here. If you bothered to go through the pain I did, you'll get a +1 from me. [Answer] # 33 code bytes, 2n+3=11 n+4=8 memory cells Edited: I can improve memory usage by keeping the count in only one cell. ``` >,[>,]+[<[-<]>[>]>[<-[>]<.>>]<<+] ``` EOF is 0, 8 bit wrapping memory (0+256=0) ## How it works * Read all numbers * Decrement each number, keep count of how many times you do this. * When something hits zero, print the count * Repeat until count rolls over. ## Details Memory: 0(start padding),[input],...,count,0(padding),0 (more padding) ``` > (start padding) ,[>,] read input + count=1 [ while count !=0 <[-<] decrement all inputs >[>] go to an input that was just decremented to zero, or padding > point to next input or more padding [ if not padding <- change the 0 to 255 so it doesn't stop the next decrement pass [>]<. point to and print count >> point to more padding ] <<+ increment count ] ``` ## The old way ``` >,[->+>,]<[[+<-<]>[>>]>[.[>]>]<<] ``` Memory plan: ``` 0(padding),[input,count],[input,count],...,[0,0](dummy input & count) ``` Commented code: ``` > get some elbow room ,[->+>,] read each number & do an initial count/decrement pass so count is not 0 < point at last count [ while count !=0 (didn't roll over) [+<-<] decrement each number and increment each count > point at first input [>>] go to the first 0-ed input (probably the dummy input) > point at count or dummy count [ if not the dummy count . print it [>]> go to the dummy count (no other inputs will be 0 because they are all unique) ] << point at last count ] ``` [Answer] # 94 bytes code, 2n+5 = 13 bytes memory ``` >>,[>>+[->>+<<],]>>[<<<<<<[>>[<+<-[>>>]>>[-[-<<+>>]+>>>]<<<-]<[-<+>>+<]<<<]>>[>>]>>-]<<<<[.<<] ``` EOF is zero. Example: ``` $ echo -n '(i"G'|beef sort.bf ;echo "(Gi ``` [Answer] # 90 63 bytes code, 769 513 bytes memory ``` >>,[-[[>>]+[<<]>>-]>>[>>]<+<[-<<],]+[[>>]+<[<[<<]>>.>]<[<<]>>+] ``` This works much like the old way, but doesn't initialize memory with numbers. Instead, it keeps track of which location it is checking and prints that number. # The old way ``` >>>+[[->+>>+<<<]>[-<+>]>>+]<<<[<<<]>>,[[->>[>>>]+[<<<]>]>>[>>>]<<+<[-<<<]>,]>[>>[<<.>>-]>] ``` EOF is 0, 255+1 = 0 ## How it works Step 1: Prep the memory to look like: 0,0,0,[1,0,0],[2,0,0],...,[255,0,0],0 ``` >>>+[[->+>>+<<<]>[-<+>]>>+]<<<[<<<] ``` Step 2: Read the input and increment memory at (3+input\*3+2). Reading space (32) results in 0,0,0,[1,0,0],...,[32,0,1],... ``` >>,[[->>[>>>]+[<<<]>]>>[>>>]<<+<[-<<<]>,] ``` Step 3: Read through the memory and output any number that has a non-zero value two cells to the right of it. Stop after 255. This prints out the characters in ascending order. ``` >[>>[<<.>>-]>] ``` ]
[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/249759/edit). Closed 1 year ago. [Improve this question](/posts/249759/edit) ## Background I was working on a system where for convenience (not security) people could use four digit codes to identify themselves. I figured this is something that may actually be useful in many real cases, yet is well enough defined that it could make a nice challenge! ## Explanation of pin codes and typo resistant sets EDIT: Based on the comments, this is probably a more formal definition: > > I think a mathematical way of specifying what you are looking for is a > maximal set of strings with length 4 over the alphabet > {0,1,2,3,4,5,6,7,8,9} with minimum pairwise hamming distance 2, if it > helps others. > > > There are 10000 possible pin codes (0000-9999). Example pin code ``` 1234 ``` However, since a typo is easily made you are to generate a set of pincodes that is resistant to a single typo. Example of set that is NOT resistant to single typo: ``` 0000 0005 (if you mistype the last digit as 0 instead of 5, you get another code in the set) ``` Example of set that IS resistant to single typo ``` 0000 0011 0101 0202 ``` ## Allowed outputs The allowed output can be a bit flexible, specifically: * A pincode may be a string or a number * You may always have separators (e.g. comma, newline), however if your codes are always represented as 4 digits separators are optional * The codes should be represented by 0-9, not other characters Example sets: ``` 0011,0022: OK 00220011: OK 11,22,33: OK 112233: NOT OK abcd,abef: NOT OK {'1111',/n'2222'}: OK ``` ## Scoring system The primary score is the number of unique pin codes generated (note that 0001,1000 would count as 2). Edit: If your code does not always generate the same amount of unique pin codes you must estimate the amount it will at least generate in 95% of the cases and you may use that as your score. So for example if you uniformly randomly generate between 300 and 400 unique pincodes, your score would be 395. In case there is a tie, the shortest code wins! Please post your score as: Language, #Unique codes generated with bytes (e.g. Python, 30 codes generated with 123 bytes) (I guess formally this could be rewritten to 'generate X typo resistant pin codes' but as I have no idea what X is I will keep it like this, this also allows simpler solutions to compete against each other on lenght for 'third place' and beyond.) --- In principle no inputs are needed and for simplicity sake I will not make it part of the challenge and scoring, but it would be interesting to see how the code would need to be changed to allow for various length pin codes. [Answer] # [Python 2](https://docs.python.org/2/), 1000 unique pin codes, 44 bytes ``` i=0;exec'print i+int(`i`,11)%10;i+=10;'*1000 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWwDq1IjVZvaAoM69EIVMbSGokZCboGBpqqhoaWGdq2wJJdS1DAwOD//8B "Python 2 – Try It Online") I suspect 1000 pin codes is optimal. You can check the [verification program](https://tio.run/##Pdjdih3GEUXh6/RTHBuMZ0CE/u/qgHKVF5HRmAjLkpBksPPyylcK5GZjS0szZ3p1VVfNp7@@/vvjh/Ht29uXXx9v3335@vTm1eOX53@Uv31@@frH5w@PL3/8/vTn44fXj78ev378/Pjzlf949@Hxn3efnn78qc63Pz5@evgn///vX56fS3n/eP14n1/s9zefnt59@Prq8fHTy4en@vz3zy9v3r5/9@Hly9Nzgvkl3319@T2/5Hvf9M2XLy@fvz7evH//9Nvj9ev//R3m@yf77dX3/39@/PP1o3//NL99/3fP5dNn3@Tp5399/PDyw8/P377V0lrpvYxR5ixrlb3LOSWi3Ftabf66l9ZHaWOWNldpa5e2T2knSgvMraXXXnobvs4sfazS5y59ndJ3lH5u6YG5rYw6ymizjL58w13GPGWsKGPfMk4tIzC3l1lnmW2V2XeZ4/hkUea6Ze5a5mllBuaOsuoqq@2y@ilrRFnz@hFqWbuVdXpZgbmz7LrLbqfsHmWPW/asZa/mZ@1ln1F2YO4qp55yWpTTbzmjljNbOauXs4dDmeUE5u4SNUq0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M8gl2MKLnVsqgLQzsCwoGPefgEwkzqODBwaA/AgeDJxi0uIGDQfMeOCLhNHhVrRYBvqrWFwFfVXuuqrXrga@qNSEmrGqNiZa/mttfzfWv5v5XcwGsuQHWXAFr7oA1l8DKoD0CbGMTDHp6wHYjwaBPC7aFiEiYQXsl2KgvGDSbgA3VgkHXGdxzSzeMCgbDVJmrKNjEJxg0zYDNVoJBBQA2xQgGwzgiGLS9gj38gkHzD9gTKxhUMgkz6AzBXiXBoIUXrP8LBk1MYL1ZRMIMKjKwdiYYDK0md2SwNiAYNGOBlahgUBcGqwPBYLijgkFrNdj9EQyayhJm0DMNdoCCQWbBfjjBoE0c7MuISDgNXlXrYQdfVav0wVfV@kvwVbWWd/CNhFWt5c4iX3OTr7nK19zlay7zNbf5mut8zX2@xvelP3LrB1vQBYMGRrBVWDCox4AtnSJ/02IhLNcumL8oANvTBINGTLCNSDCoK4HtHoJBnxtsJcjfLYCN64JBQynYYCwY1McSZtDFBpslBYPXnCcYtLWATVSCQQ9dwgzqfGBDiGDwGhDyNxhgj7dg0OAL9rAKBj2NYK@XYNBpgr0T@UsPsK4vGDQqJ8yg2Qms7QkGlRtYSxIMXu1CMGiXSphBwzVYvQgG9WOwuywYvO5Z/moF7A6INEiNULXmM7BjE6pWSYN9QKFqr38sVO1/AQ "Python 3 – Try It Online"). ## How was this discovered? The process for discovering this rather simple formula was quite messy for me. The first insight I had was that you can transform this into a graph problem - let the PIN numbers be nodes and connect edges if and only if the hamming distance between the PIN numbers is greater than 1. Then the problem boils down to finding a [maximum clique](https://en.wikipedia.org/wiki/Clique_problem) of the graph. From reading some papers apparently there was a simple C program [available in the web archive](https://web.archive.org/web/20020201175854/http://www.tcs.hut.fi:80/%7Epat/wclique.html) that solves the maximal clique problem for small instances, so I downloaded it (and patched it a little bit since it doesn't compile on a modern compiler). I wrote a simple driver program to generate input in the format it expected and ran it. It was too slow for the full problem but I noticed something odd about its output for smaller instances: ``` ... level = 9997(10000) best = 100 time = 0.65 level = 9998(10000) best = 100 time = 0.65 level = 9999(10000) best = 100 time = 0.65 level = 10000(10000) best = 100 time = 0.65 Record: 9 10 21 32 43 54 65 76 87 98 100 111 122 133 144 155 166 177 188 199 201 212 220 234 245 253 267 278 289 296 302 313 324 330 341 356 368 379 385 397 403 414 425 431 447 458 469 470 486 492 504 515 526 537 548 559 560 571 582 593 605 616 623 638 649 657 661 672 680 694 706 717 728 739 740 751 762 773 784 795 807 818 829 835 846 852 863 874 881 890 908 919 927 936 942 950 964 975 983 991 ``` For the first 1000 PINs, the optimal clique had 100 nodes, which suspiciously looks like just the number of PINs divided by 10. And also, every prefix from `000..099` appeared once. This led me to hypothesize that there was some closed form solution of the form: ``` 10 * i + f(i) % 10 ``` It looks like `f` is almost just `f(i) = i` but occasionally it jumps some extra. After toying around a little bit, I came across the formula `(i + i / 10 + i / 100) % 10`, which passes. But `(i + i / 10 + i / 100) % 10` is just `int(str(i), 11) % 10`, that is, reinterpreting the digits of `i` in base 11! This gives the final answer. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 1000 codes generated with 7 bytes ``` 9Ý4ãʒOθ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f8vBck8OLT03yP7fj/38A "05AB1E – Try It Online") Works using the observation that you can append any function \$ f(a, b, c) \$ to all 3-digit PINs \$ abc \$ iff after fixing two of the variables you get a permutation - no value appears more than once. This code uses \$ f(a, b, c) = (1 - a - b - c) \mod 10 \$, which is equivalent to the statement that the last digit of the PIN's digit sum is 1. ``` 9Ý push [0, 1, 2, ..., 9] 4ã push the fourth cartesian power, all choices of four values from the above list ʒ keep only elements for which the following returns 1 O sum all values θ take the last digit of the sum ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 1000 codes, 16 bytes ``` (~10!+/')#+!4#10 ``` [Try it online!](https://ngn.codeberg.page/k#eJzTqDM0UNTWV9dU1lY0UTY0AAAbWQL6) -5 bytes thanks to @CommandMaster and @ovs! Uses @xnor's clever observation that each pin can satisfy `(digit sum) mod 10 == 0`. ## Explanation * `+!4#10` generate all 4-digit pins * `(...)#` filter... + `~10!+/'` equivalent to `(digit sum) mod 10 == 0` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 1000 codes, 17 bytes ``` UB0←EΦXχ⁴¬﹪Σιχ⮌Iι ``` [Try it online!](https://tio.run/##DYhBCsIwEADvviL0tIEIKXiyNwVPVkr7gpCuGoxd2W7q89OdwwxMfAeOFHKtE8olxM@LqSwzNL6x3WHgtAic7/gUZ/rwg1vKggwD/dWtd@ZknXmQQE9zyQRT@ULS1XprNSNuyCvCNayiX@lqrcct7w "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses @xnor's observation. ``` UB0 Zero-fill the output. ←E ⮌Iι Output right-aligned an in reverse order. χ Predefined variable `10` X Raised to power ⁴ Literal integer `4` Φ Filter over implicit range ι Current value Σ Digital sum ﹪ Modulo χ Predefined variable `10` ¬ Is zero ``` By replacing the `⁴` with an `N` the program will accept the number of digits in the PIN as an input. [Answer] # JavaScript (ES6), 1000 codes, 46 bytes Returns a comma-separated string. Based on [xnor's observation](https://codegolf.stackexchange.com/questions/249759/typo-resistant-pin-codes#comment557406_249762). ``` f=(n=1e3)=>--n&&n+[~(~(n/100)-n-n/10)%10,f(n)] ``` [Try it online!](https://tio.run/##TY4xbsMwDEX3noINUIdEJNVuM7WQgQw5QUfDAy3LqQtHEiQ3Y67uSJ26PXy@/8EfvnEycQ6rdH602zZpdLqx76RbKV1VuUN3xzu616auSTpZgF6aWkzoqN@iTaBhQvp8Mt4lv1i1@AvmOCenfMqkUljmFfdiT@rKAXOjhaQCj18rxxWPAmoqupp8PLP5Ri7G6U8eCjI8axigqqBTSnGvoh1/jUUMAoyAmYoU4ABoQGezm3sqo9DCW2n9f213jtHHj52AjgUMPRFtDw "JavaScript (Node.js) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `M`, 6 bytes, 1000 codes ``` k2'∑₀Ḋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJNIiwiIiwiazIn4oiR4oKA4biKIiwiIiwiIl0=) Uses that the digit sum must be divisible by 10. ``` k2'∑₀Ḋ k2' # Filter for elements in [0, 10000]: ∑₀Ḋ # Is the digit sum divisible by 10? ``` [Answer] # [Desmos](https://desmos.com/calculator), 61 bytes ``` l=[0...9999] l[[mod(floor(i/10^{[0...3]}).total,10)fori=l]=0] ``` Outputs a list of numbers. Uses xnor's observation that the digit sum has to be a multiple of 10. [Try It On Desmos!](https://www.desmos.com/calculator/ch3ptnbx9i) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/0o0djef0ls) ]
[Question] [ **This question already has answers here**: [Calculate average characters of string](/questions/53675/calculate-average-characters-of-string) (58 answers) Closed 8 years ago. You have been employed by a data analysis company, and have been appointed the task of finding the average character of a string of characters. However, this company has limited funding for code storage, so your code must be as small as possible. ## Task Write a program or function that takes one string of characters as input, and outputs the average character of that string. ## Calculation of average The average character of a string is the sum of the [ASCII values](http://www.asciitable.com/) of the individual characters divided by the total number of characters, then converted back to an ASCII character. For example, the string `cat` consists of the sequence `99 97 116` of ASCII values. These values summed equals 312, which then divided by 3 gives an average of 104. 104 represents the ASCII character `h`. The average character of the string `cat` is therefore `h`. ## Rules * You can assume the input string will only contain printable ASCII characters * If the average of the string's ASCII values is floating point, it should be rounded to the nearest integer and then converted to the equivalent ASCII character (eg. an average of 66.4 would output `B`, and an average of 66.5 would output `C`) * Input can be from STDIN (or language equivalent), or as a function parameter * Output must be to STDOUT (or language equivalent), or as a return result if your program is a function * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are not allowed * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins ## Examples Input → average → output `Hello, world!` → `89.3076923076923` → `Y` `Code golf` → `92.77777777777777` → `]` `8112015` → `50.57142857142857` → `3` [Answer] # Matlab, ~~23,21~~ 16 bytes I think this is quite obvious, if you know that matlab handles strings as arrays of characters, which can be treated like integers, aparently rounding occurs automatically when concatenated with a string. ``` @(s)[mean(s),''] ``` [Answer] # Julia, 41 bytes With help from @AlexA. ``` a->Char(round(Int,mean([Int(i)for i=a]))) ``` (Older version only worked in Julia 0.3.) [Answer] # JavaScript ES6, ~~87~~ ~~82~~ ~~81~~ 79 bytes ``` f=s=>String.fromCharCode([...s].reduce((r,c)=>r+c.charCodeAt(),0)/s.length+.5); ``` Thanks ETHproductions for the time to shorten by 5 bytes. Thanks rink.attendant for a byte less. Thanks Vihan for another 2 bytes. [Answer] ## CJam, 11 bytes ``` q_1b\,d/moc ``` [Test it here.](http://cjam.aditsu.net/#code=q_1b%5C%2Cd%2Fmoc&input=Code%20golf) ### Explanation ``` q e# Read input. _1b e# Duplicate and get the ASCII sum by treating the character codes as base-1 digits. \, e# Swap with other copy and get its length. d/ e# Convert to float and divide. mo e# Round to nearest integer. c e# Convert to character. ``` [Answer] # Vitsy, 11 Bytes This was what this was *MADE* for. ``` IVzV1-\+V/O I Get the length of the input stack. V Save it as the final global variable, popping it. z Push the input stack to the program stack. V1-\ Repeat the next item global variable size - 1. + Add the top two items. This adds up everything. V/ Divide by the global variable. O Output as a character. ``` [Answer] # Pyth, 9 bytes ``` C.R.OCMz0 ``` [Try it online.](https://pyth.herokuapp.com/?code=C.R.OCMz0&input=8112015) [Answer] # Mathematica, 47 bytes ``` FromCharacterCode@Round@Mean@ToCharacterCode@#& ``` or using composition: ``` FromCharacterCode@*Round@*Mean@*ToCharacterCode ``` String handling in Mathematica is such a joy... [Answer] # K5, 16 bytes ``` {`c$.5+(+/x)%#x} ``` The phrase `{(+/x)%#x}` is a classic K idiom for calculating an arithmetic mean, and in K5 characters naturally coerce to numbers with no special work. ``c$.5+` handles rounding and converting the result back into a character. In action: ``` {`c$.5+(+/x)%#x}'("Hello, world!";"Code golf";"8112015") "Y]3" ``` [Answer] # [TeaScript](https://github.com/vihanb/TeaScript), 14 [bytes](https://en.m.wikipedia.org/wiki/ISO/IEC_8859) ``` ÇU(x¿lÅ)x¡/xn© ``` Probably can be golfed using a reduce ### Ungolfed ``` C(U(xs``.m(#lc())x()/xn)) C( // Char from code from... U( // Round xs`` // Split input .m(# // Map over input lc() // get char code ).x() // Sum up array /xn // Divided by input length ) ) ``` [Answer] # Python 3, 48 Bytes Straightforward solution with an anonymous lambda function. ``` lambda k:chr(int(round(sum(map(ord,k))/len(k)))) ``` [Answer] # Ruby, ~~46~~ 45 characters ``` ->s{'%c'%(s.bytes.reduce(0.0,:+)/s.size+0.5)} ``` Sample run: ``` 2.1.5 :001 > ->s{'%c'%(s.bytes.reduce(0.0,:+)/s.size+0.5)}['Hello, world!'] => "Y" 2.1.5 :002 > ->s{'%c'%(s.bytes.reduce(0.0,:+)/s.size+0.5)}['Code golf'] => "]" 2.1.5 :003 > ->s{'%c'%(s.bytes.reduce(0.0,:+)/s.size+0.5)}['8112015'] => "3" ``` [Answer] # Japt, ~~31~~ 27 bytes ``` Ua r(X$,$Y =>Xc +Yc)/Ul)r d ``` Try it in the [Stack Snippet interpreter](https://codegolf.stackexchange.com/a/62685/42545)! (Arrow functions require ES6-compliant browser, e.g. Firefox.) ### How it works ``` // Implicit: U = input string Ua // Split U into chars. r(X$,$Y => // Reduce the result by: Xc +Yc // summing the char codes. /Ul) // Divide the result by the original string's length. r d // Round the result and turn back into a character. // Implicit: output last expression ``` (Side note: `c` works as `.charCodeAt` on strings and `Math.ceil` on numbers. The first time reduce is run, it will be between two strings, so `Xc` is necessary, but has no effect on the rest of the reducing.) This is still much longer than it should be. The summing is 17 bytes when it could be 5 or so. Here's a 14-byte version I'd like to get working in the interpreter: ``` Uamc)r+ /Ul)rd Uamc) // Split input into chars, then replace each with its char code. r+ // Reduce the result with operator +. Equivalent to summing the array. /Ul) // Divide the sum by the original string's length. rd // Round and turn into a character. ``` [Answer] ## CoffeeScript, 94 bytes ``` f=(x)->String.fromCharCode Math.round x.split('').reduce(((p,v)->p+v.charCodeAt 0),0)/x.length ``` [Answer] # Ruby, 48 ``` ->s{t=0.0;s.bytes{|i|t+=i};(t/s.size).round.chr} ``` [Answer] ## PowerShell, 60 Bytes ``` param([char[]]$a)$a|%{$b+=[int]$_};[char][int]($b/$a.Length) ``` Nothing esoteric. Takes input string `param(..)` and casts it as a `char[]`. Iterates over that array `$a|%{..}`, and each iteration adds the int value of that character to our accumulator `$b`. Then takes the average, casts it as `int` (which does implicit rounding to the nearest integer), then casts as a `char` for output. Since that's left on the pipeline, output is implicit. [Answer] # Haskell, ~~74~~ 69 bytes ``` s x=toEnum$round$(fromIntegral.sum.map fromEnum$x)/(foldr(\_ y->y+1)0x) ``` Pretty straightforward. A good chunk of the length is due to the fact that we can't apply the floating-point division operator (/) to integral types and that besides we need to round so we can't take advantage of the integral division's truncating behaviour. *P.S. :* Shaved off 5 bytes by using a fold to avoid the second fromIntegral. Interestingly, replacing the dividend by a fold gives a *longer* program, probably because you need the fromIntegral there. ]
[Question] [ Given dimensions of a 2D array, except **1xn**, that results in an odd number of elements, find the midpoint index. Example: Input is **3x5**, representing the 2D array > > [0,0] [0,1] [0,2] [0,3] [0,4] > > > [1,0] [1,1] [1,2] [1,3] [1,4] > > > [2,0] [2,1] [2,2] [2,3] [2,4] > > > The midpoint index is **[1,2]** ### Input > > **3** > > > **5** > > > ### Output > > **1 , 2** > > > ### Rules * Standard code-golf rules, fewest bytes wins * Either full program or function is permitted * When input is either **1xn** or the corresponding array would have an even number of elements, *output must be* **[0,0]** * **nx1** should be treated like any other array [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~20~~ ~~19~~ ~~15~~ 13 bytes ``` ⌊÷∘2×2|×/×1≠⊃ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Dko56uw9sfdcwwOjzdqObwdP3D0w0fdS541NX8/3@agrGCqcKj3rkKeflFuYk5XGlAriFEQDepUtcQKGAIVWEIEsgDCphABVLLUvMU8kpzk1KLFPLTFIryy4u5QAaaYJNNzs8pzc0rBms3w6VdITEvBaYSAA "APL (Dyalog Classic) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 bytes My first (somewhat) serious Japt submission! Any help is appreciated, I think ~10 bytes or even less may be possible. Saved 4 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)! ``` £ÎÉ©Ueu)*Xz ``` [Try it here!](https://ethproductions.github.io/japt/?v=1.4.5&code=o87JqVVldSkqWHo=&input=WwpbMTcsMjldClsxNywxXQpbMSwxN10KWzMsNV0KWzMsNF0KXQotbVI=) ### How it works *Slightly outdated.* ``` £eu *UÎ>1 *Xz – Full program. £ – For each X of the input array. *Xz – Multiply floor(X/2) by the truth value of: eu – Are both numbers odd? And... *UÎ>1 – Is the initial element greater than 1? – Implicit output to STDOUT. ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 23 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous prefix function. Takes rows,columns as right argument. ``` {0::0 0⋄÷∘÷@0⌽¨⍨.5×⍵-1} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6sNrKwMFAwedbcc3v6oY8bh7Q4Gj3r2HlrxqHeFnunh6Y96t@oa1v5PA6p91NsH0dbVfGi98aO2iUBecJAzkAzx8Az@n6ZgrGCqoPCod65CXn5RbmIOVxqQbwgV0U2q1DUEihjC1BiCRPKAIiYwkdSy1DyFvNLcpNQihfw0haL88mIukKEmWKWT83NKc/OKwQaY4TRAITEvBawUpBYA "APL (Dyalog Unicode) – Try It Online") `{`…`}` "dfn"; `⍵` is right argument (rightmost letter of Greek alphabet).  `0::` if any error happens:   `0 0` return `[0,0]`  `⋄` now try:   `⍵-1` right argument minus 1   `.5×` multiply by a half   `⌽¨⍨` rotate each by itself (this errors on non-integers)   `÷∘÷@0` reciprocal of reciprocal at position 0 (this errors when the first coordinate is 0) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes Saved 1 byte thanks to *Mr. Xcoder* (remove `D`) ``` ¬≠*ÉP*;ï ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0JpHnQu0DncGaFkfXv//f7SxjoJpLAA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##MzBNTDJM/V9TVqns8v/QmkedC7QOdwZoWR9e/79S6fB@BV07hcP7lXT@GyuYcpkqGAOxIZchkG2kYMJlomAEpM25zIG0gYIBAA) **Explanation** ``` ¬≠* # multiply the input by its first value falsified ÉP* # multiply the input by the product of the results values' oddness ; # divide by 2 ï # convert to int ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~24~~ 16 bytes *-8 bytes saved thanks to @Shaggy* ``` Neu ©UÉ?Nmz :2ÆT ``` [Try it online!](https://tio.run/##y0osKPn/3y@1VOHQytDDnfZ@uVUKVkaH20L@/zc01zGyBAA "Japt – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~42~~ 39 bytes ``` {(^$^a X ^$^b)[$b-1&&$a*$b%2&&$a*$b/2]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1ojTiUuUSFCAUglaUarJOkaqqmpJGqpJKkaQRn6RrG1/4sTKxXSNAx1DDWtuWBsYzjbGEncWMcUzjZCYZtoWv8HAA "Perl 6 – Try It Online") Anonymous code block that returns a list of two integers. ### Explanation: ``` { } # Anonymous code block (^$^a X ^$^b) # Cross product of the two ranges, basically the flattened 2D array [ ] # Get the element at &&$a*$b/2 # Midpoint of the array $a*$b%2 # If the numbers are odd $b-1&& # And the second element is not 1 # Else the 0th element, which is 0,0 ``` [Answer] # JavaScript (ES6), 31 bytes *Saved 1 byte thanks to @Neil* Takes the dimensions in currying syntax `(w)(h)`. ``` w=>h=>w&h&w>1?[h>>1,w>>1]:[0,0] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/c1i7D1q5cLUOt3M7QPjrDzs5QpxxIxFpFG@gYxP5Pzs8rzs9J1cvJT9dI0zDV1DDW1ORCFTTW1DDEEASqNMEQNNTUMMImCDTzPwA "JavaScript (Node.js) – Try It Online") --- # Original version, 32 bytes Takes the dimensions in currying syntax `(w)(h)`. ``` w=>h=>w*h&!!--w?[h>>1,w/2]:[0,0] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/c1i7D1q5cLUNNUVFXt9w@OsPOzlCnXN8o1iraQMcg9n9yfl5xfk6qXk5@ukaahqmmhrGmJheqoLGmhiGGIFClCYagoaaGETZBoJn/AQ "JavaScript (Node.js) – Try It Online") ### How? We want to test whether both \$w\$ and \$h\$ are odd, which is true if and only if \$w\times h\$ is odd. We also want to make sure that \$w\$ is not equal to \$1\$, which means that \$w-1\$ is not equal to \$0\$. We can merge both tests into: ``` w * h & !!--w ``` If this test passes, we know that \$w\$ was odd and is now even (since it was decremented), so we can divide it by \$2\$ with a standard division. For \$h\$, we use a bitwise shift instead because it's still odd. [Answer] # [Haskell](https://www.haskell.org/), 46 42 bytes ``` x%y|odd$x*y,x>1=(`div`2)<$>[x,y]|1<2=[0,0] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v0K1siY/JUWlQqtSp8LO0FYjISWzLMFI00bFLrpCpzK2xtDGyDbaQMcg9n9uYmaegq1CSj6XgkKFgo2uQnpqiU9mXiqQW4nKLSjKzCtRUFHQKEpNTAGqtbJS8Mwr0VRQhYpUwkX@G3OZAgA "Haskell – Try It Online") *EDIT: -4 bytes thanks to a trick from [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s answer.* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) This confused me :p ``` :2×Ḃ_ỊḢ$PƲ ``` A monadic link accepting a list of the dimensions returning a list of the middle-indices or `[0,0]` in the special-cases. **[Try it online!](https://tio.run/##ASIA3f9qZWxsef//OjLDl@G4gl/hu4rhuKIkUMay////WzEsMTld "Jelly – Try It Online")** ### How? ``` :2×Ḃ_ỊḢ$PƲ - Link: list of dimension lengths e.g. [19,12] or [19,13] or [1,19] or [19,1] :2 - integer divide by two (gets middle indices) [9,6] [9,6] [0,9] [9,0] Ʋ - last four links as a monad: Ḃ - bit (n%2) (of the input) [1,0] [1,1] [1,1] [1,1] $ - last two links as a monad (of the input): Ị - insignificant? (abs(n)<=1) [0,0] [0,0] [1,0] [0,1] Ḣ - head 0 0 1 0 _ - subtract (vectorises) [1,0] [1,1] [0,0] [1,1] P - product 0 1 0 1 × - multiply (vectorises) [0,0] [9,6] [0,0] [9,0] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes *Ugh. Waaaaaaaay too long!* ``` :2×ḂẠ$×Ḣn1Ɗ ``` [Try it online!](https://tio.run/##y0rNyan8/9/K6PD0hzuaHu5aoAJiLMozPNb1/3D7o6Y1//9HRxvqmBrG6kQb6ZgASWMdUyBpqmMMJA3NdAxBMoaWOobGsbEA "Jelly – Try It Online") ### Alternative, 11 bytes ``` ḷ/>1×ḂẠ$×:2 ``` [Try it online!](https://tio.run/##y0rNyan8///hju36doaHpz/c0fRw1wKVw9OtjP4fbn/UtOb//@hoQx1Tw1idaCMdEyBprGMKJE11jIGkoZmOIUjG0FLH0Dg2FgA "Jelly – Try It Online") [Answer] # [Julia 0.6](http://julialang.org/), 28 27 bytes ``` x\y=x&y&1&(x>1)*[x÷2,y÷2] ``` [Try it online!](https://tio.run/##FcmxDYAgEEDRVajInTmLA9FKpqBDCkqNGmM0gckcwMEQm/eLv9zrHPtS0pTHJLNkCckyNj69j6JcCWWLB7jWHue8X@sOznOYnFcBSYAAJsNIoKirajJVQ7rKPfF/ePiLKMoH "Julia 0.6 – Try It Online") *(-1 byte thanks to Jo King.)* Explanation: `x\y` - define an operator instead of a function, to save bytes `x&y&1` - check that both inputs are odd. `&(x>1)` - and that the first input is not 1 `*` - the result of the above checks is 0 or 1, multiply that with: `[x÷2,y÷2]` - `÷` is integer division, so here for odd numbers gives `(n-1)/2` i.e. the middle index. So this forms a vector of the two middle indices (which might be made `[0, 0]` if any of the previous checks fail). [Answer] # [Lua](https://www.lua.org), 77 bytes ``` x,y=...f=math.floor print((x%2==1 and y%2==1)and f(x/2)..","..f(y/2)or "0,0") ``` [Try it online!](https://tio.run/##yylN/P@/QqfSVk9PL802N7EkQy8tJz@/SKGgKDOvREOjQtXI1tZQITEvRaESzNQEMdM0KvSNNPX0lHSUgNo0KoEcoBYlAx0DJc3///@b/7f8DwA "Lua – Try It Online") not the smallest language but submission for practicing :) [Answer] # [Rust](https://www.rust-lang.org/), 42 bytes ``` |w,h|if w>1&&w*h%2>0{(w/2,h/2)}else{(0,0)} ``` [Try it online!](https://tio.run/##jczRCoMgGIbh813Fv2Ch44fUrZNi7VoGMxTMohwemNfu2hg7ze/4/Z75tbjUWxge2hIK4QDbjHQw6Oc0auvgllaPatU9@I6XpT@rk@hYIL4SqCpBozSLDIQhozF93u3XmObtbOyRFKG5xwL/IOEINaV7lUAQWVWGdUG4ZlV5Ft@v6p8V0xs "Rust – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~38~~ ~~29~~ 28 bytes An extra byte removed thanks to @Guiseppe ``` (i=scan()-1)/2*!any(i%%2,!i) ``` [Try it online!](https://tio.run/##K/r/XyPTtjg5MU9DU9dQU99ISzExr1IjU1XVSEcxU/O/oYLpfwA "R – Try It Online") Get the input, subtract 1 store in `i` and divide by 2 and multiply by not any evens or 0's in `i` [Answer] # [Python 2](https://docs.python.org/2/), 39 bytes -2 bytes thanks to ovs ``` lambda a,b:[0,a/2,0,b/2][a>1==a*b%2::2] ``` [Try it online!](https://tio.run/##K6gsycjPM/rvYxvzPycxNyklUSFRJ8kq2kAnUd9Ix0AnSd8oNjrRztDWNlErSdXIysoo9n9BUWZeiYKPhqGOpaUmF4xnrGOI4Jgjc4x1TJE5JgiOEVDmPwA "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~43~~ 41 bytes ``` lambda a,b:((0,0),(a/2,b/2))[a*b%2*(a>1)] ``` [Try it online!](https://tio.run/##FcpBCoMwEIXhqwyFwkQHzMTagqAXSQOZUEKFNoq4SE@fxs33L97bfsd7TabE6Vk@8g0vAaEwImrSilA6Q6EzSllpwtU0KDMrV@K6Q4YlATINXH@GbtWehupAfZXvxOfCj7Pjti/pAJ89tHCBaa604CNmqx1ly0758gc "Python 2 – Try It Online") No rocket science here. -2 with thanks to @MrXcoder and @Emigna ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 8 years ago. [Improve this question](/posts/8529/edit) I am back with a brand new puzzle for C/C++ addicts. Following the feedback received on the 1st puzzle, this time I will try to make the requirements crystal clear and to provide a perfectly valid code. Here is the problem. Given the following code: ``` #include <iostream> char message[6]="hello"; void print_hello_message() { std::cout << message; } int main() { char* q = &message[0]; // insert your code here } ``` You are required to insert two more lines where the comment specifies in order to make the program print "hello" and nothing more, with the following restrictions: 1. the first line will NOT call any function, including cout 2. the second line will contain AT MOST 5 letters (and as many other symbols as you want) 3. the first line may contain new variable declarations but may not initialize them 4. the symbols # and / will not be used at all. 5. no logical operators will be used The shortest code wins! [Answer] In thinking about it some more, the problem states "insert two more **lines** where the comment specifies" not "**statements**". Taking that into consideration, here is another shorter answer (though it depends on how you define "the first line will NOT call any function, including cout"): ``` std:: cout<<q; ``` The first line qualifies which cout will be used, and the second line includes the actual operator that results in calling operator<< for the std::ostream & const char\* operands. [Answer] If I understand what you're asking for, this is what I'd add: ``` using std::cout; cout<<q; ``` The first line brings std::cout into the current name space so that we can use it without qualification. `using namespace std;` would have worked as well but is longer so I didn't use it. The second line uses the limit of five letters (plus three symbols and no necessary white space beyond whatever the platform uses to denote end of line). There may be something shorter, but I can't think of it at the moment. [Answer] Use `q` to store a pointer to `print_hello_message`, then cast it back to a function pointer and invoke it. ``` q = (char *) &print_hello_message; (*(void(*)())q)(); ``` Short version: ``` q=(char*)print_hello_message; (*(void(*)())q)(); ``` ]
[Question] [ You are given 4 positive integers: volume of the first container (`v1`), volume of the second container (`v2`), volume of the liquid in the first container (`l1`), and volume of the liquid in the second container (`l2`). Your task is to move some of the liquid from container 1 to container 2, making the amount of empty space in the containers equal to each other, outputting how much liquid should be moved. ## An example Here is an example of some possible input (formatted for the ease of test cases. The input isn't formatted.): ``` 8 11 6 5 ``` Here, you need to make sure that the differences between the volumes and the containers are equal. Currently the difference is not equal: ``` 8 11 - 6 5 ====== 6 2 ``` So we need to try to make them equal, by taking some of the values in one container to another container: ``` 8 11 - 4 7 ====== 4 4 ``` After you have succeeded, output how much liquid you need to take from container 1 to container 2. Therefore the above example should output `2`. ## Test cases ``` 15 16 9 2 ``` We move into this state: ``` 15 16 - 5 6 ====== 10 10 ``` Therefore `4` is the expected result. ## Test case #2 ``` 16 12 13 1 ``` We move into this state: ``` 16 12 - 9 5 ====== 7 7 ``` Therefore `4` is the expected output. ## Test case #3 ``` 20 12 10 2 ``` Moved: ``` 20 12 -10 2 ====== 10 10 ``` Therefore `0` is the expected output. ## More test cases (They don't have explanations as this should be quite clear) ``` 12 5 9 0 -> 1 9 11 7 3 -> 3 ``` ## Rules * The test cases will be made so that the result is always possible as a positive integer. The result will **never** be a decimal. * Input can be taken in any convenient and reasonable format. * Output can be given in any convenient and reasonable format. * The input string will be made so that a moving is always possible without involving decimals or negative numbers. Also there will not be more liquid than how much a container can hold. * Of course, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer in each language consisting of the fewest number of bytes wins. Happy golfing! * An extra restriction for the test cases: you can assume that there is always going to be space available in the second container. So a test case like this: ``` 10 2 2 2 ``` is not going to be a valid testcase. [Answer] # JavaScript (ES6) / C#, 21 bytes ``` (v,V,q,Q)=>V-Q-v+q>>1 ``` [Try it online!](https://tio.run/##ZckxCoAgGAbQvZMofYa/UNSgd2hpj9IoQivD6xuN0VvfNqYxTtd63MKH2WanM0sYcKLn2gyiF6k8jaE8BR/Dbqs9LMyxFkRoUHNefINqUIMO6jdKghRIvpUf "JavaScript (Node.js) – Try It Online") (JS) [Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXooOMFYCEnUKagu1/jTKdMJ1CnUBNW7sw3UDdMu1COzvD/9Zc4UWZJak@mXmpGmkaFjqGhjpmOqaamqjihqY6hmY6ljpG6BJGBjqGRjqGBmCZ/wA "C# (Visual C# Interactive Compiler) – Try It Online") (C#) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` ®β; ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0Lpzm6z//4821VEwBGEzHQWzWAA "05AB1E – Try It Online") Input is an array of volumes in the order [first liquid, first container, second container, second liquid]. Alternative 3-byter: ``` ÆÆ; ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cNvhNuv//6OjDU11FExjdRSiDc10FMxiYwE "05AB1E – Try It Online") Input is a nested array: [[first container, first liquid], [second container, second liquid]]. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ISH ``` [Try it online!](https://tio.run/##y0rNyan8/98z2OP/w537rB81zFHQtVN41DDX@nA71@H2R01rIv//j@aKjjbSMTSL1Yk2NNWxjI3VAQoY6hgagwTMdAyNICJGIJZOtJGBjqFBbCxXLAA "Jelly – Try It Online") A monadic link taking as its argument `[[l1, v1], [v2, l2]]` and returning the volume needed to move. A relatively rare ASCII-only Jelly answer! ## Explanation ``` I | Increments S | Sum H | Half ``` [Answer] # [Keg](https://github.com/JonoCode9374/Keg), ~~14~~ 13 bytes ``` -±¿-¿+½:0<[±] ``` [Try it online!](https://tio.run/##y05N////0P5D@3XBSPvQXisDm@hDG2P//7fgMuMyNOQyBQA "Keg – Try It Online") A port of Arnauld's original javascript answer. Takes input in form of: ``` volume1 container1 volume2 container2 ``` *-1 byte by utilising implicit input correctly.* [Answer] # [~~Perl 6~~ Raku](https://github.com/nxadm/rakudo-pkg), ~~12~~ 11 bytes ``` (*-*-*+*)/2 ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfQ0sXCLW1NPWN/ltz5SYWKFQXJ1YqpCnUqMTX6kSb6ZjqWOgYGlpb6hjpGJrqGJpZGxrrGAJpHUMja0MDoKiRAYgZa/0fAA "Perl 6 – Try It Online") Edit: I realized that I could take the parameters in any order. Four parameters are: liquid in container 1, liquid in container 2, volume of container 1, volume of container 2. [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 79 bytes ``` [S S S N _Push_0][S N S _Dupe_0][T N T T _Read_STDIN_as_integer][T T T _Retrieve_input_vol1][S N S _Dupe_input_vol1][S N S _Dupe_input_vol1][T N T T _Read_STDIN_as_integer][T T T _Retrieve_input_liq1][T S S T _Subtract_vol1-liq1][S N S _Dupe_vol1-liq1][S N S _Dupe_vol1-liq1][T N T T _Read_STDIN_as_integer][T T T _Retrieve_input_vol2][S N S _Dupe_input_vol2][S N S _Dupe_input_vol2][T N T T _Read_STDIN_as_integer][T T T _Retrieve_input_liq2][T S S T _Subtract_vol2-liq2][T S S T _Subtract_(vol1-liq1)-(vol2-liq2)][S S S T S N _Push_2][T S T S _Integer_divide_((vol1-liq1)-(vol2-liq2))/2][T N S T _Print_as_integer] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIObk4QQDIQnA4FRRQBTBkwSrAqjiBBCdQ7v9/Q0MuUy4LLjMA) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** ``` Integer vol1 = STDIN as integer Integer liq1 = STDIN as integer Integer vol2 = STDIN as integer Integer liq2 = STDIN as integer Integer diff1 = vol1 - liq1 Integer diff2 = vol2 - liq2 Integer diffOfDiff = diff1 - diff2 Integer result = diffOfDiff / 2 Print result as integer to STDOUT ``` Since the integers are guaranteed to be positive, it uses them as heap-address for the next input in line with some duplicates, saving bytes. [Answer] # Excel, 16 bytes ``` =(B1-D1-A1+C1)/2 ``` Same approach as others [Answer] # Java 8 / CoffeeScript 2, ~~22~~ 21 bytes ``` (V,v,L,l)->v-l-V+L>>1 ``` Port of [*@Grimmy*'s second 05AB1E answer](https://codegolf.stackexchange.com/a/198100/52210). -1 byte by porting @Arnauld's approach, golfing the `(...)/2` I had to `...>>1`. [Try it online in Java 8.](https://tio.run/##dZCxasMwFEX3fMVDk4yeTeQS0xLqJaubJeCldFBltyhVlBApglKy9gP6if0RV1JESYcuF3Q4cK/eVnhRboe3SWphLTwIZT5mAMq48fgi5Ajr@EwAJI3ZY0yfskupi2VwzrMQ1gmnJKzBwD1MtEePHeqibH2py551bcunZRQPp2cdxOz7vRpgF7rpxh2VeX18AlFcit1oHb1FzrHBRSrKjC@QN3iH9R/YIK@R3yC/pvU80Xl2r5em5iT997fLjM27deOu2p9cdQgLnTaUrDj1hPWMIGjCOkYKEGaAVR2xz1hH/P35BYSZSv5eJA85Tz8) [Try it online in CoffeeScript 2.](https://tio.run/##ZckxCoAgGAbQvZMofYa/oNSQJ3D2AqIRSEaG1zcao7e@UFKKsYZrP2/V09qZR4ND5sI2kYUfnbXUQzlqyXHKZWOJzSCCgeZ8@AZpkMEC9RslQQok3@oP) **Explanation:** ``` (V,v,L,l)-> // Method with four integer parameters and integer return-type v-l // Calculate the difference between the volume and liquid of container 1 -V+L // Subtract the difference between the volume and liquid of container 2 >>1 // Divide that result by 2 (by bit-shifting once towards the right) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~27~~ ~~26~~ 25 bytes Saved a bytes thanks to [meetaig](https://codegolf.stackexchange.com/users/59449/meetaig)!!! ``` lambda a,b,c,d:b-d-a+c>>1 ``` [Try it online!](https://tio.run/##XcqxCoMwFEbh3ae4o7a/kBsxWKF5kdQhMQQFjSJZ@vQpOAj1jB9n/6Zpi00O709e7Oq8JQuHEb53ta/tc9Sac9gOSjRHMqYDMxTaAQVdGW7BCi/IGyuwBDfgf5fidHH7h76g/ZhjKkP5SFWVfw "Python 3 – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), ~~29~~ 28 bytes Saved a bytes thanks to [meetaig](https://codegolf.stackexchange.com/users/59449/meetaig)!!! ``` #define f(a,b,c,d)b-d-a+c>>1 ``` [Try it online!](https://tio.run/##ZY3LCsIwFET3/YpQERKcQG@0QSn2S9ykeUhBg4S6Er89igh9zfLMHMZKezPxmvPG@dBHzwI36GDhRCedNDvbtpTvpo9cvAr2zSP1cQi8DPwIImjUgp3Z1l1iCTaBolnMqQZpnKBm@5GuBQ1SoD1obox4pajq11WLkwn@K8kPzxTZQTXFO38A "C (clang) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~39~~ 25 bytes ``` f(a,b,c,d){a=b-d-a+c>>1;} ``` Wrote a testing framework for possible future testcases. Takes as input 4 integers: * `a`: capacity of first container * `b`: capacity of second container * `c`: amount of liquid in first container * `d`: amount of liquid in second container Explanation: ``` f(a,b,c,d) ``` Function implicitly returning `int` with four arguments of type `int`. ``` a= ``` A sort of `return` that exploits GCC's code generation when compiling without optimization. ``` b-d-a+c>>1 ``` The main algorithm. There's several steps involved here: * `b-d`: Subtract the amount of liquid in the second container from the capacity in the second container to get the free space in the second container. * `-a+c`: Subtract the capacity of the first container and add back the amount of liquid in the second container to get the total free space in both. * `>>1` After that, divide the amount of free space in both by 2 to get the amount of liquid to move from container one to container two. This is a binary right shift and binary is base 2, so it is equivalent to division by 2 but removes the need for parentheses as the operator precedence of `>>` is lower than that of `+` and `-`. The operator precedence for `/` is higher than that of `+` and `-` so it would require extra parentheses. [Try it online!](https://tio.run/##jZPdToMwFMfveYqzmSUgnVLYNMrYU@wOuWC0aJMJC1RjJDw7HiqfY8vWUFL@/bXnk2j5HkVVFesh2ZOIMKMIvf2SLUMz2m6pW1Z3IokOX4zDJpdMpA8fW62Xwjznmaw1TSQSPkOR6N@pYIZWaICjFiXPZRTmPPcDfxWAB0UBdE2APhF4IWBDSRR7fhSKozZOB@c12LYa2LrlZgTXygnrGooMpQSeCThQlm4XHP858khy5qvAYEXqp/ZBga6mwP8s6bn45Wmsd/kw4BEa7X4get7QkwZo7QzPdJrR2InTTB@lHH2y3P62Tt7cdO2Zk6YJhlKLbk/Zs9BSX@d2FfhWME6rpBdAegraF0D7FHQugE7gjnzMuEQS04/VkVgeicWXziDIY4ZYrM93C/aK3IIR6CeWRa3a5KjPt2Q@6ZrWgenGyO5kG92baF1zdVEN3BWxXoc0885hHVWM7oybGPFP5llGYL5rO2LBIA7FgbNZHVTfKSbQgc1S@3@X1R8 "C (gcc) – Try It Online") [Answer] # AWK, ~~21~~ 20 bytes ``` 1,$0=($2-$4-$1+$3)/2 ``` [Try it online!](https://tio.run/##BcGxDYAwEAPAPlO4cAGCiLchERQMQ50BMv5z982RqZ3xLnTlVamN53o484aEjlbUoI4HLg7IUMA/ "AWK – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 19 bytes ``` \d+;? $* +`1,1 , 11 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZF29qeS0WLSzvBUMeQS4fL0PD/fwsdQ0NrMx1TLkNTHUtrQzMdIy4gYWhsbWgEVGNkoGNoAGIaAQA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \d+;? $* ``` Convert to unary and sum the middle two numbers. ``` +`1,1 , ``` Subtract the outer numbers from that sum. ``` 11 ``` Divide by 2 and convert to decimal. [Answer] # TI-BASIC, ~~26~~ 21 bytes ``` Prompt A,B,C,D:.5abs(A-C-B+D ``` Input is a series of prompts for each value. A = volume1 B = volume2 C = liquid1 D = liquid2 Output is the amount of liquid that needs to be moved from the fuller container to the emptier one. **Explantion:** ``` Prompt A,B,C,D ;Prompt the user to input the values .5abs(A-C-B+D ;Compute the amount of liquid needed, convert it ; to a positive number if need be and leave the ; result in Ans ;Implicit print of Ans ``` **Examples:** ``` prgmCDGF21 A=?15 B=?16 C=?9 D=?2 4 prgmCDGF21 A=?11 B=?10 C=?6 D=?7 1 ``` **Note:** TI-BASIC is a tokenized language. Character count does *not* equal byte count. [Answer] # Brainf\*ck, 39 bytes [Try it online!](https://tio.run/##SypKzMxLK03O/v9fxw4IbaJ17bRtYkGUna6NTaydDpClC6SjdcESdnr//1dVVRkAAA) ``` ,>,>,<[->+<]<[->>-<<]>,[->-<]>[-->+<]>. ``` The input/output are the ASCII values of characters. Using "aaz0" gives "%" as output, as it corresponds to the case ``` 97 122 97 48 ``` which is solved by moving 37 units of liquid, the % symbol. Could shave a couple of bytes if the input order could be rearranged, but not sure if that would be acceptable. [Answer] # [J-uby](https://github.com/cyoce/J-uby), 18 bytes Port of [Nick Kennedy's Jelly answer](https://codegolf.stackexchange.com/a/198110/11261). Takes input in format `[[v1, l1], [l2, v2]]`. ``` (:<<&:-)**:+|~:/&2 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY1LToRAEIbjllNUoiGAQE-TEZXM6I5Er0DIhEfBtAGa0I1h4uMibtjMBbyNnkYeE8wsuqvq67--_jq-7Nr40P9eXF2CYQCvsYkkb6DBkr9iCqyC23WENE5A20tZC4-QnMl9G9sJL0ly4AmSZ2twECZEi4K4ulLytC0Q_LZKFIAUs1GtVfowALAMKpuJXfSoPVUSc2xmDmA9aJ3-dhpgSElWooCULwiggy0kUVEMyYVilS59d-o-poqFwH-5ETW5OPtgRnYZ1ZoqsMh0_Xx9Eo_3eBR_e2xlZt19a95mo3qWbhje9funR1RnfvjxavCDgLqmE5rBvUlvwlCZ0dqkA6KOSd2FOVOMrkxnFYazoe_n-gc) ## Explanation ``` (:<< & :-) ** :+ | ~:/ & 2 ( ) ** # Map arguments with... :<< & :- # Splat pair of elements onto :- (subtract) :+ | # Add, then ~:/ & 2 # Divide by 2 ``` ``` ]
[Question] [ ## Introduction: We all know these three basic arithmetic math tables I assume. ``` ADDITION: + | 1 2 3 4 5 6 7 8 9 10 ---------------------------------- 1 | 2 3 4 5 6 7 8 9 10 11 2 | 3 4 5 6 7 8 9 10 11 12 3 | 4 5 6 7 8 9 10 11 12 13 4 | 5 6 7 8 9 10 11 12 13 14 5 | 6 7 8 9 10 11 12 13 14 15 6 | 7 8 9 10 11 12 13 14 15 16 7 | 8 9 10 11 12 13 14 15 16 17 8 | 9 10 11 12 13 14 15 16 17 18 9 | 10 11 12 13 14 15 16 17 18 19 10 | 11 12 13 14 15 16 17 18 19 20 SUBTRACTION: - | 1 2 3 4 5 6 7 8 9 10 --------------------------------- 1 | 0 1 2 3 4 5 6 7 8 9 2 | -1 0 1 2 3 4 5 6 7 8 3 | -2 -1 0 1 2 3 4 5 6 7 4 | -3 -2 -1 0 1 2 3 4 5 6 5 | -4 -3 -2 -1 0 1 2 3 4 5 6 | -5 -4 -3 -2 -1 0 1 2 3 4 7 | -6 -5 -4 -3 -2 -1 0 1 2 3 8 | -7 -6 -5 -4 -3 -2 -1 0 1 2 9 | -8 -7 -6 -5 -4 -3 -2 -1 0 1 10 | -9 -8 -7 -6 -5 -4 -3 -2 -1 0 MULTIPLICATION: * | 1 2 3 4 5 6 7 8 9 10 ---------------------------------- 1 | 1 2 3 4 5 6 7 8 9 10 2 | 2 4 6 8 10 12 14 16 18 20 3 | 3 6 9 12 15 18 21 24 27 30 4 | 4 8 12 16 20 24 28 32 36 40 5 | 5 10 15 20 25 30 35 40 45 50 6 | 6 12 18 24 30 36 42 48 54 60 7 | 7 14 21 28 35 42 49 56 63 70 8 | 8 16 24 32 40 48 56 64 72 80 9 | 9 18 27 36 45 54 63 72 81 90 10 | 10 20 30 40 50 60 70 80 90 100 For the sake of this challenge, division is excluded. ``` ## Sequence definition: We will follow the same steps for both a 0-indexed and 1-indexed sequence. So the resulting sequence will become `f(0)+g(1)`, `f(1)+g(2)`, etc. * Both `f` (0-indexed) and `g` (1-indexed) start in the ADDITION table at `(1,1)`. So `f(0) = 1+1 = 2` and `g(1) = 1+1 = 2`. * We then go to the SUBTRACTION table, and we either go `n` steps down if `n` is odd, or `n` steps to the right if `n` is even. So `f(1) = 1-2 = -1` (it went to the down, because `n=1` is odd); and `g(2) = 3-1 = 2` (it went right, because `n=2` is even). * Then we go to the MULTIPLICATION table, and do the same: `f(2) = 3*2 = 6` and `g(3) = 3*4 = 12`. * And then we go back to the ADDITION table again. Also, when we go beyond the borders of the 10x10 table, we wrap around from the bottom to the top, or from the right to the left. So going from `(7,9)` six steps right, will end up at `(3,9)`. The resulting sequence will be `f(n)+g(n+1)` (with `n` being 0-indexed). Here the first six in colors, in the order green → blue → purple → grey → red → orange: `f` (0-indexed): `(1+1) → (1-2) → (3*2) → (3+5) → (7-5) → (7*10)` [![enter image description here](https://i.stack.imgur.com/xwS3D.png)](https://i.stack.imgur.com/xwS3D.png) `g` (1-indexed): `(1+1) → (3-1) → (3*4) → (7+4) → (7-9) → (3*9)` [![enter image description here](https://i.stack.imgur.com/rHuJN.png)](https://i.stack.imgur.com/rHuJN.png) The resulting sequence is the sum of both these sequences. Here are the first 100 items of the 0-indexed sequence `f`: ``` 2,-1,6,8,2,70,13,-4,7,7,-5,7,10,-7,70,12,-2,6,3,0,1,3,1,15,12,-3,30,10,-6,6,7,-6,21,13,-3,35,8,1,2,2,0,2,5,-2,35,17,-7,21,8,-5,6,8,-4,30,17,2,15,5,-1,1,2,-1,6,8,2,70,13,-4,7,7,-5,7,10,-7,70,12,-2,6,3,0,1,3,1,15,12,-3,30,10,-6,6,7,-6,21,13,-3,35,8,1,2,2 ``` Here are the first 100 items of the 1-indexed sequence `g`: ``` 2,2,12,11,-2,27,9,-5,5,6,-5,18,12,-2,28,7,2,1,11,-9,1,4,-1,28,16,-6,18,7,-4,5,7,-3,27,16,3,12,4,0,10,11,0,3,7,3,63,12,-3,6,6,-4,6,9,-6,63,11,-1,3,2,-9,10,2,2,12,11,-2,27,9,-5,5,6,-5,18,12,-2,28,7,2,1,11,-9,1,4,-1,28,16,-6,18,7,-4,5,7,-3,27,16,3,12,4,0,10,11 ``` Here are the first 100 items of the result sequence: ``` 4,1,18,19,0,97,22,-9,12,13,-10,25,22,-9,98,19,0,7,14,-9,2,7,0,43,28,-9,48,17,-10,11,14,-9,48,29,0,47,12,1,12,13,0,5,12,1,98,29,-10,27,14,-9,12,17,-10,93,28,1,18,7,-10,11,4,1,18,19,0,97,22,-9,12,13,-10,25,22,-9,98,19,0,7,14,-9,2,7,0,43,28,-9,48,17,-10,11,14,-9,48,29,0,47,12,1,12,13 ``` ## Challenge: Given an integer `n`, output the `n`'th number of the above result sequence (which sums both the 0-indexed and 1-indexed sequences). So calculate `h(n) = f(n)+g(n+1)`. ## Challenge rules: * The result-sequence is always 0-indexed. I know some languages are 1-indexed by default, in which case you'll have to do `n-1` right after entering the function/program so `f(n)+g(n+1)` will start at `f(0)+g(1)` (and not `f(1)+g(2)`). * Output can be in any reasonable format, so a String or decimal with `.0` instead of an integer is allowed. * As you may or may not have noted; in the tables above the number at the top is taken first, then the number at the left. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code. * Also, please add an explanation if necessary. ## Test cases (0-indexed): ``` 0 4 1 1 2 18 3 19 4 0 5 97 10 -10 50 12 60 4 61 1 62 18 63 19 100 0 111 17 1000 0 1994 98 2497 1 2498 12 2499 13 2500 0 ``` ***Note/tip:*** The sequences are self-repeating every 60 items. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 77 bytes Full program which prompts for `n`, looks up the result in the list of 60 possible results, and prints that to STDOUT. ``` ¯50+⎕AV⍳'63DE2èHy£¢xKHyéE29∆y492ýNyÂCx$∆yÂO2Á£3£¢27£3éOxM∆y£CxäN3D9x$'[60|⎕] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862p0SizOTi/8fWm9qoA2UcAx71LtZ3czYxdXo8AqPykOLDy2q8PaoPLzS1cjyUUdbpYml0eG9fpWHm5wrVED8w03@RocbDy02Bqk0MgcyDq/0r/AFSR1a7FxxeImfsYtlhYp6tJlBDdD42P9AK/8rgAHEZi4DBUMFIwVjBRMFUwVDAwVTAwUzIDJUMDNSMDMGigDlDQ1BNJBhaWmiYGRiaQ4iLECEpYKRqYEBAA "APL (Dyalog Unicode) – Try It Online") `'`…`'[`…`]` index the string by the following:  `⎕` prompt for `n`  `60|` remainder when dividing by 60 `⎕AV⍳` find **ɩ**ndices in the **A**tomic **V**ector (the character set) `¯50+` add negative fifty [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~48~~ ~~47~~ ~~43~~ 42 bytes 1-indexed. ``` ¾4×SsFD2äεT%>`…+-*Nè.V}Os0NÌ‚ÂTS-‚Nƒí}˜+}\ ``` [Try it online!](https://tio.run/##AUUAuv8wNWFiMWX//8K@NMOXU3NGRDLDpM61VCU@YOKApistKk7DqC5WfU9zME7DjOKAmsOCVFMt4oCaTsaSw619y5wrfVz//zg "05AB1E – Try It Online") or see the [Whole sequence](https://tio.run/##AUgAt/8wNWFiMWX//8K@NMOXU3NGRDLDpM61VCU@YOKApistKk7DqC5WfU9zME7DjOKAmsOCVFMt4oCaTsaSw619y5wrfVz/Kf8xMDA) **Explanation** ``` ¾4×S # initialize stack with [0,0,0,0] sF } # for N in range [0 ... input-1] do: D # duplicate 2äε } # for each pair of values T%> # get last digit of each and increment …+-*Nè # index into "+-*" with N ` .V # apply the function to our values O # sum the pair s # swap the list of 4 values to the top 0NÌ‚ # push [0, N+2] ÂTS- # bifurcate and subtract [1,0] ‚ # pair, resulting in [[0,N+2],[N+1,0]] Nƒí} # reverse each pair N+1 times ˜+ # flatten and add to the list of values from last iteration \ # discard the final list ``` [Answer] # [Python 3](https://docs.python.org/3/), 89 bytes ``` lambda i:ord('HEVWD¥Z;PQ:]Z;¦WDKR;FKDo`;tU:OR;taDsPEPQDIPE¦a:_R;PU:¡`EVK:O'[i%60])-68 ``` [Try it online!](https://tio.run/##HYvBCoJAGITvPcV/iRQ2WFO33KXbGoUHN0GDSmojpIVyxbz0OB3yQXwxWz3Mx/wz/1Sf5qFLty/W5/4pX7e7BEV1fbdm2zA78O53ZGJP8yPr2gOPEraJuL6yJqVxwhrJ3yIUe74TYddKekmYSGn3vYZZROPZSU0Jzu05WfWFrkGBKuGEETgIFghcBB4C35wm8o3IINMRUxJ3yIdfxxndYIPADBZesBy5GhkY@hjndAJQ1apsLIWgsJRt938 "Python 3 – Try It Online") [Answer] # JavaScript (ES6), ~~95~~ ... ~~84~~ 82 bytes This is the best I could come up with so far without hardcoding the sequence. *Edit: Now probably shorter than hardcoding anyway.* ``` m=>(g=(x,y=n=1)=>n>m?[x*y,x+y,n+o--&1?y-x:x-y][n%3]:g((y-o+n++)%10+1,x))(o=1)+g(1) ``` ### Demo ``` let f = m=>(g=(x,y=n=1)=>n>m?[x*y,x+y,n+o--&1?y-x:x-y][n%3]:g((y-o+n++)%10+1,x))(o=1)+g(1) ;[0, 1, 2, 3, 4, 5, 10, 50, 60, 61, 62, 63, 100, 111, 1000] .forEach(i => { console.log(`a(${i}) = ${f(i)}`) }); ``` ### Formatted and commented ``` m => ( // m = input g = ( // g = recursive function using: x, y = n = 1 // (x,y) = coordinates, n = counter ) => // and o = offset (0 or 1) n > m ? // if n is greater than the input: [ // evaluate the current cell in the current table x * y, // both multiplication x + y, // and addition are commutative n + o-- & 1 ? y - x : x - y // but subtraction is not: we need to make sure that ][n % 3] // x and y are set in the correct order : // else: g( // do a recursive call to g(): (y - o + n++) % 10 + 1, // updating y and using it as x; incrementing n x // using x as y ) // end of recursive call )(o = 1) + g(1) // invoke g() with o = 1; then o = 0; return the sum ``` [Answer] # Excel, 188 bytes Hardcoded results: ``` =CHOOSE(MOD(A1,60)+1,5,2,19,20,1,98,23,-8,13,14,-9,26,23,-8,99,20,1,8,15,-8,3,8,1,44,29,-8,49,18,-9,12,15,-8,49,30,1,48,13,2,13,14,1,6,13,2,99,30,-9,28,15,-8,13,18,-9,94,29,2,19,8,-9,12)-1 ``` Saved 3 bytes by adding 1 to all results in lookup, then subtracting at end. This turns `-10` into `-9` 5 times. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 81 bytes (UTF-8) ``` 'HEVWD¥Z;PQ:]Z;¦WDKR;FKDo`;tU:OR;taDsPEPQDIPE¦a:_R;PU:¡`EVK:O'["$args"%60]-68 ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X93DNSzc5dDSKOuAQKvYKOtDy8JdvIOs3bxd8hOsS0Kt/IOsSxJdigNcAwJdPANcDy1LtIoPsg4ItTq0MME1zNvKXz1aSSWxKL1YSdXMIFbXzOL///9GJpYWAA "PowerShell – Try It Online") Port of [ovs' answer](https://codegolf.stackexchange.com/a/144346/42963) to PowerShell. Since after reading the challenge, I was going to do something similar, it's easier to just re-use the string. [Answer] # Haskell, ~~159~~ 155 bytes **EDIT**: thanks to Laikoni for taking off 4 bytes! ``` ((z(+)(a 1)$a 0)!!) p#n=mod(p+n-1)10+1 b i=(1,1):[(p#(n*0^e),q#(n*e))|n<-[1+i..],let(p,q)=b i!!(n-1-i);e=mod n 2] a=z uncurry o.b o=(+):(-):(*):o z=zipWith ``` Usage: ``` (zipWith(+)(a 1)$a 0)!!5 ``` [Try it online!](https://tio.run/##FY5BDoIwEEX3PcUQXcwIbag70J7DBWJSsWojlBFwIfHsVlz85G3ey7/b8eHaNo7mGBFnTAktaFpbyClJSPAqmK6/IKdBatJ5qsUZvEGdaSor5BWGTX5ylD3/5Ig@YS8rnXql6qx1E3L2JLMoSYJLQXrauX8QAmxrYc0Mr9C8huENvTqL3iwHSpTLNlT2Yjaz54Of7rGzPhgefJjWnWUYocqVKoo6fptra29jlA3zDw) Explanation: The # operator is for incrementing a coordinate by some value n and wrapping it. Notice the -1 and +1 to get it onto the range [0..9] so mod will work right. The `b` function builds an infinite list of coordinates given an offset value of 0 or 1 to simulate the difference between 0 indexing and 1 indexing. `b` works by recursively iterating on the coordinates, starting with a hardcoded value of (1,1). When updating a coordinate we need to make sure we don't change it if n doesn't have the right parity so I multiply n by some value that will be 0 or 1 depending on its parity. `e` will be 0 when `n` is even and 1 otherwise and the `0^` trick can invert that for the other case. The `a` function also takes an offset, passes it to `b` and zips the result with an infinite list cycling between the addition, subtraction and multiplication operators. The zip is performed with the `uncurry` function which breaks up the coordinate pair and applies them to the operator. Finally we build the resulting sequence by simply zipping the lists (generated with different offsets) with the addition operator. Then we use the `(!!)` operator to turn it into a lookup function. [Answer] # [Python 2](https://docs.python.org/2/), 85 bytes ``` lambda j:ord('! /0 ~3)*630 $+$ H9M.(+M: L) )* ") :8+).z9 /$('[j%60])-29 ``` [Try it online!](https://tio.run/##PZAxb4MwEEZ3r7BCr4gqdgjENsTBVOwdmk7Z0gyggEqUADIs7dD8dEqDiaen7@7e2W6/@6@m5kOZfg6X7JqfMjgnjTrhxbO9ptZvaJKlIULzRi3XM59c602au8DAnrlLrHdik6XlEPuWGLFnksD4kfbaNfDicH4R9Eh8Loc9pOA4DqIwnQgxTQzxmWIUzihRpJGijSa5RUzP@2yMNTOOBJ2tgs1WwR9WET6sjFJtZWxqZf/WKR1DKe97ZYx4JLf6fpGM9aIR5R1DxDfz0PiuA0t8dkRlo6CHqoZ90LWXqr9UddFhkkC2gnz8gWvW4qruV9BPdUzIK2RdV6geSpwRSFPIUavGHnA@Gl2qmhoKpRrVBc7wBw "Python 2 – Try It Online") Based off of [ovs' Python 3 answer](https://codegolf.stackexchange.com/questions/144334/back-to-the-basics-of-math/144346#144346); implemented in Python 2 without using non-ASCII characters. [Answer] # Java 8, ~~191~~ 85 bytes ``` n->"HEVWD¥Z;PQ:]Z;¦WDKR;FKDo`;tU:OR;taDsPEPQDIPE¦a:_R;PU:¡`EVK:O".charAt(n%60)-68 ``` -106 bytes by porting [*@ovs*' Python 3 answer](https://codegolf.stackexchange.com/a/144346/52210). I lost my initial solution that I've used to create the test cases.. :( But the hard-coded result is way shorter anyway. I didn't knew the sequence was repeating every 60 items until after I posted the challenge. ;) [Try it online.](https://tio.run/##LY/fasIwFMbv9xSHgtDQtXQ3MpIpDNKxUaaxooJDZhbrFqdJaaIwxIfZxXyQvliXVuH84XyHw@87G37goS5ytVl912LLjYFXLtXxBkAqm5drLnIYNGMrgPCbqhBxysmlC2O5lQIGoKAHtQr73nMyndHqb07YCC/mpDrPaJqRp5TqJbETPMyI5dSwhI3oC0uqM8fvGWETXP0uk2mKh14kvnj5aH3V6cYo7N7X5IIq9h9bh7oSD1quYOfc@mNbSvX5tuDo4nSty9an7MUE5MNd3LQgQO0SYPxjbL6L9N5GhTt0nMj9hQLv1rs@dqr/AQ) ]
[Question] [ We seem to quite like digit runs lately, so here's a fairly simple challenge. Given a positive integer, split it into it's digit runs, and return the product. For example: `11122333` would become `111, 22, 333`, the product of which is `813186` Input may be taken as an integer, string, or list/array of digits/characters. Your entry must work for any number within it's representable range. I have tested this for 32-bit integers (2^32-1 max value) and the largest possible result I have found is `1099999989` from `1199999999`, which is also within the 32-bit integer range. I have yet to find a number who's output is larger than the input. For the purposes of this challenge, runs of length 1 are not counted. If there is only 1 run, return the run. If there are no runs, do anything (undefined behaviour) Standard I/O rules apply, output can be given as an integer or string. ## Testcases ``` 11122333 -> 813186 1112333 -> 36963 1122855098 -> 13310 98776543 -> 77 1000000 -> 0 123456789 -> undefined 1 -> undefined 99445662 -> 287496 1199999999 -> 1099999989 999999999 -> 999999999 ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes **in each language** wins! [Answer] # [Haskell](https://www.haskell.org/), ~~63~~ 55 bytes Since no one has done Haskell yet here's my take on it. Takes a string as input (of course). ``` import Data.List f s=product[read x|x@(_:_:_)<-group s] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrTaHYtqAoP6U0uSS6KDUxRaGipsJBI94KCDVtdNOL8ksLFIpj/@cmZuYB1WXmlaikaRRn5JcrGBoaGhkZGWv@BwA "Haskell – Try It Online") This code almost looks as if it is not golfed, but I cannot find anyway to make it shorter. [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~10~~ 8 bytes Takes input as a string, outputs an integer or `1` for "undefined". ``` ò¦ fa_Ã× ``` [Test it](http://ethproductions.github.io/japt/?v=1.4.5&code=8qYgZmFfw9c=&input=IjExMTIzMzMi) * 2 bytes saved thanks to [ETH](https://codegolf.stackexchange.com/users/42545/ethproductions) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 5 bytes -1 byte thanks to Erik the Outgolfer ``` γ9ÝKP ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3GbLw3O9A/7/t7QwNzczNTEGAA "05AB1E – Try It Online") If we don't need to ignore runs of length one, 2 bytes: ``` γP ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3OaA//8tLczNzUxNjAE "05AB1E – Try It Online") [Answer] # JavaScript (ES6), ~~46~~ ~~45~~ ~~38~~ 35 bytes Takes input as a string, outputs an integer or throws an error for "undefined". ``` s=>eval(s.match(/(.)\1+/g).join`*`) ``` * 7 bytes saved thanks to [Herman](https://codegolf.stackexchange.com/users/70894/herman-lauenstein). * 3 bytes saved thanks to [Craig](https://codegolf.stackexchange.com/users/68610/craig-ayre). --- ## Try it ``` o.innerText=(f= s=>eval(s.match(/(.)\1+/g).join`*`) )(i.value="11122333");oninput=_=>o.innerText=f(i.value) ``` ``` <input id=i><pre id=o> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ŒgḊÐfḌP ``` [Try it online!](https://tio.run/##y0rNyan8///opPSHO7oOT0h7uKMn4P///9GGOgoQZARGxhAUCwA "Jelly – Try It Online") -1 thanks to [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun). [Answer] # [Perl 5](https://www.perl.org/), 25 bytes 24 bytes + `-p` flag. ``` s/(.)\1+/$.*=$&/eg;$_=$. ``` [Try it online!](https://tio.run/##NYpbCsIwFAX/7yqubRAfmFebtCHk010USi1BhFiCieuP9TU/MxxO9I@gSr2Jq/EUS2I7uh/EkRF6cGTL/NWS0RFaLEKN52W6BJ/w/gz5FoPH7FPGeUo@ARmROqyGpbJAKDrktgghpGyaBt7xtZS9Utz0YPqu06pdN/4BjGlbpbVcT@YH/MO8AA "Perl 5 – Try It Online") Quite straight forward: `(.)\1+` matches the runs of more than one digit, and `$.*=$&` uses `$.` as accumulator for the multiplications (because its initial value is 1 and not 0). Finally, `$_` is set to `$.` and implicitly printed thanks to `-p` flag. [Answer] # [Perl 6](https://perl6.org), 21 bytes ``` {[*] .comb(/(.)$0+/)} ``` [Test it](https://tio.run/##VY/NTsMwEITvfoo9RDShJY3jxLEVFbhy50YRKokrBaVJlB8EqsKLcePFwm5qCvjkmf1mx25MW8pp6Ay8Sj9L2eEdLrI6N7CZjg@Xj@Bn9eHZXbu@5wTLtTdOCNz2puthA2VRmc71vj4ttM2RQHVX9SmjlffIpawpdxUs51DK9nVr81fX4DyB6xRVM/Qrx7w1JutNfuPBkQFgjdOabiipiB5kQS/FYbGH3OyxPYdzbk7hqPvJrX5nK/Bf6qJyF1S68BAcwZT4wFOm2XWYmtfDB5wgvNg9RLNx4pyHoRCCpooLriQjyzpCaikYISqOA63I40LwgGmVJDKOZipJGA/mQypgGI9imShNcqjsnxj/L7WOkJIhuaFKIk3N2p65KDjdlWb6r38W3w "Perl 6 – Try It Online") This returns `1` if there is no *“digit runs”* as that is the base case for multiplication. The only change to allow one digit runs is to replace `$0+` with `$0*` in the regular expression. ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 [*] # reduce the following using &infix:<*> .comb( # pull out substrings that match the following # (implicit method call on 「$_」) / (.) # any digit (character) $0+ # at least one more of that digit / ) } ``` [Answer] # [Retina](https://github.com/m-ender/retina), 47 bytes ``` (.)\1+ $*_ T`d {`(?<=^(_+) _*)_ $1 }`^_+ _ _ _ ``` This is slow on the larger test cases. [Try it online!](https://tio.run/##K0otycxL/P9fQ08zxlCbS0UrXoErJCGFqzpBw97GNk4jXltTIV5LM55LxZCrNiEuXlshngsI//83NDQysjA1NbC0AAA "Retina – Try It Online") ### Explanation ``` (.)\1+ $*_ ``` First, replace each run of 2 or more of the same digit with that many `_`s, followed by a space for separation. ``` T`d ``` Then remove all remaining digits. ``` {`(?<=^(_+) _*)_ $1 }`^_+ _ _ ``` Next, run these two stages in a loop. The first replaces every `_` in the second run with the entire first run, effectively multiplying them. The second stage deletes the first run. ``` _ ``` Finally, output the number `_`s. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~93~~ 89 bytes There must be some more golfing to be done here... ``` z,r;f(char*d){for(z=0;r=*d++;z=r/10?z?z*r:r:z)for(r-=48;r%10==*d-48;r=r*10+*d++-48);d=z;} ``` [Try it online!](https://tio.run/##dZDLboMwEEX3@QqEFAlDUP3Cj1hufqSbCIeURUk0ajeO8u0Uk6C4Mp3VeO49vva09bltx9HvwHRF@3mE0qFbd4HCW2zAlq6qjLfwRvDBH3wJe9h7FHSoLVcGtgTbyVWH3kJJcBWQ6YiMs97cx69jPxRoc9tkU12hH767IieEUMoYy@r3TBFGlMi27mPId5GWI2QS6MkwoQX7i6wTlKqmwVoFiDBGcAwtYsJpJaVo@Bwl5QtZ5mkQniv444THNHVTxhshlQ7@n8Gdun44uYhb9JT8j0i/oPl0h6ABoEpyHW140Vb2pZ817ws/@umd0dIWx0pixL4OUWpM3sdf "C (gcc) – Try It Online") [Answer] # Mathematica, 61 bytes ``` Times@@FromDigits/@Select[Split@IntegerDigits@#,Length@#>1&]& ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~95~~ 79 bytes -2 thanks to @LeakyNum ``` l='0' p=1 for c in input()+' ':a=c in l;p*=int(l)**(len(l)>1>a);l=l*a+c print p ``` [Try it online!](https://tio.run/##PY3LDsIgEEXX8hWTbuhjU@gLanCnWzf@QIOYNiEtoTTq11cg6mQW5947D/N24zLTXS53BQKSJNm1wCVGRhD0WCxImGbfZnNpVmDA/SCipY8mF9PsUp3learV7OFETkN21ELnQyGRsT4Gs/ubyNl3jw7PcdIKbnZTXhzUS0kIf5F6SWUcnK@Xs7WL9aEZ1nXHhBBKq6rCKOKPKGVNU3LmBWdd1zZ19MtYgWhVN23HeOAwxGuvWxqX@bei/@cP "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 69 bytes ``` lambda n:eval('*'.join(zip(*re.findall(r'((.)\2+)',n))[0])) import re ``` [Try it online!](https://tio.run/##RYvRDoIgGEav8yn@O8DIKYqKW72IekFLFw2BoWurl6fNaJ2r7@zsc6/tbg0L83kIWi7XmwTTTU@pMUpR9rDK4LdyOPVTNitzk1pjjzDOyMCOBFFDSJ@PhCRqcdZv4KcwWw8rKAN9ckBFUTBWliWiUf6bsZbzXLS7irZpal7Flu98g6gqXtcsnkQktp@NHTivzAYrBXS6IAozXkn4AA "Python 2 – Try It Online") [Answer] # [PHP](https://php.net/), 62 bytes prints 1 if no run is found ``` preg_match_all('#(.)\1+#',$argn,$t);echo array_product($t[0]); ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwJVaVJRfFF@UWpBfVJKZl65R5xrv5x/i6eyqac2lkliUnmerZGhoZGRhampgaaFk/b@gKDU9PjexJDkjPjEnR0NdWUNPM8ZQW1ldB6xaR6VE0zo1OSNfIbGoKLEyvqAoP6U0uURDpSTaIFbT@v9/AA "PHP – Try It Online") [Answer] # CJam, 18 Bytes ``` qe`{0=1>},{:*i}%:* ``` [Try it Online](http://cjam.aditsu.net/#code=qe%60%7B0%3D1%3E%7D%2C%7B%3A*i%7D%25%3A*&input=11122333) ``` q e# read string - '1112333' e` e# convert string to RLE - [[3,'1'],[1,'2'],[3,'3']] {0=1>}, e# filter out runs of length one - [[3,'1'],[3,'3']] {:*i}% e# convert sub-arrays to runs - [111,333] :* e# multiply array elements - 36963 ``` [Answer] # Ruby, 41 bytes ``` p eval gets.scan(/(.)\1+/).map(&:join)*?* ``` Takes input from stdin, scans it for runs of length > 1, joins them on `"*"`, evaluates and prints. [Answer] # Factor, 151 bytes ``` [ { } { } ] dip [ 48 - 2dup swap in? [ suffix ] [ [ suffix ] dip 1array ] if ] each suffix rest [ 0 swap [ swap 10 * + ] each ] map product ``` Getting a better grip on this language! Still don't think I'm using enough combinators... ]
[Question] [ You are required to find how many triangles are unique out of given triangles. For each triangle you are given three integers a,b,c , the sides of a triangle. A triangle is said to be unique if there is no other triangle with same set of sides. Note : It is always possible to form triangle with given sides. **INPUT:** First line contains n, the number of triangles. Each of next n lines contain three integers a,b,c (sides of a triangle). **Output:** print single integer, the number of unique triangles. **Constraints:** ``` 1 <= n <= 10^5 1 <= a,b,c <= 10^15 ``` **Sample Input** ``` 5 7 6 5 5 7 6 8 2 9 2 3 4 2 4 3 ``` **Sample Ouput** ``` 1 ``` **Explanation** ``` only triangle with sides 8, 2, 9 is unique ``` [Answer] ### GolfScript, 22 characters ``` n%{~]$}%:^{]^\/,3<},,( ``` Includes the first line into the list of triangles but subtracts one from the result later. Run [online](http://golfscript.apphb.com/?c=OyI1CjcgNiA1CjUgNyA2CjggMiA5CjIgMyA0CjIgNCAzIgoKbiV7fl0kfSU6XntdXlwvLDM8fSwsKAo%3D&run=true). *Commented code* ``` n% # Split input into lines { # For each line ~] # Evaluate the content and put into array $ # Sort the array (aka sides) }% :^ # Assign to variable ^ { # Filter list of triangles ] # Make array from triangle ^\/ # Count number of occurences in ^ by splitting ,3< # and testing if number of parts is less than 3 (i.e. # triangle occurse only once }, ,( # Count distinct lines and subtract 1 (for first line) ``` [Answer] # k [22 chars] ``` {+/1=#:'={x@<x}'x:1_x} ``` ### Example ``` input:(5;7 6 5;5 7 6; 8 2 9;2 3 4;2 4 3) input 5 7 6 5 5 7 6 8 2 9 2 3 4 2 4 3 ``` Output ``` {+/1=#:'={x@<x}'x:1_x}[input] 1 ``` ### Example ``` input:(3;1 2 3;4 5 6;7 8 9) input 3 1 2 3 4 5 6 7 8 9 ``` Output ``` {+/1=#:'={x@<x}'x:1_x}[input] 3 ``` [Answer] # APL, 18 chars/bytes\* ``` {+/1=+/∘.(≡⍦)⍨1↓⍵} ``` Dialect is [Nars2000](http://www.nars2000.org/). Following the lead in the K answer, this code is a *function* that accepts a list of vectors, first the number of lines (which is ignored) and then the triangles. Let me know if this is not ok. **Exploded view** ``` { 1↓⍵} drop the first element of the list (the number of lines) ∘.( )⍨ for each possible pair of vectors (triangles) from the list, ≡⍦ compare them as multisets: check whether they are the same triangle +/ sum each row: for each triangle, count how many others are the same 1= find out which ones are unique +/ and count them ``` **Example** ``` {+/1=+/∘.(≡⍦)⍨1↓⍵} 5(7 6 5)(5 7 6)(8 2 9)(2 3 4)(2 4 3) 1 {+/1=+/∘.(≡⍦)⍨1↓⍵} 6(7 6 5)(5 7 6)(8 2 9)(2 3 4)(2 4 3)(2 4 6) 2 ``` ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ \*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long. [Answer] ## GolfScript (24 chars) ``` ~](;3/{$}%:^1/{^\/,2=},, ``` [Online demo](http://golfscript.apphb.com/?c=Oyc1CjcgNiA1CjUgNyA2CjggMiA5CjIgMyA0CjIgNCAzJwoKfl0oOzMveyR9JTpeMS97XlwvLDI9fSws) This relies on the triangle sides being GolfScript literals of the same type (and hence sortable): it would [work equally well with strings](http://golfscript.apphb.com/?c=Oyc1CiJnIiAiZiIgImUiCiJlIiAiZyIgImYiCiJoIiAiYiIgImkiCiJiIiAiYyIgImQiCiJiIiAiZCIgImMiJwoKfl0oOzMveyR9JTpeMS97XlwvLDI9fSws). [Answer] ## C#: 250c *(compiled to exe; assumes "line" means from stdin, so ran as `type trianglesfile | counttri.exe`)* ``` using System;using System.Linq;class P{static void Main(){int n=int.Parse(Console.ReadLine());var a=new string[n];while(--n>=0)a[n]=string.Join(":",Console.ReadLine().Split(' ').OrderBy(x=>x));Console.Write(a.GroupBy(s=>s).Count(g=>g.Count()==1));}} ``` Ungolfed: ``` using System; using System.Linq; class P { static void Main() { int n = int.Parse(Console.ReadLine()); // reads line from stdin; converts to int without validation var a = new string[n]; while (--n >= 0) a[n] = string.Join(":", // re-stringfy the following: Console.ReadLine() // - read the next line .Split(' ') // - splits by space to form an array of sides .OrderBy(x => x) // - sorts by default comparison ); Console.Write( a.GroupBy(s => s) // group on the sorted, stringified value .Count(g => g.Count() == 1) // count the number of groups which have 1 member ); } } ``` --- ## C#: 116c *(via LINQPad, in "C# Statements" mode; assumes "line" means any single line from an arbitrary string `s`, definition not counted)* ``` string s = @"5 1 2 3 2 1 3 4 5 6 3 1 2 8 7 6"; // <- input not included in overall count Regex.Split(s,"\r\n").Skip(1).GroupBy(x=>string.Join(":",x.Split(' ').OrderBy(y=>y))).Count(g=>g.Count()==1).Dump(); ``` Ungolfed: ``` string s = @"5 1 2 3 2 1 3 4 5 6 3 1 2 8 7 6"; // literal string definition, not counted Regex.Split(s, "\r\n") // split on regex .Skip(1) // who cares about the number of following lines? .GroupBy(x => string.Join(":", // re-stringify the following: x.Split(' ') // - split by space into sides array .OrderBy(y => y))) // - sort sides array .Count(g => g.Count() == 1) // count the number of groups that have 1 member .Dump(); // Output into LINQPad results pane ``` [Answer] ## Bash and coreutils (~~87~~,~~98~~,~~95~~,93) Assumes input file is called "f", ``` sed 1d f|while read n;do echo `echo $n |tr ' ' '\n'|sort|tr '\n' ' '`;done|sort|uniq -u|wc -l ``` Reads line by line, sorts each line separately, then sorts all the lines. Finally the unique lines are filtered and counted. Also works for strings. EDIT: As [Yimin Rong](https://codegolf.stackexchange.com/users/15259/yimin-rong) pointed out, the first line containing the number of triangles is now handled (by removing it :) ). [Answer] ## D - ~~201~~, ~~172~~, ~~171~~, 170 chars Reads from STDIN only and relies on D 2.x for UFCS (Uniform Function Call Syntax) and assumes the `-property` compiler flag isn't set. ``` import std.stdio,std.algorithm,std.conv;void main(){int n=[stdin.readln[0]].to!int;char[][]a;while(n-->0)a~=stdin.readln.dup.sort;a.group.filter!(x=>x[1]<2).count.write;} ``` Normal indented version: ``` import std.stdio, std.algorithm, std.conv; void main() { int n = [ stdin.readln[0] ].to!int; char[][] a; while( n --> 0 ) a ~= stdin.readln.dup.sort; a.group.filter!( x => x[1] < 2 ).count.write; } ``` Input: ``` F:\Code\Other>rdmd tri.d 5 7 6 5 5 7 6 8 2 9 2 3 4 2 4 3 ``` Output: ``` 1 ``` [Answer] ## **Perl, ~~53~~ ~~50~~ 45** ``` perl -nE '$h{"@{[sort split]}"}++}{say-1+grep{!log}values%h' ``` Input either STDIN or append filename to the line above. "**50**" -- counting inside `' '` and `n`. Another edit: ``` perl -nE '$h{1,sort split}++}{say-1+grep{!log}values%h' ``` i.e. **45**. As I understand, the trick here is to force list context when evaluating hash index. Then Perl joins this list with `$;` (cf. with `$"` in my previous take). Without `1,`, `sort` evaluates in scalar context = undefined behaviour. [Answer] # bash — 98 ~~113~~ characters I'm sure this isn't the smallest `bash` solution (assumes `i` is the input file): ``` rm -f w;sed 1d i|while read L;do echo $L|xargs -n 1|sort|xargs -n 3 >>w;done;sort <w|uniq -u|wc -l ``` Explanation: `rm -f w;` // delete working file `sed 1d i|while read L;` // read each line, skipping the first one `do echo $L|xargs -n 1|sort|xargs -n 3 >>w;` // normalize each line by sorting the elements `done;` // end of while loop `sort <w|uniq -u|wc -l` // sort all the lines, pull out unique ones and count [Answer] # Haskell (116, 99 w/o import) ``` import Data.List main=getContents>>=(\x->print((length.(filter((<2).length)).group.(map(sort.words)).tail.lines)x)) ``` If the file `input` contains the example input, run with: ``` $ cat input | runghc solution.hs 1 ``` [Answer] # Ruby, 55 characters ``` a=$<.map{|s|s.split.sort} p a.count{|b|1==a.count(b)}-1 ``` The code is pretty straightforward for golfing standards: * first `a=$<.map{|s|s.split.sort}` reads all lineas from stdin, splits them into arrays, sorts them and stores them in the array `a`, * then `a.count{|b|1==a.count(b)}` counts how many of those arrays appear only once in `a`, * and the final `-1` is just not to count the first line read from stdin :) [Answer] ``` #include<iostream> #include<stdio.h> void unique_check(); typedef struct triangle { int s1, s2, s3; }t; t *tp[10]; int no; void main() { int i,ch=0; do { int ch; printf("Enter the no triangles\n"); scanf_s("%d", &no); for (i = 0; i < no; i++) { tp[i] = (t *)malloc(sizeof(t)); printf("Enter the sides of %d triangle ", i); scanf_s("%d", &tp[i]->s1); scanf_s("%d", &tp[i]->s2); scanf_s("%d" ,&tp[i]->s3); } unique_check(); printf("Enter the choice\n1 Perform more \n2 End\n"); scanf_s("%d", &ch); system("cls"); } while (ch!=2); } void unique_check() { int i, j, f = 0, count = 0,tri=0; for (i = 0; i < no; i++) { for (j = 0; j < no; j++) { if (i == j) continue; else { if (((tp[i]->s1 == tp[j]->s1) || (tp[i]->s1 == tp[j]->s2) || (tp[i]->s1 == tp[j]->s3)) && ((tp[i]->s2 == tp[j]->s1) || (tp[i]->s2 == tp[j]->s2) || (tp[i]->s2 == tp[j]->s3)) && ((tp[i]->s3 == tp[j]->s1) || (tp[i]->s3 == tp[j]->s2) || (tp[i]->s3 == tp[j]->s3))) { f = 0; break; } else f = 1; } } if (f == 1) tri++, f = 0; } printf("No of unique triangle\n%d\n",tri); } ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~12~~ 8 bytes ``` #εkOmwt¶ ``` [Try it online!](https://tio.run/##yygtzv7/X/nc1mz/3PKSQ9v@//9vymWuYKZgymWqAKS5LBSMFCy5jBSMFUyApImCMQA "Husk – Try It Online") -4 bytes from Leo. [Answer] # Pyth, 17 bytes This is not a serious participation, because Pyth is much younger than this question. Found the question while researching for another question and had to try it. ``` JmScd)t.zlfq/JT1J ``` Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=lfqeT1.rSmScd)t.z&input=5%0A7%206%205%0A5%207%206%0A2%203%204%0A8%202%209%0A2%204%203&debug=0). Wasted quite a few bytes on parsing the awkward input format. ``` .z read all of input t discard the first line m map each line d to: cd) split d by spaces S and sort J store the result in J f J filter J for trianges T, which satisfy the condition: /JT count T in J q 1 == 1 l length / number of remaining triangles, print ``` Another 17 byte solution, which uses the `.r` command (run length encoding). ``` lfqeT1.rSmScd)t.z ``` ]
[Question] [ # Task Your task is to output a single integer, with one restriction: its digits must be a permutation of [1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6]. For example, you could output 653443653152432, 413265345463352, or any of the other 15-digit integers whose digits are a permutation of the list. # Rules * Your code must terminate in a reasonable amount of time (do not just enumerate every integer until you get to 122333344455566). * If your language doesn't support 15-digit integers, or if there is no meaningful distinction between strings and integers in your language, you may output a string. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins. [Answer] # JavaScript (ES7), ~~13~~ 12 bytes ``` let f = _=>266**6+19 console.log(f()) ``` This computes: **2666 + 19 = 354233654641216 + 19 = 354233654641235** There are two triples **(a, b, c)** with **0 < a < 1000**, **0 < b < 10**, **0 < c < 100** and **ab + c** satisfying the condition. The following snippet finds them almost instantly. ``` for(a = 1; a < 1000; a++) { for(b = 1; b < 10; b++) { for(c = 1; c < 100; c++) { if((r = a**b + c + '').match(/^[1-6]+$/) && [...r].sort().join`` == '122333344455566') { console.log(a + '**' + b + ' + ' + c + ' = ' + r); } } } } ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 65 bytes ``` (((((((((((((((((((()()()){}){}){}){}())()))()))))())))())))())) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XwML0ARBzepaOALygAiMoSSc@P//v64jAA "Brain-Flak – Try It Online") This is `64` bytes of source code and `+1` for the `-A` flag. This simply pushes the ASCII values of each digit in a row. For reference, pushing the number `122333344455566` would take 238 bytes: ``` (((((((((((((((((((((((((((((((((((((((((((((((((()()()){}){}){})()){}{}){({}[()])}{}){}){}())){}{})){}{}){}())){}{})()){}{})){}{}){}())){}{}){}())){}{}){}())()){}{})()){}{})){}{})()){}{})()){}{})){}{}){}())){}{}){}())){}{})){}{}){}()){}) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X4NkoAmCmtW1UARmg5ga1bXRGpqxmrUwKaAMRAqqACGggUsCnamBVYMGCcYgCQDp//8B "Brain-Flak – Try It Online") [Answer] # [V](https://github.com/DJMcMayhem/V), ~~12~~, 10 bytes ``` 2¬26¬35a13 ``` [Try it online!](https://tio.run/##K/v/3@jQGiOzQ2uMTRMNjf//BwA "V – Try It Online") This generates the range `[2, 6]` twice, then the range `[3, 5]`, and then appends `13`. Outputs: ``` 234562345634513 ``` [Answer] # Turing machine, ~~132~~ 122 bytes ...and ~~11~~ ~~10~~ ~~8~~ 7 states, including `halt`. ``` 0 _ x r A 0 x y r A 0 y z r A 0 z _ r C 0 * * l 0 A _ 6 r B A * * r A B _ 2 r C C * 3 r D D _ 4 r E D 2 1 l halt E _ 5 l 0 ``` [Here is a Turing machine simulator that understands this syntax.](http://morphett.info/turing/turing.html) You should paste the code, clear the "Initial input" field, press Reset, then press Run. ## How it works Outputs `313456234562345` by looping to write `62345` three times and then writing `31` on top of the initial `62`. --- *-10 bytes thanks to @Leo* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes ``` “|BS½GA’ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5wap@BDe90dHzXM/P8fAA) Simply a base-250 compressed version of the number `122333344455566` Saved 1 byte thanks to @Mr. Xcoder [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 7 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ↓čvν□⅟“ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMTkzJXUwMTBEdiV1MDNCRCV1MjVBMSV1MjE1RiV1MjAxQw__) A simple compressed number. Alternate 9 byte run-length version: ``` Ƨ≡+‰“7─◄H ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMUE3JXUyMjYxKyV1MjAzMCV1MjAxQzcldTI1MDAldTI1QzRI) [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 40 bytes ``` +++++++[>+++++++<-]>.+..+....+...+...+.. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwKi7aAMG91YOz1tPRCCEFD8/z8A "brainfuck – Try It Online") fairly boring solution [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` •=["∊…Q ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcMi22ilRx1djxqWBf7/DwA "05AB1E – Try It Online") [Answer] # Befunge-93, ~~16~~ 14 or 12 bytes The only native integer literals supported by Befunge are the numbers 0 to 9, so coming up with an efficient representation for larger values is actually quite a common problem. In this case, though, it's not just a matter of finding the most efficient representation for a number, but also choosing a target number whose best representation is the shortest of all possible targets. After trying thousands of different combinations, the best I've been able to do so far is 14 bytes (12 to calculate the number, and then two more bytes to output it). ``` m&"7*:*::**+.@ ``` [Try it online!](http://befunge.tryitonline.net/#code=bSYiNyo6Kjo6KiorLkA&input=) If we allow extended ASCII characters, though, we can improve on the above solution by two bytes with: ``` eûãÃ"**:*+.@ ``` This is using the Latin-1 encoding, which we unfortunately can't demonstrate on TIO, since it doesn't support 8-byte encodings for the Befunge interpreters. **Explanation** In the first answer, we start with the string `"m&"`, which essentially pushes the values 109 and 38 onto the stack. Note that we save a byte by dropping the opening quote, since we can rely on Befunge's wrap-around playfield to have the one quote both open and close the string (this pushes a number of additional values onto the stack that we don't need, but we only care about the final two). We then push an additional `7` onto the stack, and execute the sequence `*:*::**+`, which performs a set of arithmetic calculations with the stack values, essentially calculating the expression: ``` 109+(38*7)^2^3 = 354233654641325 ``` Finally we use the `.` instruction to output the result of the calculation, and then the `@` instruction ends the program. In the second answer, we start with the string `"eûãÃ"`, which pushes the values 101, 251, 227 and 195. We then execute the sequence `**:*+`, which performs the required calculations on those values: ``` 101+(251*227*195)^2 = 123443543565326 ``` And again we finish with the instructions `.` and `@` to output the result and exit. Note that in both cases you need to be using an interpreter which supports 64-bit integers. Also note that the string wrapping trick won't work on Befunge-98 interpreters, since it relies on the interpreter ignoring instructions it doesn't recognise, but in Befunge-98 an invalid instruction will reflect. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` »Ċ¨?»²› ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCu8SKwqg/wrvCsuKAuiIsIiIsIiJd) Port of the second answer [here](https://codegolf.stackexchange.com/a/247594/107262) Explanation: ``` »Ċ¨?» # Compressed integer 11972312 ² # Squared › # Increment ``` I was on my way to making a super short one but I had read the rules wrong :( [Answer] # [Python 2](https://docs.python.org/2/), 21 bytes ``` print 122333344455566 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EwdDIyBgITExMTE1Nzcz@/wcA "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` 4967b5Ėẋ/€FḌ ``` [Try it online!](https://tio.run/##y0rNyan8/9/E0sw8yfTItIe7uvUfNa1xe7ij5/9/AA "Jelly – Try It Online") could probably be shorter [Answer] # [Pyth](https://pyth.readthedocs.io), 9 bytes ``` ."16U<³ ``` **[Try it here!](https://pyth.herokuapp.com/?code=.%2216%16U%C2%82%3C%C2%B3&debug=0)** **Output:** ``` 223133344455566 ``` [Answer] # [Tcl](http://tcl.tk/), 89 bytes ``` proc f a\ b {expr rand()>.5} puts [join [lsort -command f [split 122333344455566 ""]] ""] ``` [Try it online!](https://tio.run/##K0nO@f@/oCg/WSFNITFGIUmhOrWioEihKDEvRUPTTs@0lqugtKRYITorPzNPITqnOL@oREE3OT83F6gAqCW6uCAns0TB0MjIGAhMTExMTU3NzBSUlGJjQcT//wA "Tcl – Try It Online") [Answer] # [Tcl](http://tcl.tk/), 20 bytes ``` puts 122333344455566 ``` [Try it online!](https://tio.run/##K0nO@f@/oLSkWMHQyMgYCExMTExNTc3M/v8HAA "Tcl – Try It Online") [Answer] # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 20 bytes ``` "ek,@122333344455566 ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/Xyk1W8fB0MjIGAhMTExMTU3NzP7/BwA "Befunge-98 (FBBI) – Try It Online") Output is `665554443333221`. [Answer] # Groovy, 23 bytes ``` {"233456"​​​​​*2+145​}​ ``` Outputs: 233456233456145 [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 [bytes](https://codegolf.meta.stackexchange.com/a/9429/74163) ``` ⎕pp←30 37+266*6 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBI/6phYUPGqbYGzAZWyubWRmpmUGAA "APL (Dyalog Unicode) – Try It Online") Used @Arnauld's snippet, so credit goes to them. [Answer] # C++, 24 bytes ``` []{return(57LL<<41)-31;} ``` [Try it online!](https://tio.run/##Sy4o0E1PTv6fWFqSr5CmYPs/Ora6KLWktChPw9Tcx8fGxsRQU9fY0Lr2vzUXl3JmXnJOaUqqgk1mfnFJUWpirh1XZl6JQm5iZp6GpkJ1cUmKlVVyfmmJgo2NQpqGJlAXAA "C++ (gcc) – Try It Online") Returns 57×241−31 = 125344325566433. [Answer] # ARM T32 machine code, 8 bytes ``` 20d5 f24e 6157 4770 ``` Following the [AAPCS](https://github.com/ARM-software/abi-aa/blob/main/aapcs32/aapcs32.rst), this is a function returning a 64-bit integer in r0 and r1. The number is 58967×232+213=253261336543445. Disassembled: ``` 20d5 movs r0, #213 f24e 6157 movw r1, #58967 4770 bx lr ``` [Answer] # [A0A0](https://esolangs.org/wiki/A0A0), 16 bytes ``` O122333344455566 ``` `O` outputs the number after it. The number after it is a valid integer. I don't really think it's possible to save bytes by using some arithmetic expression. When multiplying two numbers of n and m digits, the resulting length of the multiplication will be at most n + m. Doing such a multiplication requires at least n + m + 2 (ignoring the operand) bytes, at which point you might as well just write the result directly. Addition is even worse in terms of length. Considering multiplication, addition and subtraction are the only built-in operators I find it hard to believe this can be shortened. I'd love to be proven wrong, though. [Answer] # x86 32-bit machine code, 9 bytes ``` 6A 85 58 BA 4F C9 00 00 C3 ``` Returns a 64-bit integer in EDX and EAX, as is standard. The value is 51536×232−123 = 221345434566533. [Try it online!](https://tio.run/##bZA/T8MwFMTn@FNcgyrZbVK1ibI0hIWZhYmBxfhPYsmxrTgplRBfneAisSCWk97de7@Tnih7IdaVxxH0Oafk0Fv/xi000ecsLHFAearqFsEHKH4l2egvUPJaoDk1dUOySc2E5awlxHrX40eMm6HpxRt58@@ME3aRCvdxlsYfhgdyWxi5cZSRD5KFKc2a5ltrzat74mIwTkF4qc55oSlLkEx4F2csLpreKQkx8Am7gA7034Tp9o8lEkR6/HZhe6xe8gKi24X9nrV4H4xViYZNh@P1sU6ln@v6JbTlfVzLsa6SpDd16V7Zbw "C (gcc) – Try It Online") In assembly: ``` f: push -123; pop eax mov edx, 51535 ret ``` --- Some alternatives that also take 9 bytes: --- ]
[Question] [ The **[Pythagorean Theorem](http://en.wikipedia.org/wiki/Pythagorean_theorem)** states that for a right triangle with sides `a`, `b`, and `c`, a2+b2=c2. A [**Pythagorean triplet**](http://en.wikipedia.org/wiki/Pythagorean_theorem#Pythagorean_triples) is a set of three numbers, where a2+b2=c2, a To extend this even further, a **primitive Pythagorean triplet** is a Pythagorean triplet where `gcd(a,b,c)=1`. The goal is to find 100 primitive Pythagorean triplets. **Input:** No input. **Output:** 100 primitive Pythagorean triplets, in whatever order and shape, as long as the output contains only those triplets. Shortest code wins. Good luck! [Answer] ## Python, 42 ``` i=4 while i<203:print 2*i,i*i-1,i*i+1;i+=2 ``` [Answer] # Javascript, 44 characters **Update:** ``` for(i=s=0;i^400;)s+=[i+=4,r=i*i/4-1,r+2]+' ' ``` I should have looked up an algorithm first. Well, can't beat python anyway. Run in a console to see the result. **Old, slow, brute-force variant (140 characters)** ``` for(q=a=[];563>++a;)for(b=a;--b;)(k=Math.sqrt(a*a+b*b))==~~k==function c(e,d,f){return f?c(c(f,e),d):d?c(d,e%d):e}(a,b,k)&&q.push([b,a,k]);q ``` [Answer] ## J, 64 60 38 49 characters ``` 100$}.~.(/:~*(0<*/*1=+./))"1[4$.$.(=/+/~)2^~i.699 ``` Should've realised that such a big gain was probably flawed. Still uses the brute-force method, but done a bit more efficiently. Explanation: `x=.2^~i.699` generates a list of ints from 0 to 699 and squares `2^~` them (`~` here reverses the order of the arguments). `(=+/~)` is a hook that generates an addition table and compares the result to the list. This gives me a three dimensional array with items which are either `1` or `0`. A `1` means that a2+b2=c2. `$.` converts to a sparse array. For my smaller (9) example I get: ``` $.(=/+/~)2^~i.9 0 0 0 | 1 1 0 1 | 1 1 1 0 | 1 2 0 2 | 1 2 2 0 | 1 3 0 3 | 1 3 3 0 | 1 4 0 4 | 1 4 4 0 | 1 5 0 5 | 1 5 3 4 | 1 5 4 3 | 1 5 5 0 | 1 6 0 6 | 1 6 6 0 | 1 7 0 7 | 1 7 7 0 | 1 8 0 8 | 1 8 8 0 | 1 ``` `4$.` just gives me the left part of this list. `(/:~*(0<*/*1=+./))"1[` decides which rows meet the criteria. `(verb)"1` tells the verb to act on the individual rows rather than on the list. `[` just separates the `1` and `4`, otherwise J will think that `1 4` is a list of 2 numbers. '1=+./' gets the GCD of the three numbers and checks if it's `1`. `*/` multiplies each triple together (getting `0` if it contains a `0`) and these two are multiplied together. `0<` turns the result into a boolean. `*` multiplies this result by each triple which eliminates all triples which contain a `0` or have a GCD which is not `1`. `/:~` sorts each triple. `~.` selects the unique items from the list. `}.` removes the first item (0 0 0) from the list. `100$` takes the first 100 items from the list. The above is my answer to this question, but as a matter of interest I implemented [grc's method](https://codegolf.stackexchange.com/a/6447/737), (27 characters): ``` 2(*,.<:@^~,.>:@^~)2*2+i.100 ``` [Answer] ### Scala 180: ``` def g(a:Int,b:Int):Int=if(a==b)a else if(a>b)g(a-b,b)else g(b,a) for(c<-(5 to 629); a<-(1 to c-2); b<-(a to c-1); if((a*a+b*b==c*c)&&g(c,g(a,b))==1)&&a<400)println(a+" "+b+" "+c) ``` Ungolfed: ``` def gcd (a: Int, b: Int) : Int = if (a == b) a else if (a > b) gcd (a-b, b) else gcd (b, a) def gcd (a: Int, b: Int, c:Int): Int = gcd (c, gcd (a, b)) def pythagorean (a: Int, b: Int, c: Int) = (a * a + b * b == c * c) for (c <- (5 to 629); a <- (1 to c-2); b <- (a to c-1); if (pythagorean (a, b, c) && gcd (a, b, c) == 1)) yield { println (a + "² + " + b + "² = " + c + "² => " + (a*a) + " + " + (b*b) + " = " + (c*c)) c*c } ``` [Answer] ## APL (31) ``` ↑{(2×⍵),(A-1),1+A←⍵×⍵}¨2+2×⍳100 ``` It uses basically the same approach as the Python program. [Answer] # MATLAB 29 ``` i=2:2:200;[2*i;i.*i-1;i.*i+1] ``` [Answer] **Mathematica 33** ``` {2#,#^2-1,#^2+1}&/@Range[4,203,2] ``` [Answer] # APL(NARS), 26 chars, 52 bytes ``` {k(4×⍵),2+k←¯1+×⍨2×⍵}¨⍳100 ``` test: ``` a←{k(4×⍵),2+k←¯1+×⍨2×⍵}¨⍳100 ≢a 100 +/{(x y z)←⍵⋄(z*2)=(y*2)+x*2}¨a 100 +/{∨/⍵}¨a 100 10↑a 3 4 5 15 8 17 35 12 37 63 16 65 99 20 101 143 24 145 195 28 197 255 32 257 323 36 325 399 40 401 ``` [Answer] ## R, 49 characters translated from the Python solution: ``` i=4;while(i<203){print(c(2*i,i*i-1,i*i+1));i=i+2} ``` ]
[Question] [ ## Description In this challenge, you need to write a function that takes in a list of strings and returns the smallest string based on their ASCII value. You should assume that the input list contains only lowercase alphabetical strings. ## Test Cases ``` ["a", "b", "c"] => "a" ["hello", "world", "code"] => "code" ["aaa", "aa", ""] => "" ["cat", "bat", "rat"] => "bat" ["zab", "xyz", "abcd"] => "zab" ``` Write the function in as few bytes as possible. The code itself can be a function, process or anything provided that it gives the desired output. Use of other ASCII characters like big or small letters, with space function must be supported. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ΣÇO}н ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3OLD7f61F/b@/x@tlJGak5OvpKOgVJ5flJMCYiTnp6QqxQIA "05AB1E – Try It Online") #### Explanation ``` ΣÇO}н # Implicit input Σ } # Sort by: Ç # ASCII values O # Sum н # First item # Implicit output ``` [Answer] # [Factor](https://factorcode.org/), 22 bytes ``` [ [ sum ] infimum-by ] ``` [Try it online!](https://tio.run/##RY3NCsIwEITvfYoxd30ARa/ixYt4Kj2kaYqB/JmmaFr67LEbkB52YOebne25iC7k5@N2vx4xyPcorZADfJAxJh@UjThVczWDcQbWriMYFuxwvpBF4CW1div4uKA7CrhObpmylXtODUU2WojgkbqLBtI/JYsCE6fH3zRRQSu6LUGkWnKNGsNo0EDZXpnR7NuEJhvuccg/ "Factor – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 57 bytes ``` l->l.stream().min((a,b)->a.chars().sum()-b.chars().sum()) ``` [Try it online!](https://tio.run/##lVC9TsMwEJ7JU1iZbJT4BVIyMoEYOiKGi/NTF8e27EshrfrswXFSCQQD8XCn@07fz/kIJ8iP9fske2sckmOY@YBS8XbQAqXR/L5Ifi2fpMc/4Bc7M0AViR0qJQURCrwnzyA1uSQkPI@AAX9cxXez0G6PTuquzMiNf0NK0j5MKi8V9@ga6CnjvdSUQlaxvAQuDuB8AP0QVnn1c2ZTES3XKKvzycia9CEQXTxe3wi4zrNLcrcfPTY9NwNyG1aoNG05WKtGOsfkpqUppBlJq7mIlDHeNRiMiv9xD41SZqZ@GKfqqGHqZrMMQAyx1M1sARhPWJoLbavCGeL9n@M5xqhE/V1i/vFrcp2@AA "Java (JDK) – Try It Online") Takes input as a `List<String>` and returns an `Optional<String>`. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), ~~18~~ 16 bytes -2 from Dominic van Essen for replacing `'0'` with `@`. ``` {𝕩⊑˜⊑⍒(+´@⊸-)¨𝕩} ``` [Try it online!](https://bqnpad.mechanize.systems/s?bqn=eyJkb2MiOiIjIFtcImFcIiwgXCJiXCIsIFwiY1wiXSA9PiBcImFcIlxuIyBbXCJoZWxsb1wiLCBcIndvcmxkXCIsIFwiY29kZVwiXSA9PiBcImNvZGVcIlxuIyBbXCJhYWFcIiwgXCJhYVwiLCBcIlwiXSA9PiBcIlwiXG4jIFtcImNhdFwiLCBcImJhdFwiLCBcInJhdFwiXSA9PiBcImJhdFwiXG5pbiDihpAg4p%2BoXCJoZWxsb1wiLCBcIndvcmxkXCIsIFwiY29kZVwi4p%2BpXG578J2VqeKKkcuc4oqR4o2SKCvCtCcwJ%2BKKuC0pwqjwnZWpfWluIiwicHJldlNlc3Npb25zIjpbXSwiY3VycmVudFNlc3Npb24iOnsiY2VsbHMiOltdLCJjcmVhdGVkQXQiOjE2NzQ5Mzc2OTI1NzZ9LCJjdXJyZW50Q2VsbCI6eyJmcm9tIjowLCJ0byI6MTc3LCJyZXN1bHQiOm51bGx9fQ%3D%3D) ### Explanation ``` {𝕩⊑˜⊑⍒(+´@⊸-)¨𝕩} { ¨𝕩} 1. For each string in the (monadic) input 𝕩 { ( @⊸-) } 2a. convert the string to (negative) its unicode representation... { (+´ ) } 2b. and perform a sum reduction. { ⍒( ) } 3. return descending-sorted indices. { ⊑ } 4. take the first. {𝕩⊑˜ } 5. take this index into the input 𝕩 where ˜ "flips" the next function. ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~5~~ 4 bytes ``` ‡C∑P ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigKFD4oiRUCIsIiIsIltcImhlbGxvXCIsXCJ3b3JsZFwiLFwiY29kZVwiXSJd) *-1 thanks to @mathcat* #### Explanation ``` ‡C∑P # Implicit input ‡ P # Minimum by: C # ASCII values ∑ # Sum # Implicit output ``` Old: ``` C∑)ṡh # Implicit input )ṡ # Sort by: C # ASCII values ∑ # Sum h # First item # Implicit output ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 92 bytes ``` f(s,t,u,i,c)char**s,*t,*u;{for(i=~0,u=0;t=*s;c<i+0U?u=*s,i=c:0,s++)for(c=0;*t;c+=*t++);s=u;} ``` [Try it online!](https://tio.run/##dZBNbsMgEIX3OcXIUhWMpxLrUtpTdOV6QcZxg@TYlYH@JHKv7g64kSq12Txg5mMePLp9IVqWTngMGNEhlXSwk5QeZUAZ9bkbJ@HMl8JolA5Gek33rlJPj5H36AzdKfRVVSaOGJFBU2Vk4JL2Jup5cUOAo3WDeBtdW8J5A5A8gE3qxqQjgMiudcNtKGyBUOySEIuCGf8yh33fjwl5H6e@zezY7q/i1uahq16lyIZsvS5TXv4nTza/7@PzlMfuqP2NKtYZ@YOcIWvUGy6kgILxGjghSPHA@vXXiQPqRFFDUepcSSSnyxhfhZjQC7S98VtgKxl/2EujAfMAqfs8cLsTMpSZmDfz8g0 "C (gcc) – Try It Online") Ungolfed: ``` f(s,t,u,i,c)char**s,*t,*u;{ for(i=~0, // initialize minimum string sum to largest possible u=0; // initialize smallest string (in case of empty list) t=*s; // scan list c<i+0U?u=*s,i=c:0, // reset minimum string sum and pointer if smaller s++) for(c=0;*t;c+=*t++); // get string sum s=u; // return smallest string } ``` [Answer] # Swift, ~~64 ~~ 69 bytes *Now with fewer compiler crashes!* ``` {$0.map{($0.reduce(0){$0+Int($1.asciiValue!)},$0)}.min{$0.0<$1.0}!.1} ``` [SwiftFiddle link](https://swiftfiddle.com/nwsbjcbcmfbfraijjpnba3ppp4) [Answer] # [Python](https://www.python.org), 44 bytes ``` lambda l:min(l,key=lambda x:sum(map(ord,x))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3dXISc5NSEhVyrHIz8zRydLJTK22hQhVWxaW5GrmJBRr5RSk6FZqamlA9KgVFmXklGmka0UoZqTk5-Uo6Ckrl-UU5KSBGcn5KqlIsTO2CBRAaAA) #### Commented ``` lambda l: # Anonymous function taking l, a list of strings min(l, ) # Return the minimum of l... key= # ...using the following function: lambda x: # Function taking x, a string sum( ) # Sum the following: map(ord,x) # Convert all characters to ASCII values ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 59 bytes ``` a=>a.sort(g=(x,y)=>x>=x&&~~eval(Buffer(x).join`+`)-g(y))[0] ``` [Try it online!](https://tio.run/##Zc7NCoMwDAfw@55CepCW@bEXqIe9hghmtXVKMaM6Vy@@emfrYUNz@IcQfiQ9zDAK072mdMBGOsUd8AKyEc1EW05tsjBe2ILbOF5XOYOm97dS0lDLsh67ob7WLG3pwlh5q5zAYUQtM40tVbQkQJKIPHwIUjEW/VeeR9v@ciRPqTV68UGjm0C3x3btSZhOCiCc2vNwyquzEDCF5/ZmtvZTXviF@wI "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array a.sort(g = // g is a recursive callback function (x, y) => // for each pair (x, y) to be tested: x >= x && // stop if x is undefined ~~eval( // otherwise, evaluate as JS code: Buffer(x) // the ASCII codes of x .join`+` // joined with '+' ) // end of eval() - g(y) // subtract the result of a recursive call with x = y ) // end of sort() [0] // keep the first entry ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes input as an array of character arrays. ``` ñÈxc ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&header=bXE&code=8ch4Yw&input=WwoiemFiIgoieHl6IgoiYWJjZCIKXS1Q) ``` ñÈxc :Implicit input of 2D array ñ :Sort by È :Function x : Sum of c : Codepoints :Implicit output of first element ``` [Answer] # Excel, 78 bytes ``` =LET(x,A1#,y,ROW(A:A),@SORTBY(x,MMULT(TOROW(y^0),IFERROR(CODE(MID(x,y,1)),)))) ``` where `A1#` is a *horizontal* spilled range containing the strings. [Answer] # [Zsh](https://www.zsh.org/) +old utils, 47 ~~55~~ ~~103~~ bytes Using the filesystem and the old System V [`sum`](https://www.gnu.org/software/coreutils/manual/html_node/sum-invocation.html)\* command: ``` for i;echo $i>$[++n];set `sum -s *|sort -n`;<$3 ``` [Try it online!](https://tio.run/##ZUxLCsIwFNz3FEPJQi1duYx4ERH68jOVmkCSUo169pisHRgG5pejLWa3f3erizrBFeMDZq6l9WDzmV2GwV15i6a4PjBGHD7Rh4TRTfzEjuXbGeR/IOr7bG5WgYSsFYJAU6uXxWPzYVGQXulqSUoQlYFS@yKB5yu3mWo7okr0ffkB)   ~~[55 bytes](https://tio.run/##ZUxLCsIwFNz3FEPpQi1ZiMuIF5FCX36mUhNIUtRazx6TtQPDwPzWaLPZ7T/N4qJOcNn4gIlraT266dJd@94NvEZjXB5gEYct@pDA3GY1KbDjyM/dKX8bg/UfiPo@mZtVICFLhSBQ1ep59nj6MCtIr3SxJCWIwkCpfpHA673Wmao7okK0bf4B)~~ \* On MacOS, `cksum -o2` is equivalent to GNU `sum -s`. According to Wikipedia, the [BSD checksum](https://en.wikipedia.org/wiki/BSD_checksum) algorithm is "useless from a security perspective" 😛 --- #### 103 bytes, using arrays and builtins only: ``` for x;{w=;for a (${(s::)${x:?}})((w+=#a));k+=($w)} for i ({1..$#})((k[i]==$(printf ${(n)k})))&&<<<$@[i] ``` [Try it online!](https://tio.run/##TVBNa4NAEL3nVzyihF0SAqU3o6SH9tpD2lvpYdRRNxpX3E01ir/d7vbUgcd8vPeGYSZTrYWQ8@beGrYgKFxRY1wL3WM8zUNy8hVBhLMwUSTDeYzOyyKFGPZJQFKe6n0iwkEuGy9UEPPT8RgGXlF/qe8kCUXXq9YWcBtaWS9Syt0ujuPwxdGrs8HwVRVllYPSzLWEFD5X3DQag@6bHJnO2Y0yskgderKumyjF@Ji8Lfc@Igdst/gXwbu2fICtGM99jh9q7gxlQC341tkHjHXXlTAarbaVLx37dzHnB/CYcef/cmNjqGToFh@fr2@Xy/oL "Zsh – Try It Online") Explanation of code is in earlier revisions of this answer [Answer] # [Raku](https://raku.org/), 17 bytes ``` *.min(*.ords.sum) ``` [Try it online!](https://tio.run/##FYpNCsMgGAWv8pBQ2lBcdlPjVcLnHy1obTQhNSFntwbeLGZ4X5v8o4aCi8NQex7en2vPYzKZ5yXc6hOZClg3YpDYHbrxYHAxQRAUtLxDvKz3EWtM3kBHY1ubplUQEdoYOz@aZqhGovnUjRR@ZQMpbWT9Aw "Perl 6 – Try It Online") `*.ords.sum` is an anonymous function that calculates the sum of the ordinal values of its string argument. That function is passed as the argument to `*.min`, which returns the element of the input list with the smallest value computed by the first function. [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 9 bytes ``` {)**++}<m ``` [Try it online!](https://tio.run/##SyotykktLixN/V@tpGBrp2RtrRtblPi/WlNLS1u71ib3f214zv9opUQlHQWlJBCRrBQLVKcAFOGKVspIzcnJB4mW5xflpICl81NSoSrATKCixESwbggJlQOJJyeWgE2FUEVACiIHEgBKVyWC7auorALrTkpOgcqDJAA "Burlesque – Try It Online") ``` { )** # Map to ord ++ # sum }<m # Minimum by ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) ``` OS$ÞḢ ``` [Try it online!](https://tio.run/##y0rNyan8/98/WOXwvIc7Fv3//z9aKQMolq@ko6BUnl@UkwJiJOenpCrFAgA "Jelly – Try It Online") #### Explanation ``` OS$ÞḢ # Main link $ # Last two links as a monad: O # Ordinals S # Sum Þ # Sort the input by this monad Ḣ # First item (minimum) ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~9~~ 5 bytes *And pure ASCII!* ``` {|+}e ``` [Run and debug it](https://staxlang.xyz/#c=%7B%7C%2B%7De&i=%5B%22a%22,+%22b%22,+%22c%22%5D%0A%5B%22hello%22,+%22world%22,+%22code%22%5D+%0A%5B%22aaa%22,+%22aa%22,+%22%22%5D%0A%5B%22cat%22,+%22bat%22,+%22rat%22%5D%0A%5B%22zab%22,+%22xyz%22,+%22abcd%22%5D&m=2) (with test cases) # Explanation ``` { }e # minimum by |+ # sum ``` [Answer] # [janet](https://janet-lang.org), 51 bytes ``` (fn[l](((sort-by first(map(fn[x][(sum x)x])l))0)1)) ``` in janet, you can save bytes by not using spaces between brackets, which i personally think is very ugly for a lisp-like language, so here's an de-uglified version and an example ``` (fn [l] (((sort-by first (map (fn [x] [(sum x) x]) l)) 0) 1)) ``` ``` $ janet Janet 1.29.1-20230709 openbsd/x64/clang - '(doc)' for help repl:1:> (def F (fn[l](((sort-by first(map(fn[x][(sum x)x])l))0)1))) <function 0x028B13B5F580> repl:2:> (F ["zab" "xyz" "abcd"]) "zab" ``` [Answer] # [Arturo](https://arturo-lang.io), 42 bytes ``` $=>[minimum&=>[∑to[:integer]to[:char]&]] ``` [Try it](http://arturo-lang.io/playground?xKuDUd) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 74 bytes ``` . $&$&96$*~ 0T1`l`L`\w\w {`[J-Z] 9$& }T`_L`dL \d $*~ +`(\w)~ ~$1 O` 1G` ~ ``` [Try it online!](https://tio.run/##K0otycxL/P9fj0tFTUXN0kxFq47LIMQwISfBJyGmPKacqzoh2ks3KpbLUkWNqzYkId4nIcWHKyaFC6RQO0EjplyzjqtOxZDLP4HL0D2Bq47r///EpOQUrorKKq6qxCQA "Retina 0.8.2 – Try It Online") Only accepts strings of lowercase letters. Explanation: ``` . $&$&96$*~ ``` Duplicate each letter and suffix 96 `~`s to each pair. ``` 0T1`l`L`\w\w ``` Uppercase alternate letters. ``` {`[J-Z] 9$& }T`_L`dL ``` Map uppercase letters into digits that sum to their index i.e. `A=1` to `Z=998`. ``` \d $*~ ``` Expand the digits into that many `~`s. ``` +`(\w)~ ~$1 ``` Move all of the `~`s to the beginning of the string. ``` O` ``` Sort the strings into order. Since `~` sorts after `z`, this means that the string with the fewest `~`s will sort first. ``` 1G` ``` Keep only the first string. ``` ~ ``` Delete the `~`s. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` UMθ⟦↨Eι℅λ¹ι⟧⊟⌊θ ``` [Try it online!](https://tio.run/##Fcg9C4MwEIDhvb8iZLqDdOjsprPoHjKcieBBPjS2Yv3zVzu8PPD6haovFEV6WruSEuUAm1G2pX2G@wEbNdTAmSJERKNed@yweYyV8xvGskLPmdMnwYaIjYi1miYftFH6/F5/Lpq0c/I84g8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` UMθ⟦↨Eι℅λ¹ι⟧ ``` Calculate the sum of ASCII values for each string. ``` ⊟⌊θ ``` Output the string with the smallest sum. [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 55 bytes ``` ($args|Sort-Object{"$($_|% t*y|%{'+',+$_[0]})"|iex})[0] ``` [Try it online!](https://tio.run/##RU/JboMwED3jrxhZTsENSP2BSEhVe23V9BZFyJjJJlqntlEW4NupbUhyme1tmqM6oTY7rOtMKo0D2yzaIWFCb023VNpmH@UBpW0pS1jRzcA@X7pZG8/jdM6K1cu657Tb47nnbh56QvKERGme5AkVNAVa@iIpd1VQfoN8nPLISem6ChRVYWCNw91DBJexBvyBSWFDwti0a3xa75SrCPnnyzW4lLIKHH/mhEMH70q/CbmbnoSWRMyisSkwPB/dBStYACvcWaNpauu2J7aB3JNItPpcvjbGqp9RvobcGUTLRko0xgsnUYZ/D0PH@HZqD3sXyA5q/wtxCrFDvm4pk5REPenJ8A8 "PowerShell Core – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 6 bytes ``` .msCMb ``` [Try it online!](https://tio.run/##K6gsyfj/Xy@32Nk36f//aKWqxCQlHQWlisoqEJWYlJyiFAsA "Pyth – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 2 bytes ``` ◄Σ ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8f@j6S3nFv///z86WilRSUcpCYiTlWJ1opUyUnNy8oG88vyinBSQaH5KKlgiMRGkEEyA@cmJJSCNYLIISILEqhJBBlVUVoFUJiWnKMXGAgA "Husk – Try It Online") ``` ◄ # minlon: Element that minimizes function result Σ # chrsum: Sum of code points ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), ~~15~~ 14 bytes ``` ⊑∘⍋∘(+´¨-⟜@)⊑⊢ ``` [Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=U21hbGxlc3Rfc3VtIOKGkCDiipHiiJjijYviiJgoK8K0wqgt4p+cQCniipHiiqIKU21hbGxlc3Rfc3Vtwqgg4p+o4p+oImhlbGxvIiwgIndvcmxkIiwgImNvZGUi4p+pLOKfqCJjYXQiLCAiYmF0IiwgInJhdCLin6ks4p+oInphYiIsICJ4eXoiLCAiYWJjZCLin6nin6k=) ``` ⊑∘⍋∘(+´¨-⟜@)⊑⊢ ( ¨ ) # for each element of input -⟜@ # subtract the null character from each letter # (thereby getting codepoint values) +´ # and sum by fold-addition ⊑∘ # now get the first element of ⍋∘ # the indices of sorted elements ⊑ # and use this to select from ⊢ # the elements of the input ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 12 bytes ``` @Y{$+A*a}SKg ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZrHCKrVbQdtRJrg73TIUJQma3RSsmJJUo6CkpJEKoISMVCJQE) #### Explanation ``` @Y{$+A*a}SKg ; Input on command line g ; Input list { }SK ; Sorted by: $+ ; Sum of A* ; ASCII values of a ; The string @Y ; First item (minimum) ; Implicit output ``` ]
[Question] [ Strangely never asked before, this question pertains to the generation of a list of prime numbers within a given range using the shortest possible code. Several algorithms, such as the Sieve of Eratosthenes and trial division, are known to be effective for this purpose, but require significant code length. Is there an alternative approach or trick that can be used to generate a list of prime numbers in a more concise manner? The focus of this question is on the optimization of code length, so answers should try to make their code as short as possible. Answers in any programming language are welcome. May the shortest code win! ### Format You must accept two positive integers and output a list of integers in [any reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). ### Rules * Your code doesn't need to handle numbers less than one. * The range should be exclusive, i.e., `(a..b)` instead of `[a..b]` or `[a..b)`. * Either ascending or descending ranges should be supported. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. ### Test cases ``` 11 59 -> [13,17,19,23,29,31,37,41,43,47,53] 11 3 -> [7,5] 2 2 -> [] 2 3 -> [] 2 4 -> [3] 4 2 -> [3] ``` [Answer] # [Factor](https://factorcode.org/) + `math.primes`, 27 bytes ``` [ (a,b) [ prime? ] filter ] ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQm1iSoVdQlJmbWqxQnFpYmpqXDGSBRYsS89KB7IKi1JKSSqCSvBKF7NSivNQcBWsuLmMFQ8P/0QoaiTpJmgrRCmAT7BViFdIyc0pSixRi/ycn5uQo6P0HAA "Factor – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes *+1 byte from @Jacob for informing me about the requirement for exclusive range* ``` rḢ'æ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJy4biiJ8OmIiwiIiwiMTBcbjIiXQ==) Finds all the primes between the first input and the second input (exclusive). ## Explanation ``` r # Get the range from [<input 1>, ..., <input 2>-1] Ḣ # Remove the first value (so it's exclusive on both ends) ' # of that range, filter.... æ # only those which are prime ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ÿ¦¨ʒp ``` [Try it online](https://tio.run/##yy9OTMpM/f//6I5Dyw6tODWp4P//aENDHVPLWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/ozsOLTu04tSkgv@1Ov@jow0NdUwtY3VAtDGQMtIxApMQtgmQNAGKxAIA). **Explanation:** ``` Ÿ # Convert the (implicit) input-pair to an inclusive list ¦¨ # Remove both the first and last item to make it an exclusive list ʒ # Filter it by: p # Check whether the number is a prime # (after which the filtered list is output implicitly) ``` [Answer] # [Perl 5](https://www.perl.org/), 48 bytes ``` sub{grep{(1x$_)!~/^1$|^(11+)\1+$/}1+pop.."@_"-1} ``` [Try it online!](https://tio.run/##K0gtyjH9r5Jm@7@4NKk6vSi1oFrDsEIlXlOxTj/OUKUmTsPQUFszxlBbRb/WULsgv0BPT8khXknXsPa/NZdDTmZxiYKtgppKmoappY6hoaY1V0FRZl6JghJYSsn6/7/8gpLM/Lzi/7q@ZaZ6hgYA "Perl 5 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` oV Åfj ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=b1YgxWZq&input=MTAgNTA) Essentially equivalent to [97.100.97.109's answer](https://codegolf.stackexchange.com/a/258219/108687), though developed independently. Gets the exclusive range by getting the inclusive range between \$[n\_1+1,n\_2-1]\$. -2 bytes thanks to Shaggy Explanation: ``` oV Åfj full program oV the inclusive range between the two inputs Å cut off the first and last elements f filter, keeping only those that j are prime ``` ## Japt, 5 bytes Inclusive range, which was banned after writing this ``` oV fj ``` ``` oV the range from input 1 to input 2 f filter, keeping only those that j are prime ``` [Answer] # [Arturo](https://arturo-lang.io), 35 bytes ``` $=>[select chop drop@&..&1=>prime?] ``` [Try it](http://arturo-lang.io/playground?zgMeW9) ``` $=>[ ; anonymous function select ; take elements from chop ; remove last element drop .. 1 ; remove first element @&..& ; inclusive input range, reified =>prime? ; that are prime ] ; end function ``` [Answer] # Java 10, 137 bytes ``` (a,b)->{var r=new java.util.Stack();int t=0,i;for(a^=b<a?b^(t=b=a):0;++a<b;){for(i=a;a%--i>0;);if(i<2)r.add(t<1?r.size():0,a);}return r;} ``` [Try it online.](https://tio.run/##XVDLbsIwELzzFatIlWwlsYDSQ3EMP9By4VgVaZ1HZQgG2RuqFuXbUycgNe1lpdmZWc3OHi@Y7otDl9foPbyisdcJgLFUugrzEjY9BNgHnWjI1OLFeIKcBQVg0k/NZZC0kzA8IZkcNmBBdQwTzdPV9YIOnLLl5@jIljA/MC57P6lpYmR1cgx3Sme41jtGSivky6mMY8y05NeeNgolPqSpWU1lsFbMZHPuBBYFo2y2dsKb75IFV4Jctq6kxllwsu1kn@3c6Dpku0e8nEwBx/At25Iz9uPtHfntUyo9sdkseXoe/vpdPI7xPJn/hf/YxRgu7uJxR0OAgR03eYuw/fJUHsWpIXEO4ai2DOMoiWIdR0uIYivyodz70bb7AQ) **Explanation:** ``` (a,b)->{ // Method with two integer parameters and List return-type var r=new java.util.Stack();// Result-list, starting empty int t=0,i; // Temp-integers for(a^=b<a? // If `b` is smaller than `a`: b^(t=b=a):0; // Set `t` to `a`, // and then swap `a` and `b` by using bitwise XORs ++a<b;){ // Loop in the range (a,b): for(i=a; // Set `i` to the current `a` a%--i>0;); // Decrease `i` before every iteration with `--i`, // and continue as long as `a` is NOT divisible by `i` if(i<2) // If `i` is 1 after the loop (which means `a` is a prime): r.add(t<1? // If `t` is 0 (which means `a` was already smaller than // or equal to `b`): r.size() // Append to the result-list : // Else (`a` was larger than `b`): 0, // Prepend to the result-list instead a);} // The current prime `a` return r;} // And finally return the result-list ``` Unlike [my 05AB1E answer](https://codegolf.stackexchange.com/a/258224/52210), the exclusive range is actually an advantage for my Java answer, since checking whether a number \$n\geq2\$ is a prime is 3 bytes shorter than checking whether a number \$n\geq1\$ is a prime ([see section *Primes* in this Java tip of mine](https://codegolf.stackexchange.com/a/100149/52210)). --- Since I was curious: using an `IntStream` is apparently **~~144~~ 143 bytes**: ``` a->b->java.util.stream.IntStream.iterate(a<b?a+1:a-1,i->b<a?i-1:i+1).limit(a<b?b+~a:a>b?a+~b:0).filter(k->{int i=k;for(;k%--i>0;);return i<2;}) ``` -1 byte thanks to *@Neil*. [Try it online.](https://tio.run/##lVE9a8MwFNzzK4ShIGFbxGk71HacoVAotFPG0uHJkcOL5Q/s59AQkr/uyq6hSUuHLuJOd3o6nXawB3@3yfvUQNuyV8DyOGOsJSBM2c6qsiM0MuvKlLAq5dME4ueS9FY33n9NLTUaCmmV9YiShGVs2YOfKD/52yaRdAOkOcRqBW4Qgh94aA/FsEI/CNENhDRYII0O5Z4hhGSwnlU4FzJDYwfw3E@OWBLDZR5lVcOj/Mb3MZlHImo0dU3JMF5EJ9FHM1tD3Slja5ja2Fe4YYVtiNtIWG7f3kEMZTFGuiUeBN79g4iuNm4v@cJbXNMf6t0lvZvMp9n3d4wBRnV4AnjDqqYI60NLupBVR7K24ciUHFzHc1zlOiFz3ExCXZsDBzEBJaSqPvSGC5lWxuiU@K/2H7@EqmklVS9oLxZiSnXqPwE) **Explanation:** ``` a->b-> // Method with two integer parameters and IntStream return java.util.stream.IntStream // Create an IntStream .iterate(a<b? // If `a` is smaller than `b` a+1 // Start at `a+1` : // Else (a>=b): a-1, // Start at `a-1` instead i-> // In every iteration: b<a? // If `b` is smaller than `a`: i-1 // Decrement once : // Else (b>=a) i+1) // Increment once instead .limit(a<b? // If `a` is smaller than `b`: b+~a // Do `b-a-1` amount of iterations :a>b? // Else-if `a` is larger than `b`: a+~b // Do `a-b-1` amount of iterations : // Else (`a` equals `b`): 0) // Make the IntStream empty .filter(k->{ // Then filter this IntStream by: int i=k;for(;k%--i>0;);return i<2;}) // Primes-check similar as above ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~62~~ 52 bytes ``` .+ $* O` M!&`(?<=(1+)¶1+)1+\1 A`^(11+)\1+$ O` 1+ $.& ``` [Try it online!](https://tio.run/##K0otycxL/K@qEZyg819Pm0tFi8s/gctXUS1Bw97GVsNQW/PQNiBhqB1jyOWYEKdhCOTEGGqrgFQZApXrqf3/b2ioY2rJxQWkjLm4jHSMQASYZcLFZaJjBAA "Retina 0.8.2 – Try It Online") Takes inputs on separate lines but link is to test suite that splits on comma for convenience. Explanation: ``` .+ $* ``` Convert to unary. ``` O` ``` Sort into order. ``` M!&`(?<=(1+)¶1+)1+\1 ``` Generate the exclusive range. ``` A`^(11+)\1+$ ``` Remove any composite numbers. ``` O` ``` Sort into order. ``` 1+ $.& ``` Convert any remaining numbers to decimal. [Answer] # Excel, 122 bytes ``` =LET( a,A1, b,B1, c,a>b, d,SEQUENCE(IF(c,a,b)-1), SORT(FILTER(d,(d>IF(c,b,a))*MMULT(N(MOD(d,TRANSPOSE(d))=0),d^0)=2,""),,-1^c) ) ``` Inputs in cells `A1` and `B1`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` IΦ…⊕⌊θ⌈θ⬤…²ι﹪ιλ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwy0zpyS1SCMoMS89VcMzL7koNTc1ryQ1RcM3My8ztzRXo1BTU0fBN7ECwXHMyYGqN9JRyATJ5qeU5uRrZOoo5GiCgPX//9HRxjoKhoaxsf91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list. Explanation: ``` … Range from θ Input list ⌊ Minimum ⊕ Incremented θ To input list ⌈ Maximum Φ Filtered where … Range from ² Literal integer `2` ι To current value ⬤ All members satisfy ι Outer value ﹪ Modulo i.e. is not divisible by λ Inner value I Cast to string Implicitly print each prime on its own line ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` æRḟ, ``` A dyadic Link that accepts the one bound on the left and the other bound on the right and yields a list of primes strictly between the bounds. **[Try it online!](https://tio.run/##y0rNyan8///wsqCHO@br/P//3/S/oTkA "Jelly – Try It Online")** ### How? ``` æRḟ, - Link: integer, A; integer, B æR - inclusive prime range -> list of primes between A and B, inclusive , - pair -> [A, B] ḟ - filter discard -> list of primes between A and B, exclusive ``` [Answer] # Regex (ECMAScript 2018), ~~54~~ ~~53~~ 48 bytes ``` x(?=(x+))(?<=(?=.*\b(?!\1)x+\b).*)(?!(xx+)\2+\b) ``` [Try it online!](https://tio.run/##bVC9UuMwGOz9FLYbfUJCgwwU4BOurkhDcVeemUGxFaMbRTaSQjQJae8B7hF5kSDDMZPiCo1Wu9/Prn7LF@k7p6dwbsdeHb24qJ34oYbvcYKfwWk7MCe3j8cIjYBIMIbmm0iYnbVLaIqW40jaJWZnSSggpoq2monjI/NGdwo4PeeYogHh2qnnjXYKkFOyN9oqhFmXcFALG5RbyVS@13bahNvJjZ3ynvnQa3vAbLSAPjqoEXf7QRjmJ6MDIJrm6hUMzCg7hKdCVK@v2t/Le5Biks7Po2H4dfGA8ZewPBV4EnB4cuO2XNgXaXSffzrIS2LqExvjJrCt00EB@Aa1Ft0ihIkhKH/78zdPLrzgdRRlLJlTUwoFEpOSluSEWeJ6NTrYpU@GtXBMRdVBxLgQwm6MqXeC4332/6W7BuWfO9fJ9L@4H9mLdYr3RThmpA8L26tIyOGAj5zT65vs@oZyniV8mV3OqKJVOvNjvq@yK1q9Aw "JavaScript (Node.js) – Try It Online") Takes its input in unary, as two strings of `x` characters whose lengths represent the two numbers, joined/separated by a `,`. Returns its output in unary as the list of matches' `\1` captures, whose lengths represent the prime numbers in the range. *-1 byte thanks to Neil, by leaving out an unneeded ≥2 assertion* *-5 bytes by handling ascending and descending ranges all in one go rather than separately* ``` x # tail -= 1; force the top end of the range to be excluded; # X = tail (?=(x+)) # Capture \1 = tail (?<= # Variable-length lookbehind, evaluated right-to-left: (?= # Lookahead (evaluated left-to-right): .*\b # Skip tail over to a word boundary, which could be the # beginning or end of the string, or either side of a comma. (?!\1) # Assert tail < \1, i.e. along with the word boundary # assertion above, that this is the bottom end of the range, # implying \1 was captured from the upper end of the range. x+\b # Assert tail >= 1 ) .* # Skip all the way to the beginning, then evaluate the above ) (?!(xx+)\2+\b) # Assert tail is not composite; tail > 1 was already asserted # above, so along with that, this asserts tail is prime. ``` [Answer] # [Python](https://www.python.org), 67 bytes ``` lambda a,b:[n for n in range(a+1,b)if all(n%m for m in range(2,n))] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY5NasMwEEb3PsVsiiU6NtVPcB1INj1G4oVM7EYgy0JWoblEL9BNoLR3ym0qyymuVp94b76Zzx93CefRXr_63fH7LfTF8-3FqKE9KVDYbg8W-tGDBW3BK_vaEfXIsKW6B2UMsQ9D4sPKOVpKm3vVxwyNtt3MR9dZ8kRL36kToeXkjA4zmwjdZhCfQfCwS_5CSQ7FHnKa6DvCJdJBOaJtQDDlFLx2f02ELprzkZJZRsiPodjnCH36U7pcdb2dGYNNPXcfmEBWIauRC-Q1CoaiQslQCpQVbkSTRVdAcpuMA4c1i39Z3nMckKu0LPwF) The challenge has now been edited to allow *either* ascending or descending ranges, so this only supports ascending. [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$5\log\_{256}(96)\approx\$ 4.12 bytes ``` :ZTgN ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhZLraJC0v0g7AUwytSSy9AQwgEA) Takes the inputs in reverse order. #### Explanation ``` :ZTgN # Inputs: x and y : # Push [x..y) ZT # Remove first item gN # Filter for primes ``` [Answer] # Mathematica (Wolfram Language), 61 Bytes I'm new at this, but I thought this is a good problem to practice on. ``` Select[Range[First[Sort[{##}]]+1,Last[Sort[{##}]]-1],PrimeQ]& ``` [Try it out online](https://tio.run/##y00syUjNTSzJTE78n2b7Pzg1JzW5JDooMS89Ndots6i4JDo4v6gkulpZuTY2VttQxycRVUjXMFYnoCgzNzUwVu0/kJFXEq2sa5fm4KAcq1YXnJyYV1fNVW1oqGNqWasDohWMgbSRjhGYhLBNgKQJUISr9j8A) This is a functional implementation, which takes a list of two numbers, orders them, and generates all integers in the open interval (input 1, input 2). Then the select function picks out all the prime elements of that interval. I'll keep thinking about how to shorten this code. EDIT: Added all the test cases on tio.run, and implemented Range function. ]
[Question] [ Your task is to make a program in `L` that takes `n` as an input number, output a program `p` in `L` that prints its own first `n` characters. ## Rules * The program `p` has to be irreducible, See an example below. * **PAY ATTENTION TO THIS RULE:** If a program takes an input as `n`, the first `n` characters of the output would be the same as the first `n` characters of the program taking `n + 1` as input. * Standard loopholes apply * You have to make a full program. * A trailing newline of the output of the program `p` is allowed if the first `n` characters of the program `p` doesn't have a newline ## Example I'm using pseudocode as `L` if `n` = 10, an example of `p` would be ``` PRINT "PRINT \"PRI" ``` but not ``` // comment PRINT "// comment" ``` because it breaks the first rule above (if you removed `com` and still makes the same output). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so you have to make your program shortest as possible (in bytes). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 1 byte ``` N ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9nnX//5sAAA "Charcoal – Try It Online") Port of @Ausername's Vyxal answer. Explanation: Simply outputs `n` `-`s; strings of printable ASCII need no delimiter in Charcoal, so as a program, it just prints the string of `-`s, i.e. itself. [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), ~~20~~ 18 bytes ``` say 1 x get,".put" ``` [Try it online!](https://tio.run/##K0gtyjH7/784sVLBUKFCIT21REdJr6C0ROn/f1MA "Raku – Try It Online") Outputs a number with `n` digits followed by a `.put` [Answer] # [Python 3](https://docs.python.org/3/), 48 bytes ``` print('a'*int(input())+'=1;print(locals()[-1])') ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQz1RXQtEZ@YVlJZoaGpqq9saWkOkcvKTE3OKNTSjdQ1jNdU1//83BQA "Python 3 – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes ``` \1* ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJcXDEqIiwiIiwiNCJd) Literally prints that many 1s. [Answer] # [Ruby](https://www.ruby-lang.org/), 26 bytes ``` $><<?1*gets.to_i+'=>x;p x' ``` Uses the Ruby 3 pattern match syntax to bind the integer to `x`. [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWu1TsbGzsDbXSU0uK9Ury4zO11W3tKqwLFCrUIQqg6hYsNIUwAA) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 13 bytes ``` .+ *KKK KK K` ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0@bS8vb25sLhBL@/zcBAA "Retina – Try It Online") Explanation: Outputs a string of length `n+2` alternating between `K` and ```. This creates a program in Retina that outputs the part of the string after the `K`` which is also equal to the first `n` characters of the program. Retina can also execute the resulting program for you automatically: [Try it online!](https://tio.run/##K0otycxLNPyvpFSn4Z7wX0@bS8vb25sLhBL@/zcBAA "Retina – Try It Online") Or see both the program and its output: [Try it online!](https://tio.run/##K0otycxLNPyvpFQXo@Ge8F9Pm0vL29ubC4QS/v83AQA "Retina – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 1¸sиJ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f8NCO4gs7vP7/NwUA "05AB1E – Try It Online") Sort-of port of [emanresu A's Vyxal answer](https://codegolf.stackexchange.com/a/255303/114446): ``` 1¸sиJ # Implicit input STACK: 1¸ # Push ['1'] ['1'], 5 sи # Repeat input number of times ['1', '1', '1', '1', '1'] J # Join by '' '11111' # Implicit output ``` [Answer] # [Julia 1.0](http://julialang.org/), 36 bytes ``` print('1'^parse(Int,ARGS[]),|>,show) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/v6AoM69EQ91QPa4gsag4VcMzr0THMcg9ODpWU6fGTqc4I79c8////6YA "Julia 1.0 – Try It Online") port of [Jo King's answer](https://codegolf.stackexchange.com/a/255304/98541) will print something like `1111|>show` (equivalent to `show(1111)`) [Answer] # [///](https://esolangs.org/wiki////), 65 bytes ``` /9/8*//8/7*//7/6*//6/5*//5/4*//4/3*//3/2*//2/1*//1/0*//*0/9*//0// ``` [Try it online!](https://tio.run/##DcwpDsAwDAVR3qOEjJ3VOU5BpYKy3F/uJ2/YnO8@73OSC5JNFAiWXEw5GXLQZafJRpUVl47JYmzFdPDIHw "/// – Try It Online") Converts decimal to unary. # [///](https://esolangs.org/wiki////), 0 bytes [Try it online!](https://tio.run/##K85JLM5ILf6vz6Wv//@/Fgb4DwA "/// – Try It Online") Takes input as unary. For me, That's cheating. [Answer] # [Bash](https://www.gnu.org/software/bash/), 25 bytes ``` eval echo\ echo\$_{0..$1} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70kKbE4Y8GCpaUlaboWO1PLEnMUUpMz8mMgpEp8tYGenophLUQeqmxptJKpUiyUAwA) ]
[Question] [ Given an input string, output at random the unique combinations with repetition of the characters in the input string, from length 1 up to the length of the input string, with an equal chance of each one occurring. Example: given the input `abcd` (or any combination thereof of the four characters `a`,`b`,`c`,`d`) , there is an equal chance of outputting: ``` a b c d aa ab ac ad ba bb bc bd ca cb cc cd da db dc dd aaa aab aac aad aba abb abc abd aca acb acc acd ada adb adc add baa bab bac bad bba bbb bbc bbd bca bcb bcc bcd bda bdb bdc bdd caa cab cac cad cba cbb cbc cbd cca ccb ccc ccd cda cdb cdc cdd daa dab dac dad dba dbb dbc dbd dca dcb dcc dcd dda ddb ddc ddd aaaa aaab aaac aaad aaba aabb aabc aabd aaca aacb aacc aacd aada aadb aadc aadd abaa abab abac abad abba abbb abbc abbd abca abcb abcc abcd abda abdb abdc abdd acaa acab acac acad acba acbb acbc acbd acca accb accc accd acda acdb acdc acdd adaa adab adac adad adba adbb adbc adbd adca adcb adcc adcd adda addb addc addd baaa baab baac baad baba babb babc babd baca bacb bacc bacd bada badb badc badd bbaa bbab bbac bbad bbba bbbb bbbc bbbd bbca bbcb bbcc bbcd bbda bbdb bbdc bbdd bcaa bcab bcac bcad bcba bcbb bcbc bcbd bcca bccb bccc bccd bcda bcdb bcdc bcdd bdaa bdab bdac bdad bdba bdbb bdbc bdbd bdca bdcb bdcc bdcd bdda bddb bddc bddd caaa caab caac caad caba cabb cabc cabd caca cacb cacc cacd cada cadb cadc cadd cbaa cbab cbac cbad cbba cbbb cbbc cbbd cbca cbcb cbcc cbcd cbda cbdb cbdc cbdd ccaa ccab ccac ccad ccba ccbb ccbc ccbd ccca cccb cccc cccd ccda ccdb ccdc ccdd cdaa cdab cdac cdad cdba cdbb cdbc cdbd cdca cdcb cdcc cdcd cdda cddb cddc cddd daaa daab daac daad daba dabb dabc dabd daca dacb dacc dacd dada dadb dadc dadd dbaa dbab dbac dbad dbba dbbb dbbc dbbd dbca dbcb dbcc dbcd dbda dbdb dbdc dbdd dcaa dcab dcac dcad dcba dcbb dcbc dcbd dcca dccb dccc dccd dcda dcdb dcdc dcdd ddaa ddab ddac ddad ddba ddbb ddbc ddbd ddca ddcb ddcc ddcd ddda dddb dddc dddd ``` Example: given the input `efgh` (or any combination thereof of the four characters `e`,`f`,`g`,`h`), there is an equal chance of outputting: ``` e f g h ee ef eg eh fe ff fg fh ge gf gg gh he hf hg hh eee eef eeg eeh efe eff efg efh ege egf egg egh ehe ehf ehg ehh fee fef feg feh ffe fff ffg ffh fge fgf fgg fgh fhe fhf fhg fhh gee gef geg geh gfe gff gfg gfh gge ggf ggg ggh ghe ghf ghg ghh hee hef heg heh hfe hff hfg hfh hge hgf hgg hgh hhe hhf hhg hhh eeee eeef eeeg eeeh eefe eeff eefg eefh eege eegf eegg eegh eehe eehf eehg eehh efee efef efeg efeh effe efff effg effh efge efgf efgg efgh efhe efhf efhg efhh egee egef egeg egeh egfe egff egfg egfh egge eggf eggg eggh eghe eghf eghg eghh ehee ehef eheg eheh ehfe ehff ehfg ehfh ehge ehgf ehgg ehgh ehhe ehhf ehhg ehhh feee feef feeg feeh fefe feff fefg fefh fege fegf fegg fegh fehe fehf fehg fehh ffee ffef ffeg ffeh fffe ffff fffg fffh ffge ffgf ffgg ffgh ffhe ffhf ffhg ffhh fgee fgef fgeg fgeh fgfe fgff fgfg fgfh fgge fggf fggg fggh fghe fghf fghg fghh fhee fhef fheg fheh fhfe fhff fhfg fhfh fhge fhgf fhgg fhgh fhhe fhhf fhhg fhhh geee geef geeg geeh gefe geff gefg gefh gege gegf gegg gegh gehe gehf gehg gehh gfee gfef gfeg gfeh gffe gfff gffg gffh gfge gfgf gfgg gfgh gfhe gfhf gfhg gfhh ggee ggef ggeg ggeh ggfe ggff ggfg ggfh ggge gggf gggg gggh gghe gghf gghg gghh ghee ghef gheg gheh ghfe ghff ghfg ghfh ghge ghgf ghgg ghgh ghhe ghhf ghhg ghhh heee heef heeg heeh hefe heff hefg hefh hege hegf hegg hegh hehe hehf hehg hehh hfee hfef hfeg hfeh hffe hfff hffg hffh hfge hfgf hfgg hfgh hfhe hfhf hfhg hfhh hgee hgef hgeg hgeh hgfe hgff hgfg hgfh hgge hggf hggg hggh hghe hghf hghg hghh hhee hhef hheg hheh hhfe hhff hhfg hhfh hhge hhgf hhgg hhgh hhhe hhhf hhhg hhhh ``` Example: given the input `ijkl` (or any combination thereof of the four characters `i`,`j`,`k`,`l`), there is an equal chance of outputting: ``` i j k l ii ij ik il ji jj jk jl ki kj kk kl li lj lk ll iii iij iik iil iji ijj ijk ijl iki ikj ikk ikl ili ilj ilk ill jii jij jik jil jji jjj jjk jjl jki jkj jkk jkl jli jlj jlk jll kii kij kik kil kji kjj kjk kjl kki kkj kkk kkl kli klj klk kll lii lij lik lil lji ljj ljk ljl lki lkj lkk lkl lli llj llk lll iiii iiij iiik iiil iiji iijj iijk iijl iiki iikj iikk iikl iili iilj iilk iill ijii ijij ijik ijil ijji ijjj ijjk ijjl ijki ijkj ijkk ijkl ijli ijlj ijlk ijll ikii ikij ikik ikil ikji ikjj ikjk ikjl ikki ikkj ikkk ikkl ikli iklj iklk ikll ilii ilij ilik ilil ilji iljj iljk iljl ilki ilkj ilkk ilkl illi illj illk illl jiii jiij jiik jiil jiji jijj jijk jijl jiki jikj jikk jikl jili jilj jilk jill jjii jjij jjik jjil jjji jjjj jjjk jjjl jjki jjkj jjkk jjkl jjli jjlj jjlk jjll jkii jkij jkik jkil jkji jkjj jkjk jkjl jkki jkkj jkkk jkkl jkli jklj jklk jkll jlii jlij jlik jlil jlji jljj jljk jljl jlki jlkj jlkk jlkl jlli jllj jllk jlll kiii kiij kiik kiil kiji kijj kijk kijl kiki kikj kikk kikl kili kilj kilk kill kjii kjij kjik kjil kjji kjjj kjjk kjjl kjki kjkj kjkk kjkl kjli kjlj kjlk kjll kkii kkij kkik kkil kkji kkjj kkjk kkjl kkki kkkj kkkk kkkl kkli kklj kklk kkll klii klij klik klil klji kljj kljk kljl klki klkj klkk klkl klli kllj kllk klll liii liij liik liil liji lijj lijk lijl liki likj likk likl lili lilj lilk lill ljii ljij ljik ljil ljji ljjj ljjk ljjl ljki ljkj ljkk ljkl ljli ljlj ljlk ljll lkii lkij lkik lkil lkji lkjj lkjk lkjl lkki lkkj lkkk lkkl lkli lklj lklk lkll llii llij llik llil llji lljj lljk lljl llki llkj llkk llkl llli lllj lllk llll ``` This by definition also means that every indiviual character within the string too has equal probability. All characters in the input are distinct. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 5 bytes ``` ṗJẎQX ``` A monadic Link accepting a list of characters which yields a list of characters. **[Try it online!](https://tio.run/##y0rNyan8///hzuleD3f1BUb8//8/MTEpGQA "Jelly – Try It Online")** ### How? ``` ṗJẎQX - Link list of characters e.g. aabc J - range of length [1,2,3,4] ṗ - Cartesian power (vectorises) [[a,a,b,c],[aa,aa,ab,ac,aa,aa,ab,ac,ba,ba,bb,bc,ca,ca,cb,cc],[aaa,aaa,aab,aac,aaa,aaa,aab,aac,aba,aba,abb,abc,aca,aca,acb,acc,aaa,aaa,aab,aac,aaa,aaa,aab,aac,aba,aba,abb,abc,aca,aca,acb,acc,baa,baa,bab,bac,baa,baa,bab,bac,bba,bba,bbb,bbc,bca,bca,bcb,bcc,caa,caa,cab,cac,caa,caa,cab,cac,cba,cba,cbb,cbc,cca,cca,ccb,ccc],[aaaa,aaaa,aaab,aaac,aaaa,aaaa,aaab,aaac,aaba,aaba,aabb,aabc,aaca,aaca,aacb,aacc,aaaa,aaaa,aaab,aaac,aaaa,aaaa,aaab,aaac,aaba,aaba,aabb,aabc,aaca,aaca,aacb,aacc,abaa,abaa,abab,abac,abaa,abaa,abab,abac,abba,abba,abbb,abbc,abca,abca,abcb,abcc,acaa,acaa,acab,acac,acaa,acaa,acab,acac,acba,acba,acbb,acbc,acca,acca,accb,accc,aaaa,aaaa,aaab,aaac,aaaa,aaaa,aaab,aaac,aaba,aaba,aabb,aabc,aaca,aaca,aacb,aacc,aaaa,aaaa,aaab,aaac,aaaa,aaaa,aaab,aaac,aaba,aaba,aabb,aabc,aaca,aaca,aacb,aacc,abaa,abaa,abab,abac,abaa,abaa,abab,abac,abba,abba,abbb,abbc,abca,abca,abcb,abcc,acaa,acaa,acab,acac,acaa,acaa,acab,acac,acba,acba,acbb,acbc,acca,acca,accb,accc,baaa,baaa,baab,baac,baaa,baaa,baab,baac,baba,baba,babb,babc,baca,baca,bacb,bacc,baaa,baaa,baab,baac,baaa,baaa,baab,baac,baba,baba,babb,babc,baca,baca,bacb,bacc,bbaa,bbaa,bbab,bbac,bbaa,bbaa,bbab,bbac,bbba,bbba,bbbb,bbbc,bbca,bbca,bbcb,bbcc,bcaa,bcaa,bcab,bcac,bcaa,bcaa,bcab,bcac,bcba,bcba,bcbb,bcbc,bcca,bcca,bccb,bccc,caaa,caaa,caab,caac,caaa,caaa,caab,caac,caba,caba,cabb,cabc,caca,caca,cacb,cacc,caaa,caaa,caab,caac,caaa,caaa,caab,caac,caba,caba,cabb,cabc,caca,caca,cacb,cacc,cbaa,cbaa,cbab,cbac,cbaa,cbaa,cbab,cbac,cbba,cbba,cbbb,cbbc,cbca,cbca,cbcb,cbcc,ccaa,ccaa,ccab,ccac,ccaa,ccaa,ccab,ccac,ccba,ccba,ccbb,ccbc,ccca,ccca,cccb,cccc] Ẏ - tighten [a,a,b,c,aa,aa,ab,ac,aa,aa,ab,ac,ba,ba,bb,bc,ca,ca,cb,cc,aaa,aaa,aab,aac,aaa,aaa,aab,aac,aba,aba,abb,abc,aca,aca,acb,acc,aaa,aaa,aab,aac,aaa,aaa,aab,aac,aba,aba,abb,abc,aca,aca,acb,acc,baa,baa,bab,bac,baa,baa,bab,bac,bba,bba,bbb,bbc,bca,bca,bcb,bcc,caa,caa,cab,cac,caa,caa,cab,cac,cba,cba,cbb,cbc,cca,cca,ccb,ccc,aaaa,aaaa,aaab,aaac,aaaa,aaaa,aaab,aaac,aaba,aaba,aabb,aabc,aaca,aaca,aacb,aacc,aaaa,aaaa,aaab,aaac,aaaa,aaaa,aaab,aaac,aaba,aaba,aabb,aabc,aaca,aaca,aacb,aacc,abaa,abaa,abab,abac,abaa,abaa,abab,abac,abba,abba,abbb,abbc,abca,abca,abcb,abcc,acaa,acaa,acab,acac,acaa,acaa,acab,acac,acba,acba,acbb,acbc,acca,acca,accb,accc,aaaa,aaaa,aaab,aaac,aaaa,aaaa,aaab,aaac,aaba,aaba,aabb,aabc,aaca,aaca,aacb,aacc,aaaa,aaaa,aaab,aaac,aaaa,aaaa,aaab,aaac,aaba,aaba,aabb,aabc,aaca,aaca,aacb,aacc,abaa,abaa,abab,abac,abaa,abaa,abab,abac,abba,abba,abbb,abbc,abca,abca,abcb,abcc,acaa,acaa,acab,acac,acaa,acaa,acab,acac,acba,acba,acbb,acbc,acca,acca,accb,accc,baaa,baaa,baab,baac,baaa,baaa,baab,baac,baba,baba,babb,babc,baca,baca,bacb,bacc,baaa,baaa,baab,baac,baaa,baaa,baab,baac,baba,baba,babb,babc,baca,baca,bacb,bacc,bbaa,bbaa,bbab,bbac,bbaa,bbaa,bbab,bbac,bbba,bbba,bbbb,bbbc,bbca,bbca,bbcb,bbcc,bcaa,bcaa,bcab,bcac,bcaa,bcaa,bcab,bcac,bcba,bcba,bcbb,bcbc,bcca,bcca,bccb,bccc,caaa,caaa,caab,caac,caaa,caaa,caab,caac,caba,caba,cabb,cabc,caca,caca,cacb,cacc,caaa,caaa,caab,caac,caaa,caaa,caab,caac,caba,caba,cabb,cabc,caca,caca,cacb,cacc,cbaa,cbaa,cbab,cbac,cbaa,cbaa,cbab,cbac,cbba,cbba,cbbb,cbbc,cbca,cbca,cbcb,cbcc,ccaa,ccaa,ccab,ccac,ccaa,ccaa,ccab,ccac,ccba,ccba,ccbb,ccbc,ccca,ccca,cccb,cccc] Q - de-duplicate [a,b,c,aa,ab,ac,ba,bb,bc,ca,cb,cc,aaa,aab,aac,aba,abb,abc,aca,acb,acc,baa,bab,bac,bba,bbb,bbc,bca,bcb,bcc,caa,cab,cac,cba,cbb,cbc,cca,ccb,ccc,aaaa,aaab,aaac,aaba,aabb,aabc,aaca,aacb,aacc,abaa,abab,abac,abba,abbb,abbc,abca,abcb,abcc,acaa,acab,acac,acba,acbb,acbc,acca,accb,accc,baaa,baab,baac,baba,babb,babc,baca,bacb,bacc,bbaa,bbab,bbac,bbba,bbbb,bbbc,bbca,bbcb,bbcc,bcaa,bcab,bcac,bcba,bcbb,bcbc,bcca,bccb,bccc,caaa,caab,caac,caba,cabb,cabc,caca,cacb,cacc,cbaa,cbab,cbac,cbba,cbbb,cbbc,cbca,cbcb,cbcc,ccaa,ccab,ccac,ccba,ccbb,ccbc,ccca,cccb,cccc] X - uniform random choice ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` ā€ã˜ÙΩ ``` [Try it online!](https://tio.run/##ARsA5P9vc2FiaWX//8SB4oKsw6PLnMOZzqn//2FhYWI "05AB1E – Try It Online") **Explanation** ``` ā # push [1 ... len(input)] €ã # apply repeated cartesian product on each and input ˜ # flatten Ù # remove duplicates Ω # pick random string ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~35 33~~ 28 bytes *-2 bytes thanks to nwellnhof* ``` {[~] roll .rand+1,$_}o*.comb ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OrouVqEoPydHQa8oMS9F21BHJb42X0svOT836b81V3FipUKahlJiUrKSJjIvBcj9DwA "Perl 6 – Try It Online") This challenge keeps changing a lot. ### Explanation: ``` { }o*.comb # Anonymous code block turning input into chars $_ # From the input .rand+1, # Take a random number from 1 to length of list roll # Of characters [~] # And join them into a string ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` ⊇ᶠbṛ;?ṛw ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FX@8NtC5Ie7pxtbQ8kyv//V0pMSk5RAgA "Brachylog – Try It Online") Prints output directly instead of constraining the output variable, because for some reason this actually fails without the `w` at the end. Originally this used `≠` and the `∈&` backtracking hack I used [to implement bogosort](https://codegolf.stackexchange.com/a/182062/85334), but I realized that it would be far saner to just use `b` instead. ``` w Print ṛ a random one of ? the input ; or ṛ a random element of ᶠ every ⊇ sublist of the input b except the first one (which would be the input). ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~111~~ 121 bytes ``` lambda s:choice(g(list(set(s)),len(s))) from random import * g=lambda s,n:s+(n>1and[c+k for k in g(s,n-1)for c in s]or[]) ``` [Try it online!](https://tio.run/##bY49DoMwDIV3TuEtSZsOtBsSvQhlcAKBCHBQkqWnT0Pp39DBes/Pn2Wv9zg6OidT39KMi@oQQqVHZ3XPBz7bEHnocwkh5542FYXxbgGP1GWxy@p8hEMx1O91SVU4crqWmWj0cQLjPExgCQaeh6dSbIHegtA637Qird5SBMMZomKi2Nuf83u@v/Dy/yCFX@jpP1DDkEmmWCsvIj0A "Python 2 – Try It Online") Takes any iterable (list, set, string, etc.) of either distinct characters or non-distinct characters as input. Outputs a non-empty string with the required distribution. `g` is a recursive function to generate a list of compliant strings. [Answer] # [R](https://www.r-project.org/), ~~72~~ 64 bytes -8 bytes thanks to Giuseppe. ``` S=sample;S(t<-unique(s<-scan(,"")),S(n<-seq(s),p=length(t)^n),T) ``` [Try it online!](https://tio.run/##VYtBCsMgEEX3PUWY1QyMXiDmFHZdsFaTQDJJqkKg9OzGLrt4i//4711jZ1QXi/g8b4InfZJ38ue01nRWOyS37kvoLWajisxHCZiM@t2RAYjYorQdDkzE@7AEGfOEmR5CfKf6vUX0CA4Yng3feLWqXg "R – Try It Online") Input and output are vectors of characters. All possible outputs have equal probability. Explanation (ungolfed version): ``` s<-scan(,"") # takes input as vector of characters n<-length(s) t<-unique(s) sample(t, # sample uniformly at random from the list of unique characters sample(n,p=length(t)^(1:n)), # with length k in 1..n chosen randomly such that P[k] is proportional to length(t)^k T) # the sampling is with replacement ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes ``` ""<>#&@*RandomChoice@*Subsets@*Characters ``` [Try it online!](https://tio.run/##DcVBCoAgEADAv2zQQYI@ULHQB6JesOmaVhrodorebs1lAonjQOI1FdsXgG6oalQzRXOF0V1eM6rlXjNLRjU6SqSFUy5T8lFQ2RYfoFUbaIDt5v78fpzwlg8 "Wolfram Language (Mathematica) – Try It Online") [Answer] ## Java 131 bytes ``` void k(String a){a.chars().forEach(v->{int z=(int)(Math.random()*(a.length()+1));if(z<a.length())System.out.print(a.charAt(z));});} ``` [Answer] # Pyth - 7 bytes ``` Os^LQSl O Random choice s Collapse list ^L Map cartesian power Q Input S 1-indexed range l Length (Q implicit) Input ``` [Try it online](http://pyth.herokuapp.com/?code=Os%5ELQSl&test_suite=1&test_suite_input=%22abcd%22%0A%22efgh%22%0A%22ijkl%22&debug=0). [Try it online without random pick to see all possible options](http://pyth.herokuapp.com/?code=s%5ELQSl&test_suite=1&test_suite_input=%22abcd%22%0A%22efgh%22%0A%22ijkl%22&debug=0). [Answer] # [Haskell](https://www.haskell.org/), ~~143~~ 126 bytes -7 bytes thanks to [@Laiconi](https://codegolf.stackexchange.com/users/56433/laikoni), additional improvement (which I need to fully understand first) in the comments ``` import Control.Monad import System.Random f a|c<-concat[replicateM x a|x<-[1..length a]]=randomRIO(0,length c-1)>>=print.(c!!) ``` [Try it online!](https://tio.run/##LYuxCoMwFAB3v@LppNCEuhuXTh2kYEdxeI2xBpOXEDNY6L@nUtyOO27BbVXGpKStdyHCzVEMzvDOEU7ZKZ@fLSrLe6TJ2WwG/MqGSUcS4xCUN/oA1cF@hL1hQ825UfSOC@A4ivC/@vujvF5OLVldta3wQVPkpczzKlnUBAJmKPAli/QD "Haskell – Try It Online") --- [Original](https://tio.run/##LYwxC4MwEEZ3f8UpHVqooe46deogBTuKwzWeNZjcSQzUQv97KsXtfe@DN@IykbUxGjeLD3AVDl6sqoWxT3b5@CyBnGqQe3HJAFj1kgCYMvd/1dzux8vZEr/CCDovTgDbPXvD4aDT1GzjPZIn0JUW1hhaT7M1G1ANK@B3hTJvC6X2BHZddGgYKhggw6fO4g8 "Haskell – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~68~~ 65 bytes ``` f(s,i)char*s;{for(;i<strlen(s);i++)rand()&1?putc(s[i],stdout):0;} ``` [Try it online!](https://tio.run/##dY3RSgMxEEWf268YtiCJXWWLSKsp@iHqQ0yyuwNJZklmUSn99jWt@KBsYZ7OOcw1N50x0wqj8aN1sM9skW77p@Uf5PH9P0sYu8KmVuQapel1us7q0FISCk/auyiyVLhey6SjFfJq8zyMbER@wbe6/KSR5WOjjlPQGIU8LAHyuWQMTjRSqkJaUfXOe4IPSt5WdSPVYjGUbS7mNVa/EfeYoZyO4D51GLz7aWfSM4KOmGDTXP54d7992FUnOWd1wE7DYMBQCGQpXd7j9AXIQNFjdLN7x@kb "C (gcc) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes ``` ≔Φθ⁼κ⌕θιη≔⊕‽ΣEθXLη⊕κζWζ«§ηζ≔÷⊖ζLηζ ``` [Try it online!](https://tio.run/##TY1BCoMwFETXeoosf8CeoCvBCkIL0p4gNR8TjN8aoxZLz57GIrazHN68qZSwVSeM9@kw6Jog18ahhT5hp34UZoAmYbkmuTaac54wxY/xBhdUWWyRHEq4CpJdC7exhYt4rHjZzcF0RqqdAhWW/3jDv0nYEnSz0gYZLJy94qi0mhykriCJT1ArEZBov3SZnrREyPBnW4JoP9qkb@@FEHd/mMwH "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔Φθ⁼κ⌕θιη ``` Extract the unique characters of the input. Let's call the number of unique characters `n`. ``` ≔⊕‽ΣEθXLη⊕κζ ``` Calculate the number of combinations for each possible length and take the sum. Then, pick a random number between 1 and this number (inclusive). This ensures that all combinations are equally likely (within the accuracy of the random number generator). ``` Wζ«§ηζ≔÷⊖ζLηζ ``` Convert the number into bijective base `n`, using the unique characters as the digits. [Answer] # [MATLAB](https://www.mathworks.com/products/matlab.html) / [Octave](https://www.gnu.org/software/octave/), 110 bytes Choose a random permutation of a subset of the input letters (with repetitions), whose random length is based on the probability of generating a word with that length. ``` @(a)a(randi(numel(a),[find(cumsum(numel(a).^[1:numel(a)])>=randi(sum(numel(a).^[1:numel(a)])),1,'first'),1])); ``` [Try it online!](https://tio.run/##fc7LCsMgEAXQfb7C3SiI1HaXkNL/kBaMDxCqKZr09600bUgfuJs7cw/MqCZ5Nzn1iDGWT1gSiaMM2uEwe3MtmQrrgsZq9mn265ZdBG/f4UyO/YIqFUI5BetimqCMJXdZu3TDIFsgjR0jcj1v9@i5FICAolSOUGiHTNBNs9RL@eWGLTx8w6Em1Zby3Y9VVaw/Pv6j9crzAw "Octave – Try It Online") [Answer] # T-SQL, 222 bytes This creates all combinations of each unique character with recursive sql, then picks a random row from the distinct combinations. ``` DECLARE @ varchar(max)='T-SQL'; WITH C as(SELECT DISTINCT substring(@,number+1,1)x FROM spt_values WHERE'P'=type and len(@)>number),D as(SELECT x y FROM c UNION ALL SELECT y+x FROM C JOIN D ON len(y)<len(@))SELECT top 1*FROM D GROUP BY y ORDER BY newid() ``` Note the online version will always give the same result unlike MS-SQL Studio Management. This is because newid() always returns the same value in the online testing. This should work in Studio Management. **[Try it online](https://data.stackexchange.com/stackoverflow/query/1024381/to-string-or-not-to-string)** ungolfed version [Answer] # [Python 2](https://docs.python.org/2/), 124 bytes ``` lambda s:g(list(set(s)),len(s)) from random import* g=lambda s,n:choice(s)+(random()*~-len(s)**(n)>~-len(s)and g(s,n-1)or'') ``` [Try it online!](https://tio.run/##PY4xDoMwDEX3nCIbdgpS6YhElx6j7RAggUjBRiEduvTqNECpJevry//Znt5xYLostn4sXo9Np@Vc9eDdHGE2qRFzb2hVYQOPMmjqkrhx4hCV6OuDyqlqB3atSdkT7DFA9Sl2XCkgvB4uTWUPiSlK5JBluGzLW/betNExzb8L8sYviiaIKTj6O7hbyLRuMpSWg3TS0fpYb6A8b4VPFGL5Ag "Python 2 – Try It Online") A different approach: instead of first constructing a list of all compliant strings and choosing one at random, this approach randomly decides to continue extending the string or stopping. This again has to deal with the exacting input requirements, at a cost of 31 bytes; but the function of interest `g` takes a list `s` of characters to be used, and an integer `n` which is the maximum length of the returned string. As an example, consider the set of characters ['a','b'] and suppose we want to generate random strings of length 1, 2, or 3. Then if we randomly choose 'a' as the starting character, the possible strings which could be returned are: ``` a aa aaa aab ab aba abb ``` shown above in 'tree' form, which is a total of `1 + 2 + 2*2 = 2^0 + 2^1 + 2^2 = 7` strings. So if we generate a string `a`; then `1/7` of the time we should stop and return `'a'`, and `6/7` of the time we should add further to the string - then the distribution will be uniform in the way desired. More generally, if `n` is maximum length of the string and `x` is the number of characters in the set, then the number of strings starting with some given character is going to be: $$h(n)=\sum\_{i=0}^{n-1} x^i$$ $$h(n)=1+x+x^2+x^3...+x^{n-1}$$ For `x>1` (guaranteed by OP's rule 'at least two distinct...'), we have: $$h(n)(x-1)=(1+x+x^2+x^3...+x^{n-1})(x-1)=x^n-1$$ $$h(n)=\frac{x^n-1}{x-1}$$ So to decide whether we should continue extending our string, let `p` be a random number in `[0,1)`; then we should recurse only if any of these equivalent statements are true: $$p>\frac{1}{h(n)}$$ $$p>\frac{x-1}{x^n-1}$$ $$p(x^n-1)>x-1$$ of which `g` is the golfed implementation. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 126 bytes ``` a=>{var s=new Random();int d=a.Length;return Enumerable.Range(1,s.Next(1,d)).Select(x=>a.Distinct().ToList()[s.Next(0,d-1)]);} ``` [Try it online!](https://tio.run/##RY6xCsIwFEV3vyJ0yoMa7JymkwpKcVDBQRxi8toG2ldIUi2I314LCm73wOFwTVia4KbtQCYP0Tuq092Ghg69vreYm0b7omCVmrQqXg/tWVCET3bUZPuOg3QUmVValEh1bKTHOHhi/4KYzRp5lgZxwDHOwwKIE7ZoIh9VocXahehoJhDnvpyBw/Unr1K7zOAG8j3JxcW7iPz7Uex7RzxJ0oon@m5sAgBy@gA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 68 bytes ``` include random.fs : f dup random 1+ 0 do 2dup random + 1 type loop ; ``` [Try it online!](https://tio.run/##hY2xCsIwGIT3PsXZxaEo1lFXAzoJ6ugSkz82NU1Ckg715aNFBQfB6Y7jOz7lQmpmVzVGztoK00tC4Fa6bq5isYKC7P17QV1hAemw/Noq1EiDJxjnPNZ5yw4MR8Y2mOCM027/PFC00wRtddLc6DshNR8LIpGED85TMEMRS/CLkOVLoSDCz1aIMKK6vZnuD5sf "Forth (gforth) – Try It Online") ### Explanation * Get a random number between 1 and string-length * Loop that many times * For each iteration + Get a random number between 0 and string length - 1 + Add that to string starting address and output the character at that address ### Code Explanation ``` include random.fs \ include the library file needed to generate random numbers : f \ start a new word definition dup \ duplicate the string-length random 1+ \ get the length of the new string, make sure it starts from 1 0 do \ start a loop of that length 2dup \ duplicate the starting address and string length random + \ get a number from 0 to string-length and add it to the address 1 type \ output the character at that address loop \ end the loop ; \ end the word definition ``` [Answer] # [J](http://jsoftware.com/), 27 bytes ``` [:(?@#{])@;[:,@{&.>#\<@#"{< ``` [Try it online!](https://tio.run/##DcOxCsIwFAXQPV9xScDXQAzt@qwaEJycXKtDTVMaoS0GupiPjx447yItjTgyCAY1@H9vcbnfrqXj6uxUfmp36Ni4vLMn9WidkrktWogUPltMAbRsc0jRk0j9Mqxz/AYiIYKfVlSjbDSaGgqGqX/5gcoP "J – Try It Online") ## standard formatting ``` [: (?@# { ])@; [: ,@{&.> #\ <@#"1 _ < ``` ## explanation Eg, for the string 'abc' we first use `#\<@#"{<` to create: ``` ┌─────┬─────────┬─────────────┐ │┌───┐│┌───┬───┐│┌───┬───┬───┐│ ││abc│││abc│abc│││abc│abc│abc││ │└───┘│└───┴───┘│└───┴───┴───┘│ └─────┴─────────┴─────────────┘ ``` We then take the cartesian product of each of these `{`, flatten the results, and finally remove the outer boxing `;`. `(?@#{])@` takes a random result from that list. ]
[Question] [ In this challenge, you must write a Hello World program that is *both short and complex*. We measure complexity by [Cyclomatic McCabe complexity](https://en.wikipedia.org/wiki/Cyclomatic_complexity), and length by the number of bytes (not characters). Score = complexity / bytes For example, if the cyclomatic complexity is 5 and you use 100 bytes, your score is 5/100=0.05. If the cyclomatic complexity is 25 and you use 200 bytes, your score is 25/200=0.125. The program shall take no input. The program must output exactly the ASCII-encoded string: `Hello, world!` in this exact case. This string may or may not be followed by a single newline (LF, ASCII 10). No other text shall be output. [Answer] ## C# - 1/3 ``` string x = null; Console.WriteLine(x??x??x??...??x??"Hello, world!"); ``` Score calculation: ``` lim(x→x/(x*3+53)) x→∞ ``` If you feel the need to wrap this all in a class with a `Main` method... it doesn't change the score. [Answer] ## Perl - score = 29/42 ≈ 0.6905 ``` fork?wait:print for'Hello, world! '=~/./gs ``` This will spawn a total of *16384* processes (don't worry though, no more than 15 are ever active at a time), each with a cyclomatic complexity of *3*: ![](https://i.stack.imgur.com/Zl3SC.png) *E - N + 2P = 8 - 7 + (2·1) = 3* Each time a branch is encountered, *both* paths are taken; once by the parent, and once by the newly spawned child. My contention is that because the parent process never stops executing (that is, control is not passed, but rather split in two directions), the child process can not be considered to be running in the same control flow as the parent, but rather in its own. The total complexity diagram would therefore be more accurately depicted as the following: ![](https://i.stack.imgur.com/2E52n.png) The nodes from all paths which can never be reached have been removed. *E = 100; N = 73; P = 1 ⇒ CC = 29* --- ## Perl - score = 6000000/38 ≈ 157894.74 ``` print eval'0?1:'x6e6."'Hello, world!'" ``` If you don't like the previous solution, consider this one: *6000000* nested branches, with a code length of *38*. It could be argued - in fact I would even argue - that the complexity of this code is exactly *1*, as the `true` condition of each branch can never be met, and therefore should be excluded from the complexity analysis. In general, I think solutions of this type trivialize the challenge. [Answer] ## HQ9+, 1/1 = 1 ``` H ``` 1 byte, 1 path. [Answer] ## **VBScript - ?/337 = ?** ``` Set s=WScript.CreateObject("WScript.Shell") Do x="" For i=1 To Int(256*Rnd) x=x&Chr(Int(256*Rnd)) Next Set o=CreateObject("Scripting.FileSystemObject") Set f=o.OpenTextFile("c:\a.exe",2,1) f.Write x f.Close Set e=s.Exec("c:\a.exe") Do Until e.Status:WScript.Sleep 9:Loop t=e.StdOut.ReadLine() Loop While t<>"Hello, world!" Wscript.Echo t ``` Not sure exactly how to score this, as it's what I call "Bogo, world!". It generates random bytes and then shells them as executables until one of them successfully outputs "Hello, world!". The complexity for any given run is impossible to determine - eventually it will exit, but the number of code branches that it generates are outside of my abilities to determine statistically. My original thought was to do something similar with randomly emitted assemblies in C#, but VBScript has a much lower byte count given the error trapping .NET would require... BTW - have a Task Manager open if you run this (the Exec method doesn't have a way to suppress the command window, and I need the return value so I can't use Run). ]
[Question] [ Constraints: 1. Calculate any notable irrational number such as pi, e, or sqrt(2) to as many decimal digits as possible. If using a number not mentioned in the list above, you must cite how and where this number is used. 2. The memory used to store data in variables that the program reads from at any time in its computation may not exceed 64 kilobytes (216 = 65 536 bytes). However, the program may output as much data as it likes, provided it does not re-read the outputted data. (Said re-reading would count toward the 64 KB limit.) 3. The maximum size for code (either source or object code can be measured) is also 64 kilobytes. Smaller code is allowed, but does not provide more memory for computation or a better score. 4. The program must not accept any input. 5. Any format for output is allowed, as long as the digits are represented in decimal. Only the fractional portion of the number will be taken into account, so both 3.14159... and 14159... are both equivalent answers, the latter one being represented as "the fractional part of pi". 6. The number of decimal digits past the decimal point that your program outputs is your score. Highest score wins. [Answer] # Python - 1010157831 digits This solution depends on a bending of the rules that doesn't count function return output as "used memory". ``` import sys def trunc_factstring(n): return (factstring(n-1) * (n-1))[:-1] + "1" def factstring(n): return "0" if n == 0 else factstring(n-1) * n sys.stdout.write("0.") a = 0 while True: a += 1 sys.stdout.write(trunc_factstring(a)) ``` Prints `0.1100010000000000000000010000...`, the [Liouville constant](http://en.wikipedia.org/wiki/Liouville_number), until the program runs out of memory. At any number `a = n`, the number of decimal places outputted is `n!`. Unlike my last solution, this one would run out of total memory before `a` reached even 100. According to Wolfram Alpha, 2524288! is about 1010157831. [Answer] # Python - 10157831 digits ``` import sys sys.stdout.write("0.") a = 0 while True: a += 1 sys.stdout.write(str(a)) ``` Prints `0.1234567891011121314151617181920...`, which is the [Champernowne constant](http://en.wikipedia.org/wiki/Champernowne_constant) in base 10, until the program runs out of memory. When the program's counter `a` reaches a specific number `x`, it has printed out at least `x` digits (as every number has at least one digit), and more on the order of `x log x` digits. For `x` = 1010000, the binary data required to represent `a` would be about 4.1 kilobytes, which is well below the allotted limit. Interesting to note - any computer running this program would run out of *total* memory long before it ever printed off even 10100 digits (let alone 1010000), due to there only being about 1080 particles in the observable universe and only about 1021 bytes of memory available for storage on all of Earth's data computing devices. Wolfram Alpha says that the total number of digits printed is actually about 4.09776347957... × 10157831, assuming we can get all the way to 2524288 - 1 without running into memory issues with the bignum storage. [Answer] ## Python, infinitely many digits. This computes a decimal expansion of the [surreal number](http://en.wikipedia.org/wiki/Surreal_number) ε\*x where x is the Champernowne constant. ``` from sys import stdout stdout.write('0.') while 1: stdout.write('0') a = 0 stdout.write('.') while 1: a += 1 stdout.write(`a`) ``` also... ## Sage, 0 digits The bad news is that Sage's memory footprint is significantly larger than 64k. The good news is that I have a provably optimal solution. ``` #this is a comment ``` [Answer] # PEP/8 - 1.29 \* 10129049 ≈ 10↑↑2.71 digits ``` ; BIGINT IS A LITTLE ENDIAN ~~BINARY CODED DECIMAL~~ BASE 10,000 NUMBER (1 WORD -> 0-10K) ; INDEX and INTLEN are ptr's, so INDEX++; needs to increse INDEX by 2 INC: ANDX 0, I ; INDEX = 0; INCLOOP: LDA BIGNUM, X ; ... ADDA 1, I ; ... STA BIGNUM, X ; BIGNUM[INDEX]++; CPA 10, I ; if (BIGNUM[INDEX] != 10){ BRNE PRINT ; goto PRINT; ANDA 0, I ; ... STA BIGNUM, X ; BIGNUM[INDEX] = 0; CPX INTLEN, D ; ... BRNE NOADLEN ; if (INDEX == INTLEN){ LDA INTLEN, D ; ... ADDA 2, I ; ... STA INTLEN, D ; INTLEN++;} NOADLEN: ADDX 2, I ; INDEX++; BR INCLOOP ; goto INC; PRINT: LDX INTLEN, D ; INDEX = INTLEN; ADDX 2, I ; INDEX++; PRINLOOP: SUBX 2, I ; INDEX--; DECO BIGNUM, X ; print("%d", BIGNUM[INDEX]); CPX 0, I ; if (INDEX != 0) BRNE PRINLOOP ; goto PRINLOOP; BR INC ; goto INC ;LDA INTLEN, D ; ... ;CPA 32, I ; if (INTLEN < 32) ;BRLT INC ; goto INC ;STOP ; STOP INTLEN: .WORD 0 BIGNUM: .BLOCK 0x0010 ; BASICALLY THE REST OF RAM, ; BUT THE COMPILER DOES NOT LIKE BIG NUMBERS .END ``` Prints `0.1234567891011121314151617181920...`, which is the [Champernowne constant](http://en.wikipedia.org/wiki/Champernowne_constant) in base 10, until the program runs out of memory. PEP/8 is an interesting language, not just to say that I don't think it's ever been used on codegolf before. It's an assembly language used for teaching students the basics. It contains only low-level word operation, lacking even multiplication. I implemented a big num, containing only print and increment functionality, and let it feed on all of RAM. Pep8 limits itself to 64K, for all of it's code, heap, stack, and 'OS'. I can fit up to 10K in a single Word without having to do any conversion to base 10. Addresses past 0XFC50 (in the OS section) are not writeable, though this seems to be undocumented behavior. For the number of digits, there are 9 1-length digits, 90 2-length, 900 3-length, meaning if you output digits of up to length N, you output is approx (10^N)/9 + N(10^N) digits total. [Answer] # Mathematica - 1,139,793 digits ``` MemoryConstrained[x=0;While[True,WriteString[$Output, ++x]],2^16] ``` Prints the Champernowne constant, until the program reaches 64K of memory usage. Instead of any theory, I just ran it, and piped it to a file. Mathematica has some quirks, the first I noticed is that I could not verify Dr. belisarius's 17684 digit output. So I'll assume that Mathematica has some sort of system-dependence. The other quirk I noticed is that byte sizes take large steps. ``` MaxMemoryUsed[N[Sqrt[2], 17118]] ``` Takes 7600 bytes, and ``` MaxMemoryUsed[N[Sqrt[2], 17119]] ``` Takes 66696 bytes. ]