text
stringlengths
180
608k
[Question] [ Colonies of bacteria labelled `1` through `9` live on a segment of equally-spaced cells, with empty cells indicated by `0` ``` 0 0 2 0 0 0 1 2 0 0 3 3 0 0 ``` Every second, each colony spreads to adjacent empty cells. If two colonies reach an empty cell at the same time, the larger-labeled colony takes it. ``` t=0: 0 0 2 0 0 0 1 2 0 0 3 3 0 0 t=1: 0 2 2 2 0 1 1 2 2 3 3 3 3 0 t=2: 2 2 2 2 2 1 1 2 2 3 3 3 3 3 ``` The colonies cannot spread beyond the boundaries. A colony is never displaced by another colony, so once all empty cells are filled, nothing further changes. Given the initial state, output or print the final state. Use any reasonable list or string format. You should not output any intermediate states. The input will contain at least one bacterial colony. **Related:** [Cover up zeroes in a list](https://codegolf.stackexchange.com/questions/65770/cover-up-zeroes-in-a-list). (The colonies only spread to the right.) **Test cases:** Output below input. ``` 0 0 2 0 0 0 1 2 0 0 3 3 0 0 2 2 2 2 2 1 1 2 2 3 3 3 3 3 7 0 3 0 0 0 0 0 8 0 9 1 7 7 3 3 3 8 8 8 8 9 9 1 5 0 3 0 0 0 5 5 3 3 3 3 7 7 1 7 7 1 1 0 1 1 1 1 ``` ``` var QUESTION_ID=64812,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/67346/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] # JavaScript (ES6), ~~66~~ 62 bytes ``` a=>a.map(_=>a=a.map((c,i)=>c||Math.max(a[i-1]|0,a[i+1]|0)))&&a ``` ## Explanation ``` a=> // a = input as array of numbers a.map(_=> // loop for the length of a, this ensures the end is always reached a=a.map((c,i)=> // update a after to the result of t, for each cell c of index i c|| // keep the cell if it is not 0 Math.max( // else set the cell to the max value of: a[i-1]|0, // the previous cell (or 0 if i - 1 less than 0), a[i+1]|0 // or the next cell (or 0 if i + 1 greater than the length of a) ) ) ) &&a // return a ``` ## Test ``` var solution = a=>a.map(_=>a=a.map((c,i)=>c||Math.max(a[i-1]|0,a[i+1]|0)))&&a ``` ``` Cell numbers separated by spaces = <input type="text" id="input" value="7 0 3 0 0 0 0 0 8 0 9 1" /> <button onclick="result.textContent=solution(input.value.split(' ').map(n=>+n)).join(' ')">Go</button> <pre id="result"></pre> ``` [Answer] # Pyth, 18 bytes ``` um|@d1eSd.:++0G03Q ``` [Test suite](https://pyth.herokuapp.com/?code=um%7C%40d1eSd.%3A%2B%2B0G03Q&test_suite=1&test_suite_input=%5B0%2C+0%2C+2%2C+0%2C+0%2C+0%2C+1%2C+2%2C+0%2C+0%2C+3%2C+3%2C+0%2C+0%5D%0A%5B7%2C+0%2C+3%2C+0%2C+0%2C+0%2C+0%2C+0%2C+8%2C+0%2C+9%2C+1%5D%0A%5B5%2C+0%2C+3%2C+0%2C+0%2C+0%5D%0A%5B7%2C+7%2C+1%5D&debug=0) Takes input as a list of integers. Essentially, this uses a apply until convergence loop, `u`. It applies the update by forming all lists of each cell and the two cells on either side, then updating each zeroed cell to the max of its neighbors. ``` um|@d1eSd.:++0G03Q Implicit: Q = eval(input()) u Q Apply the following until convergence, starting with G = Q. ++0G0 Pad G with zeros on either side. .: 3 Form all 3 element substrings. Now, for each element of G, we have a list of the form [previous, current, next] m Map over this list |@d1 The current element, if it's nonzero eSd Else the max of the list. ``` [Answer] ## Mathematica, 77 bytes Not very competitive compared with alephalpha's `//.` solution, but I figured a [cellular-automata](/questions/tagged/cellular-automata "show questions tagged 'cellular-automata'") challenge should have a `CellularAutomaton` answer: ``` CellularAutomaton[{If[#2<1,Max@##,#2]&@@#&,{},1},{#,0},{{{l=Length@#}},l-1}]& ``` The function takes a ton of parameters... let's give them some names: ``` CellularAutomaton[{f,n,r},{i,b},{{{t}},d}] ``` Here is what they do: * `r` is the range of the rule, that is, it determines how many neighbours are considered for the update. We want one neighbour on each side, so we use `1`. * `n` is normally the number or list of colours (different cell types), but if we specify the rule as a custom function instead of a rule number, this should be `{}`. * `f` is a function determining the update rule. It takes a list of 3 cells (if `r = 1`) and returns the new colour for the middle cell. * `i` is the initial condition. That's the input. * `b` is the background. If this isn't given, `CellularAutomaton` uses periodic boundaries, which we don't want. Instead using `0` imposes a dead boundary condition. * `t` is the number of times to simulate. We don't need more steps than the input is wide, because after that the bacteria will have converged, so `t = Length@#`. Normally, `CellularAutomaton` returns all intermediate steps. We can avoid that by wrapping `t` in two lists. * `d` determines which cells are presented in the output. By default, we would get all the cells that could potentially be affected by the rule (which is `t*r` additional cells on either end of the input). We give it `l-1`, because this is one of the few situations in Mathematica where a zero-based index is used. [Answer] ## Haskell, ~~86~~ ~~83~~ ~~81~~ ~~79~~ ~~73~~ 71 bytes ``` (0#r)l=max r l (o#_)_=o p!_=zipWith3(#)p(0:p)$tail p++[0] id>>=foldl(!) ``` Usage example: `id>>=foldl(!) $ [7,0,3,0,0,0,0,0,8,0,9,1]` -> `[7,7,3,3,3,8,8,8,8,9,9,1]`. Nothing much to explain: if a cell is 0, take the maximum of the neighbor elements. Repeat length-of-the-input times. For this I iterate over `x` via `foldl` but ignore the second argument in `p`. Edit: @Mauris found 6 bytes to save and @xnor another two. Thanks! [Answer] ## CJam, ~~27~~ 24 bytes ``` {_,{0\0++3ew{~@e>e|}%}*} ``` [Test it here.](http://cjam.aditsu.net/#code=%5B0%200%202%200%200%200%201%202%200%200%203%203%200%200%5D%0A%5B7%200%203%200%200%200%200%200%208%200%209%201%5D%0A%5B5%200%203%200%200%200%5D%0A%5B7%207%201%5D%0A%0A%7B_%2C%7B0%5C0%2B%2B3ew%7B~%40e%3Ee%7C%7D%25%7D*%7D%0A%0A%5D)f%7B~p%7D) This pushes an unnamed block which transforms a list on the stack into a new list. ### Explanation ``` _, e# Duplicate the input and get its length N. { e# Run this block N times (convergence won't take that long)... 0\0++ e# Wrap the list in two zeroes. 3ew e# Get all sublists of length 3. { e# Map this block onto each sublist... ~ e# Dump all three elements on the stack. @ e# Pull up the left neighbour. e> e# Maximum of both neighbours. e| e# Logical OR between centre cell and maximum of neighbours. }% }* ``` [Answer] # J, ~~24~~ 23 bytes ``` (+=&0*(0,~}.)>.0,}:)^:_ ``` Usage: ``` ((+=&0*(0,~}.)>.0,}:)^:_) 0 1 5 0 0 0 6 1 1 5 5 6 6 6 ``` Method is similar to [Mauris' solution](https://codegolf.stackexchange.com/a/67386/7311). ``` ( )^:_ repeat until change 0,}: concat 0 and tailless input (0,~}.) concat headless input and 0 >. elementwise maximum of the former two lists =&0* multiply by input_is_0 (zeroing out the list at nonzero input positions) + add to input ``` [Try it online here.](http://tryj.tk/) *1 byte saved thanks to Zgarb.* [Answer] # Mathematica, ~~77~~ ~~74~~ ~~66~~ 62 bytes Saved 12 bytes thanks to Martin Büttner. ``` #//.i_:>BlockMap[If[#2<1,Max@##,#2]&@@#&,Join[{0},i,{0}],3,1]& ``` [Answer] # J, 33 bytes ``` 3 :'y+(y=0)*>./(_1,:1)|.!.0 y'^:_ ``` A bit longer than I would've liked. ``` 3 :' '^:_ Repeat a "lambda" until a fixed point: y The input to this lambda. (_1,:1)|.!.0 Shift left and right, fill with 0. >./ Maximum of both shifts. (y=0)* Don't grow into filled cells. y+ Add growth to input. ``` [Answer] ## Python 3.5, 83 bytes This function takes a Python list of integers. Not sure there's much left to golf, but I'd love to get it competitive with another language at least! ``` def b(s): for _ in s:s=[s[n]or max((0,*s)[n:n+3])for n in range(len(s))] return s ``` From Python 3.5, [PEP 448](https://www.python.org/dev/peps/pep-0448/) lets us unpack `s` into `0,*s`. Earlier releases require one byte extra, like so: ``` def b(s): for _ in s:s=[s[n]or max(([0]+s)[n:n+3])for n in range(len(s))] return s ``` Credit to [user81655's solution and explanation](https://codegolf.stackexchange.com/a/67355/13959) for helping me realise that I don't need to test whether the list has stopped changing; I just need to iterate enough times to be sure all zeroes must have been covered. (The maximum number of iterations needed is one less than the length of the list; this does one iteration more than that, because that takes less code.) [Answer] # Matlab, 90 bytes How about some convolutions? ``` x=input('');for n=x;x=x+max(conv(x,[0 0 1],'same'),conv(x,[1 0 0],'same')).*~x;end;disp(x) ``` ### Example ``` >> x=input('');for n=x;x=x+max(conv(x,[0 0 1],'same'),conv(x,[1 0 0],'same')).*~x;end;disp(x) [7 0 3 0 0 0 0 0 8 0 9 1] 7 7 3 3 3 8 8 8 8 9 9 1 ``` [Answer] ## Haskell, ~~66~~ 65 bytes ``` f x=[maximum[[-j*j,a]|(j,a)<-zip[-i..]x,a>0]!!1|(i,_)<-zip[0..]x] ``` This defines a function called `f`. ## Explanation Instead of iterating the cellular automaton, I compute the final values directly. The definition is a single list comprehension. The value `i` ranges from `0` to `length x - 1`, since we zip `x` with the natural numbers. For each index `i`, we produce the list of 2-element lists ``` [-(-i)^2, x0], [-(-i+1)^2, x1], [-(-i+2)^2, x2], ..., [-(-i+n)^2, xn] ``` From this list, we compute the maximal element whose second coordinate is nonzero and take that second element with `!!1`. This gives the closest nonzero value to index `i`, breaking ties by taking the larger value. [Answer] # Lua, 133 bytes Two loops, nested ternaries... If I want to golf it further, I will have to find an other way to do it, but I don't see one. ``` function f(a)for i=1,#a do b={}for j=1,#a do c,d=a[j+1]or 0,a[j-1]b[j]=0<a[j]and a[j]or(d or 0)>c and d or c end a=b end return a end ``` ### Explanations ``` function f(a) for i=1,#a -- this loop allow us to be sure the cycle is complete do b={} -- set a new pointer for b for j=1,#a -- loop used to iterate over all elements in a do c,d=a[j+1]or 0,a[j-1] -- gains some bytes by attributing these expressions -- to a variable b[j]=0<a[j]and a[j]or -- explained below (d or 0)>c and d or c end a=b -- we are one cycle further, new value for a end -- which is our reference array return a end ``` The part ``` b[j]=0<a[j]and a[j]or(d or 0)>c and d or c ``` will be expanded to ``` b[j]=0<a[j]and a[j]or(a[j-1] or 0)>(a[j+1] or 0) and a[j-1] or(a[j+1]or 0) ``` which can be translated in nested `if` as ``` if 0<a[j] then value=a[j] -- if the cell isn't at 0, it keeps its value elseif (a[j-1] or 0)<(a[j+1] or 0) --[[ x or y as the following truth table : x | y ||x or y ------||------- 0 | 0 || false 0 | 1 || y 1 | 0 || x 1 | 1 || x -- It means that when j=1 (1-based) and we try to index a[j-1] -- instead of failing, we will fall in the case false or true -- and use the value 0 -- the same trick is used for when we try to use an index > a:len ]]-- then value=a[j-1] -- the left cell propagate to the cell j else value=a[j+1] or 0 -- if j=a:len, we put 0 instead of a[j+1] -- this case can only be reached when we are on the right most cell -- and a[j-1]==0 end ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 18 bytes Anonymous tacit prefix function. ``` (⊢+~∘××3⌈/0,,∘0)⍣≡ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/hR2wSNR12LtOsedcw4PP3wdONHPR36Bjo6QK6B5qPexY86FwJVKRgAoRGYNFAwhLKMgRBIcxkpwKAhWM4ILAOB6pnFCkWZ6Rkl6lxcxQrmYF0GcGgBxJYKhlzmQBmIegsotASJo@k2RejmMgXycNlhDjURXb8hyO1chmBXImQA "APL (Dyalog Unicode) – Try It Online") `(`…`)⍣≡` apply the following tacit function until the result is identical to the argument:  `⊢` the argument  `+` plus   `~` not   `∘` the   `×` signum  `×` times  `3⌈/` the maxima over each group of three of  `0,` zero followed by   `,` the argument followed by   `∘` a   `0` zero [Answer] # [Husk](https://github.com/barbuz/Husk), 15 bytes ``` ω(m?!2▲!2X3`:0Θ ``` [Try it online!](https://tio.run/##yygtzv7//3ynRq69otGjaZsUjSKME6wMzs34//9/tLmOgY4xEMOgBRBb6hjGAgA "Husk – Try It Online") ## Explanation ``` ω(m?!2▲!2X3`:0Θ ω( iterate until fixed point: `:0Θ prepend and append 0 X3 take overlapping segments of 3 elements m map to: ? !2 if second element is truthy: !2 leave as is ▲ else take maximum ``` [Answer] ## Pyth, 17 bytes ``` meeSe#.e,_akdbQUQ ``` Takes a Python-style list from stdin, outputs to stdout. ## Explanation This is basically a translation of my Haskell answer. I haven't really used Pyth before, so hints are welcome. ``` Implicit: Q is input list m UQ Map over input index d: .e Q Map over input index k and element b: ,_akdb The pair [-abs(k-d), b] e# Remove those where b==0 eeS Take the second element of the maximal pair ``` [Answer] # Java 8, ~~155~~ 142 bytes ``` a->{for(int b[],i,l=a.length,p,n,f=l;f>0;)for(b=a.clone(),i=0,f=l;i<l;f-=a[i-1]>0?1:0)if(a[i++]<1)a[i-1]=(p=i>1?b[i-2]:0)>(n=i<l?b[i]:0)?p:n;} ``` Modifies the input `int[]` instead of returning a new one to save bytes. **Explanation:** [Try it here.](https://tio.run/##vVKxbsIwEN35ihsd4UQJVUVLcFDVuSyMKIMTHGpqnCg2VAjl29OLDWqpuhbpYuW9u/O9Z3vHjzysG6F3m4@@VNwYeONSn0cAUlvRVrwUsBwgwLGWGygJ8usceJAi2eGHYSy3soQlaGDQ8zA7V3U7FEKxzqmkivFICb2177ShmlZMpVUWp8FQVWCuVLUWJKCSxS4p51gQMr6WYZJn8SKZxYGsCOLxOJ8ngU8w0jCZJYsC0STHkoxohq0DMcBFM9Np16deY3MoFGq8SHVe9uiUrGwr9dY58ja9PyuMfeVGoCEtPj15jilgTNzqI/kBH1wM/13qdtJRSa77BJ5anYwV@6g@2KjBuVZpssMriA5WquilbfnJRLb2mr57L81/appeZ8e38eTWZ5R4TzWPv9Tc@SSmd7ab@EfwLyO7Udd/AQ) ``` a->{ // Method with integer-array parameter and no return-type for(int b[], // Copy array i, // Index integer l=a.length, // Length of the array p,n, // Temp integers (for previous and next) f=1; // Flag integer, starting at 1 f>0;) // Loop (1) as long as the flag is not 0 (array contains zeroes) for(b=a.clone(), // Create a copy of the current state of the array i=0, // Reset the index to 0 f=l; // Reset the flag to the length of the array `l` i<l; // Inner loop (2) over the array f-=a[i-1]>0? // After every iteration, if the current item is not a zero: 1 // Decrease flag `f` by 1 : // Else: 0) // Leave flag `f` the same if(a[i++]<1) // If the current item is a 0: a[i-1]= // Change the current item to: (p // If `p` (which is: =i>1? // If the current index is not 0: b[i-2] // `p` is the previous item : // Else: 0) // `p` is 0) >(n // Is larger than `n` (which is: =i<l? // If the current index is not `l-1`: b[i] // `n` is the next item : // Else: 0)? // `n` is 0): p // Set the current item to `p` : // Else: n; // Set the current item to `n` // End of inner loop (2) (implicit / single-line body) // End of loop (1) (implicit / single-line body) } // End of method ``` [Answer] # Ruby, 81 bytes ``` ->(a){a.map{|o|a=a.map.with_index{|x,i|x!=0 ? x : a[[0,i-1].max..i+1].max}}[-1]} ``` I think the inner `map` could be further golfed. [Answer] ## PHP - 301 291 289 288 264 Characters Didn't peak at other answers before attempting this. Don't blame the language, blame me. Very enjoyable and challenging non the less. All code golf advice heavily appreciated. ``` $a=explode(' ',$s);$f=1;while($s){$o=1;foreach($a as&$b){ if($b==0){$u=current($a);prev($a);$d=prev($a);if(!$o&&current($a)==0){end($a);$d=prev($a);}if(!$f){$f=1;continue;}if($u>$d)$b=$u;if($u<$d){$b=$d;$f=0;}} $o=0;}if(!in_array(0,$a))break;}$r=join(' ',$a);echo$r; ``` Explained ``` // Input $s = '0 0 2 0 0 0 1 2 0 0 3 3 0 0'; // Create array $a = explode(' ', $s); // Set skip flag $f = 1; while ($s) { // Set first flag $o = 1; // Foreach foreach ($a as &$b) { // Logic only for non zero numbers if ($b == 0) { // Get above and below value $u = current($a); prev($a); $d = prev($a); // Fix for last element if (! $o && current($a) == 0) { end($a); $d = prev($a); } // Skip flag to prevent upwards overrun if (! $f) { $f = 1; continue; } // Change zero value logic if ($u > $d) $b = $u; if ($u < $d) { $b = $d; $f = 0; } } // Turn off zero flag $o = 0; } // if array contains 0, start over, else end loop if (! in_array(0, $a)) break; } // Return result $r = join(' ', $a); echo $r;(' ', $a); echo $r; ``` [Answer] ## Python, 71 bytes ``` g=lambda l:l*all(l)or g([l[1]or max(l)for l in zip([0]+l,l,l[1:]+[0])]) ``` The `zip` creates all length-3 sublists of an element and its neighbors, treating beyond the endpoints as `0`. The central element `l[1]` a sublist `l`, if zero, is replaced by the `max` of its neighbors with `l[1]or max(l)`. The `l*all(l)` returns the list `l` when it has no `0`'s. [Answer] # Ruby, 74 bytes ``` ->a{(r=0...a.size).map{|n|a[r.min_by{|i|[(a[i]<1)?1:0,(i-n).abs,-a[i]]}]}} ``` works by finding the closest non-zero number. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 38 bytes Direct translation of my Matlab answer. Uses [current version](https://github.com/lmendo/MATL/releases/tag/3.1.0) of language/compiler. ``` it:"tttFFTo2X5I$X+wTFFo2X5I$X+vX>w~*+] ``` ### Example ``` >> matl it:"tttFFTo2X5I$X+wTFFo2X5I$X+vX>w~*+] > [7 0 3 0 0 0 0 0 8 0 9 1] 7 7 3 3 3 8 8 8 8 9 9 1 ``` *EDIT: [Try it online!](http://matl.tryitonline.net/#code=aXQ6InR0dEZGVG8yWDVJJFkrd1RGRm8yWDVJJFkrJnZYPnd-Kitd&input=WzcgMCAzIDAgMCAwIDAgMCA4IDAgOSAxXQ) with `X+` replaced by `Y+` and `v` by `&v`, owing to changes done in the language.* ]
[Question] [ Given an N-dimensional orthogonal (non-ragged) array of non-negative integers, and an indication of which dimensions to reverse, return the array but reversed along those dimensions. The indication may be given as a Boolean list of length N or a list of a subset of the first N dimensions indexed from 0 or 1. Please state your input formats. Code explanations are much appreciated. ## Walked-through example We are given the 2-layer 3-row 4-column 3D-array ``` [[[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9,10,11,12]], [[13,14,15,16], [17,18,19,20], [21,22,23,24]]] ``` and one of `[true,false,true]` (Boolean list) `[0,2]` (0-indexed list) `[1,3]` (1-indexed list) We need to reverse order of the first and last dimensions, that is the layers and the elements of the rows (the columns), but not the rows of each layer. First (the actual order you do this in does not matter) we reverse the order of the layers: ``` [[[13,14,15,16], [17,18,19,20], [21,22,23,24]], [[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9,10,11,12]]] ``` and then we reverse the order of the elements of each row: ``` [[[16,15,14,13], [20,19,18,17], [24,23,22,21]], [[ 4, 3, 2, 1], [ 8, 7, 6, 5], [12,11,10, 9]]] ``` ## Test cases `[[[1,2,3,4],[5,6,7,8],[9,10,11,12]],[[13,14,15,16],[17,18,19,20],[21,22,23,24]]]` `[true,false,true]`/`[0,2]`/`[1,3]`  ↓  `[[[16,15,14,13],[20,19,18,17],[24,23,22,21]],[[4,3,2,1],[8,7,6,5],[12,11,10,9]]]` --- `[[1,2,3],[4,5,6]]` `[true,false]`/`[0]`/`[1]`  ↓ `[[4,5,6],[1,2,3]]` --- `[[1],[4]]` `[true,false]`/`[0]`/`[1]`  ↓ `[[4],[1]]` --- `[[7]]` `[true,true]`/`[0,1]`/`[1,2]`  ↓ `[[7]]` --- `[1,2,3,4,5,6,7]` `[true]`/`[0]`/`[1]`  ↓ `[7,6,5,4,3,2,1]` --- `[]` `[true]`/`[0]`/`[1]`  ↓ `[]` --- `[[],[]]` `[false,false]`/`[]`/`[]`  ↓ `[[],[]]` --- `[[[[3,1,4,1],[5,9,2,6]],[[5,3,5,8],[9,7,9,3]]],[[[2,3,8,4],[6,2,6,4]],[[3,3,8,3],[2,7,9,5]]]]` `[true,false,true,true]`/`[0,2,3]`/`[1,3,4]`  ↓ `[[[[4,6,2,6],[4,8,3,2]],[[5,9,7,2],[3,8,3,3]]],[[[6,2,9,5],[1,4,1,3]],[[3,9,7,9],[8,5,3,5]]]]` --- `[[[[3,1,4,1],[5,9,2,6]],[[5,3,5,8],[9,7,9,3]]],[[[2,3,8,4],[6,2,6,4]],[[3,3,8,3],[2,7,9,5]]]]` `[false,true,false,false]`/`[1]`/`[2]`  ↓ `[[[[5,3,5,8],[9,7,9,3]],[[3,1,4,1],[5,9,2,6]]],[[[3,3,8,3],[2,7,9,5]],[[2,3,8,4],[6,2,6,4]]]]` --- `[[[[3,1,4,1],[5,9,2,6]],[[5,3,5,8],[9,7,9,3]]],[[[2,3,8,4],[6,2,6,4]],[[3,3,8,3],[2,7,9,5]]]]` `[false,false,false,false]`/`[]`/`[]`  ↓ `[[[[3,1,4,1],[5,9,2,6]],[[5,3,5,8],[9,7,9,3]]],[[[2,3,8,4],[6,2,6,4]],[[3,3,8,3],[2,7,9,5]]]]` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~20~~ 9 bytes ``` ⊃{⌽[⍺]⍵}/ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHXc3Vj3r2Rj/q3RX7qHdrrT5QWMFQwVhBwwhImDzq3fKod7ORiSYA) **How?** `/` - reduce - take the rightmost element in the input (the array) and apply the function with next left element as left argument `{⌽[⍺]⍵}` - reverse in the `left argument` (`⍺`) dimension `⊃` - flatten the enclosed array [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 9 [bytes](https://github.com/abrudz/SBCS) ``` ⊃{⊖[⍺]⍵}⌿ ``` [Try it online!](https://tio.run/##tZCxTsMwGIT3PsVtLQNS/t92nA5MLLBSNsRQCZWlEl0RYmklhghXLPAUjLCw8C7/i4SzQUIguRPESmT7vtzZN18t9y@u58ury2GwfnNj/dOZpbdzS6@3dv8@LOzuwdJWqdn2cXZyyO/p0fFsNOKE2gICN1E4eEsvgjJDQIuIDlNIAxGIQhzEQwKkhURIB5lCGyj/UaiD@r0vz/FBfsbfCdn/p/suVApad4NOpECx7hJ/X6aONkQtPVcA69c80m4mVwhPLI9cI6tirjCZFTE9UA@lzsjXlXN1JNqieq7yOu9nPdRi9N8jPm/7VxnDBw "APL (Dyalog Unicode) – Try It Online") It looks like [Uriel edited into something almost identical](https://codegolf.stackexchange.com/a/171630/41024) first, but I developed it independently. I thought this input format is invalid. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~58~~ ~~55~~ ~~53~~ 45 bytes *Saved 8 bytes thanks to @Shaggy* Takes input as `(indications)(array)`, where *indications* is a Boolean list. ``` f=([r,...b])=>a=>1/r?a.sort(_=>r).map(f(b)):a ``` [Try it online!](https://tio.run/##zVHLTsMwELzzJbE0mK7zLFLCnQMcOFoWcktSBYWkcgISXx/WpuJ5STlUXKzd1Yx3ZufRvthx69r9dN4PD/U8N2WkHaSUGyPKypYVXbgrK8fBTdF9WTkhn@w@aqKNEJd23g79OHS17IZddH13eyPHybX9rm1eGaIn91yjsd1Yw5dGRFprgkKMxECnyJCj4GoNWoEIpAx3mmJQAkpBGbeUgwrQGmrFnWK@goqhEmOMEOJsqYawPmznbxLw9r/wPXcx78N1vpTi0YcLIdznCN4C6HsYn3bYzXFHwHdfWnNULJVCnByRPyonmLKB9BBtzvPYhLH2xooQfuaxXPlxHKY@FhXQqVkU7RdBP339A12/3hMIm98A "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a function taking: [r, // r = next 'reverse' Boolean flag ...b] // b = array of remaining flags ) => // and returning an anonymous function taking: a => // a = array (or sub-array) to process, or atomic element 1 / r ? // if r is defined: a.sort(_ => r) // reverse a if r = 1; leave it unchanged otherwise .map(f(b)) // for each element in the resulting array: do a recursive call, // using f to generate a new callback function for the next flag : // else: a // a must be an atomic element and is simply left unchanged ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~56~~ 55 bytes ``` f=lambda a,t:t and[f(l,t[1:])for l in a][::1|-t[0]]or a ``` [Try it online!](https://tio.run/##vVHLasNADLznK/aYwBSs9duQa7@gN7EHl8Q04DohdQ@F/rsryU5qU1@by6LdndGMNJev/u3c@WFo9m39/nqoXY2@6l3dHbjZtuiZqrBrzlfXulPn6sBVRd9PPUchyGM9XK6nrnfNlpkJHjGSAE6RIUchVQmKQATyQW5MMSgBpaBMrpSDClAJH8nNC9/Dx/BJUPDL9fOI57r9OELLsNvvnapkxpcusZIi5WuXXG@J8aULmVwifjxIykL8ZEhV1JufCKWobDa//s2@ABKIfaG7mQMTdzz9YcIu6Upd@h5ZSlPKEp7foffhFJkvUNNGYfuc8DeozYPbhDPSAscLUflS2XGpS4v2NccyS1bSnyxPyciWwlLHojtmm8t7bGExq9PC0s8UC9uF9NBXS8rQaVjLdrkDXbP1sDAKnXBSVkUvpfW8Kyu2HLNVv/puyubPsjfPITxwwNlsa9teVcGqI9NeUcGqo4eP@Oeczfhv4pvhBw "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ”€ẋ”ṚpFv ``` Takes a 0-indexed list of dimensions. [Try it online!](https://tio.run/##tVA7bkIxEOw5xTvASLxd@324AHeIVi5pIgoqpHRR2nSpokjUNFyAtIiDPC7ijBeTKElNtzM7np3x42q9fsr58ry7vBymz1cO0/Fjs9zm017n57fp@M7FQ85mLTShaRozEygCYoJ16DFg5LSAtBCBaCIyCZAI6SA9oQyQEbKAtkTK9woN0JgonjXWunPxdmtqImj9b1kWlYTUNMMfVQ0Hj/Z75agCvqTbzcyPlmrG3Hws3o15PYRxDjS89hzIh@S0lVOj/0RftIhOB2dLDXV1l2pP@a5y50M/Je94aJa@AA "Jelly – Try It Online") ### How it works ``` ”€ẋ”ṚpFv Main link. Left arg: D (dimensions, 0-based), Right arg: A (array) ”€ẋ Repeat '€' d times, for each d in D. ”Ṛp Perform Cartesian product of ['Ṛ'] and each string of '€'s, prepending a 'Ṛ' to each string of '€'s. F Flatten the result. If, e.g., D = [0,2,4], we build the string "ṚṚ€€Ṛ€€€€". v Eval the resulting string, using A as left argument. ``` [Answer] # [R](https://www.r-project.org/), ~~80~~ ~~78~~ 77 bytes Create the call to R's extractor `[` by creating a list of sequences reversed where indicated. They actually contain zeros, which are silently ignored. The `drop=F` is needed to prevent R's default dropping of dimensions. We need the `rev` call to the dimension reverse indicator, because of the way R fills arrays. -2 thanks @Giuseppe -1 using in-line assignment. ``` function(x,a,d=dim(x))do.call("[",c(list(x),Map(seq,r<-d*rev(a),d-r),drop=F)) ``` [Try it online!](https://tio.run/##XZDLasMwEEX3@QqhLDoK42I9/CrJNrtuinddCUsGg2q7klOSr3dlt2ATBIN0jq6GkZ9bck7m9tY3Uzf0cEeN5mK6L7gzZobXRjsH9JNiA64LU6T4rkcI9hv9OTEnb39AMzSJj8UP4@XK2NyC9l4/gL8JFYMKJQrG4q7GK9aMHQ7bjTzind7LBjiqhQvkq38KR79Q/m/r56eLCIs/tRdpBCmmW4Ycj@SDmMGG/mUi3saRH/FI@ptzZM2ELW0dhMmH0XUTUMkVzyqRZzIrq6KSQpYqF7mSspSiqDKKlK59FIplbZ@w9J1/AQ "R – Try It Online") Honorable mention to @JayCe who came up with a variation that gets the same result in the same length: ``` function(x,a,d=dim(x))array(x[t(t(expand.grid(Map(seq,r<-d*rev(a),d-r))))],d) ``` [Try it online!](https://tio.run/##XZA9a8MwEIb3/ArhDD2Vc7E@/FXStVuX4q10EJZcDKrjSkpxfr0rOwWb6Bbpee69A7m5I6d07i5DG/rzABMq1C@6/4aJUuWcusL0ESCAmUY16Kcv12t4UyN484PulOpHZ35BUdSpo/F8oqZzB7cke@YSW5AokFMabw2@YkPp4bB1FBHv9F62wFAunCNb/V04@oWyf9vcjy4jLG9qL7IIMsy2DDkeyTvRZ@OHh0CcUdZe45MMF2vJmvFb2ljwwfnR9gESwSTLa17kIq/qshZcVLLghRSiErys8wSTZN0jkS@1fcKyd/4D "R – Try It Online") [Answer] # Haskell, ~~120~~ 119 bytes the function f takes the N-dimensional list and a list of bool as input ``` class F r where f::[Bool]->r->r instance F Int where f=seq instance F r=>F[r]where f(a:y)=last(id:[reverse|a]).map(f y) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~23~~ ~~11~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '€s×'R«J.V ``` [Try it online.](https://tio.run/##yy9OTMpM/f9f/VHTmuLD09WDDq320gv7/z/aQMdIxziWKxoIjHUMdUx0DGN1ok11LIHCZrFAJpBtrGOqYwFkWuqYA8WNY8HC0UBtOhY6JkC2GUgtkAUSNgaLGgOZRmDVpkDVsQA) -12 bytes thanks to *@Mr.Xcoder*. Input as 0-indexed truthy-values (i.e. `[0,2,3]`), which is the first input. **Explanation:** ``` '€s× # Repeat "€" the indices amount of times # i.e. [0,2,3] → ["","€€","€€€"] 'R« # Append each with "R" # i.e. ["","€€","€€€"] → ["R","€€R","€€€R"] J # Join them all together # i.e. ["R","€€R","€€€R"] → R€€R€€€R .V # Execute string as 05AB1E code ``` For example: if the indices input-list is `[0,2,3]`, it will create the following string: ``` R€€R€€€R ``` Which will: ``` €€€R # Reverse the items in the most inner (4th level) lists €€R # Reverse the most inner (3rd level) lists themselves # Do nothing with the inner (2nd level) lists R # Reverse the entire outer (1st level) list ``` --- **Original 23 byte answer:** ``` ćURvy„ RèJ…εÿ}}„ RXèJ.V ``` Input as boolean-list (i.e. `[1,0,1,1]`), which is the first input. [Try it online.](https://tio.run/##yy9OTMpM/f//SHtoUFllpnrQ4dWHt9Z6PWpYdm7r4f21sY8a5ikERRxe4aUX9v9/tKGOgY6hjmEsVzQQGAOZJkCOTrSpjqWOkY5ZLJAJZBvrmOpYAJmWOuZAceNYsHC0EVDcQscEyDYDqQWyQMLGYFFjINMIrNoUqDoWAA) **Explanation:** ``` ćU # Pop and save the first boolean in variable `X` R # Reverse the remaining boolean-list v } # Loop `y` over each of them: „ Rè # Take the string "R ", and index the current boolean (0 or 1) in it J # Join it together with the string of the previous iteration …εÿ} # Surround it with "ε" and "}" „ RXè # Index variable `X` also in "R " J # Join it together with the rest .V # Execute string as 05AB1E code ``` For example: If the boolean input-list is `[1,0,1,1]`, it will create the following string: ``` εεεR}R} }R ``` Which will: ``` εR} # Reverse the items in the most inner (4th level) lists ε R} # Reverse the most inner (3rd level) lists themselves ε } # Do nothing with the inner (2nd level) lists R # Reverse the entire outer (1st level) list ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 60 bytes *A different (recursive) approach. doesn't beat Arnauld's answer ... yet....* Takes the input as `array, boolean list` ``` f=(a,r)=>r>[]?(r[0]?a.reverse():a).map(c=>f(c,r.slice(1))):a ``` ``` f=(a,r)=>r>[]?(r[0]?a.reverse():a).map(c=>f(c,r.slice(1))):a console.log(f([[[[3,1,4,1],[5,9,2,6]],[[5,3,5,8],[9,7,9,3]]],[[[2,3,8,4],[6,2,6,4]],[[3,3,8,3],[2,7,9,5]]]],[true,false,true,true])) ``` [Answer] # [Pyth](https://pyth.readthedocs.io), 15 bytes ``` .v+jk.n*\_*L\ME ``` [Try it here!](https://pyth.herokuapp.com/?code=.v%2Bjk.n%2a%5C_%2aL%5CME&input=%22%5B%5B%5B1+2+3+4%29+%5B5+6+7+8%29+%5B9+10+11+12%29%29+%5B%5B13+14+15+16%29+%5B17+18+19+20%29+%5B21+22+23+24%29%29%29%22%0A%5B0%2C2%5D&debug=0) Annoyingly, handling the empty dimension list case takes no less than 2 bytes... I'd rather use `ss` in place of `jk.n` but :| Assumes that the list to be transformed can be given in native Pyth syntax, as a string. I've written a [converter to Pyth syntax](https://pyth.herokuapp.com/?code=XXz%5C%5D%5C%29%5C%2Cd&input=%5B%5B%5B1%2C2%2C3%2C4%5D%2C%5B5%2C6%2C7%2C8%5D%2C%5B9%2C10%2C11%2C12%5D%5D%2C%5B%5B13%2C14%2C15%2C16%5D%2C%5B17%2C18%2C19%2C20%5D%2C%5B21%2C22%2C23%2C24%5D%5D%5D&debug=0) to make testing easier. In the unfortunate case that the OP chooses not to allow this, a 17-byter will "fix" it: ``` .v+jk.n*\_*L\ME\E ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~15~~ 14 bytes With some inspiration from [Arnauld's solution](https://codegolf.stackexchange.com/a/171632/58974). Takes the indications as the first input, as a boolean array of `1`s and `0`s. ``` Ê?Vn@ÎãßUÅX:V ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=yj9WbkDOw6PfVcVYOlY=&input=WzEsMCwxXQpbW1sxLDIsMyw0XSxbNSw2LDcsOF0sWzksMTAsMTEsMTJdXSxbWzEzLDE0LDE1LDE2XSxbMTcsMTgsMTksMjBdLFsyMSwyMiwyMywyNF1dXQotUQ==) --- ## Explanation ``` :Implicit input of boolean array U=indications and multi-dimensional integer array V Ê :Get the length of U ? :If truthy (i.e., >0) Vn : Sort V @Îà : Function that gets the first element of U; 0 will leave the array untouched, 1 will reverse it. £ : Map each X ß : Run the programme again with the following inputs UÅ : U with the first element removed X : X will serve as the new value of V : :Else V : Just return V ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~122~~ 112 bytes ``` import StdEnv class$r::[Bool]->r->r instance$r where$_=id instance$[r]| $r where$[a:y]=if(a)reverse id o map($y) ``` [Try it online!](https://tio.run/##RY1PS8QwFMTv/RQBe9iFt7Av7f4r1IOoIHgQ1lsI8mhTDaRJSdKVgp/dGBUU5jC/GYbpjCKbRtfPRrGRtE16nJyP7Bz7O3spOkMhlL5pxI1zRm6ufVahbYhkO1V69v6mvCpfWt3/p8LLD/bXCWoW2ephRWuvLsoHxXTPXH6bVuWyTudIPhZX2k5zZC0TQiBwqKCWIHawhwMcszsBbgERkMtMAivAGnAHuM@IB8Aj4An4NhPPew68Al5LKYuWleLZzwruyQQF31ayn7f02Q2GXkPaPDym28XSqLtfeDIUB@fHLw "Clean – Try It Online") A version of Damien's Haskell answer using Clean's golfier type system. Really shows the extensive similarities between the two languages. Explained: ``` import StdEnv // import basic stuff class $ r :: [Bool] -> r -> r // $ takes a boolean list and returns a function on r to r instance $ r // instance on all types, taken when no more specific instances exist where $ _ = id // return the identity function for all arguments instance $ [r] | $ r // instance for lists of a type which has an instance itself where $ [a: y] = if(a) reverse id // reverse if the head of the argument is true o map ($ y) // composed with the map function acting on $ applied to the tail ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 54 bytes ``` f=->a,d{r,*z=d;r&&a.reverse!;d==[]?a:a.map{|w|f[w,z]}} ``` [Try it online!](https://tio.run/##NU7LDoIwELzzFXjhYEbClrek@iFNDyXASRNSRCKPb69LlD3szmQyM2vH@uNcJy83g2axOM@yqWwQmNC279YO7alqpFT6bq4mfJp@Wae1UxNmvW1O8RCEhoqRaD4vO7bYFxPvr2LXoFJkyFEwKkERiEBityiKQQkoBWVMKQcVoBIiYibYLyBiCI4/8jvzGI4WT/@eMqhXv/c7xUBv7gs "Ruby – Try It Online") [Answer] (untested but I *think* correct. compiler asm output looks like what I expect. Will update if/when I find time to write a test harness that creates and prints this data structure.) # GNU C++ (portable) 148 bytes ``` #include<algorithm> #include<cstdint> struct m{intptr_t d,l,a[];void R(int*r){if(*r)std::reverse(a,a+l);for(int i=0;d&&i<l;((m*)a[i++])->R(r+1));}}; ``` # GNU C++ (int=pointer and falls off a non-void function UB) 120 bytes ``` #include<algorithm> struct m{int d,l,a[],R(int*r){if(*r)std::reverse(a,a+l);for(int i=0;d&&i<l;((m*)a[i++])->R(r+1));}}; ``` This is a struct of depth counter, length, array of {integers or pointers}. In the bottom level of this non-binary tree (`depth==0`), the array of `intptr_t` is an array of integers. In higher levels, it's a `struct m*` stored in `intptr_t`. Traversal takes a cast. The `R()` reverse function is a member function because that saves declaring an arg, and saves a lot of `p->` syntax to reference the struct members vs. the implicit `this` pointer. **The only GNU extension is the [C99 flexible array member](https://en.wikipedia.org/wiki/Flexible_array_member) to make a variable-sized struct**, which is supported in C++ as a GNU extension. I could have used a `*a` member pointing to a separately-allocated array and have this be plain ISO C++. (And that would actually save a byte without requiring any other changes). I wrote this as a mockup / reference implementation for an asm version. --- The shorter version with just `int` also declares `R()` as returning `int` instead of `void`. These two bits of hackery are unrelated; this is just the "works on at least one implementation" version. It should work fine on 32-bit targets (where `int` can hold a pointer), as long as you compile with gcc7 or older, or disable optimizations. (`gcc8 -O3` assumes that execution can't reach the bottom of a non-`void` function because that would be UB.) x86 `gcc -m32 -O3` should work fine with gcc7, [like on Godbolt](https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAKxAEZSAbAQwDtRkBSAJgCFufSAZ1QBXYskwgA5AHoZHAMx8linggIEADoJBy0WYKgYAzAHSCCTZAGtMAD2QJWwTKbQBbGQEcRmC3lQWQRlaAHZaADYuUJl3EQYCPABafHdMIICWJgYk4kwAN0xiQWyOAAYAQXKKuW4FPBZkBhEsAGpFAGELdAY8ACNTBEVsarqGppbMTuzDYkIEd2HqrLTBTStMVsMTTHQAfQBVHj2GgnbQvkrqi2IRZDPFi9PW9EZSJg4AVj5PgBFSABKEFOACpiABKDhPYwQMHg7ogEB5QrFTAQJjvfgMSEqSrGEjAlhnPCKX5lVTobgRKkkhQdBiqKDuEHgj7fEm8fhfX7gpLDIHEfi0cE4y5VUK/KGS3FVK6VJgiIitYyaAjEdoKX7tLgRdyIgGqVpyLaYM7AZDIVpKzDuQitVj2wTuF6YYwNQiZUYSo0yVorPzrCRbIzGXaHY6nUZy2VVLj1RrNLDTBizeaLBQjK5x8aJqZ05DdSMZ5ZMVaBzbbUPoc5i65qu4PKE8U6q4h7M6vBiY77c1T5VB4atA0EQpt4GFwhFIgpFQRojEfXjY1TVfHEQnE0nkpSUnU0zoMpRMlls5tczl/Xn8iCC3jC0VeyUSlfRhVKlVqjVaql6kAGpQ%2BiaZoWlaqCtDadoOkwToum6LAeoEj6Af6awbMGOyUtGKHlq0IhsCGuw1tUrStDcDatI8tZlAAnHsJxEq27YvG8p69gBJGAVgqoIF%2BrRlBRmCsIIrT5NkviCKQGrYPxaRCa0mgDkSs6mMRHHGgwvEMOkwAEEMcrUcaeGehcIkDtWmhfD80o8LhLZqkxlI9n8hpSi%2BsoGTIdF2W2HaWWxNmAcYWl2P0Wn2sQxBMAAngJ7h9EUIDhZFMVoESeDACIojCQA7vMVoIJsZH3FGFQcaZg6tMORKtIKTk8kRlRleU1HjrCo6NRxzXNVOyKzvOkmLjwy4ymVZWteg4KAXkyBiHOrTjvleDCUtLBgFIZy6ZsfSoBoqDOlxumqaNnU0WuG7zVuGo2bS9JXRdnK8JNgFqpgmxqkwKIlAyHUkV1NFlcerKWSSl58hmApCqKam%2Brlun5ZseQWK0qDGPDLrca0vQWEd5ySh1rkytUxouMBlrWraZxQTBWBwQhLBEzI/YVb1qIQEVDwgu4knPLVVmTU2HHuGD2AClDuPVG%2BYEfuqpLarq%2BpuVKyGlgGaF4ZWuwlWMqP8caLCBEkaRxUUSTGHh9yZCJs6epUtTZgmkwal0BA9P0gxLFm8YTG0yaprp6aZjG7MUUwZxNlGtH0Vo9kdpg3GGoBMmCUEIliX4knDEnckKacykR15DEx5j6SKzRhnwYhJlM%2BZfnOQBIjeQ5tfWeLhM0QX0c%2BS8oesXXAXGkF9ihZsTARdFsXxcQiWj8lrSpYkGVZa0sM8ZtpH1sVVzPm3FTVyHL35GzG8PKHrQgpo3PVSzc7N5CW9US1MLX1M3yaMLB1DJeONlT1M6s2/wx0A90kgAjMQDLD8FAdgLSLAHw/XmjCKBH8vyyzKJNPIBAxD0zbtRM6zxaRkjujdKBMCiHnh4PzC4EdmruFDsiJkocWRIJ7sDbkkln5wPcq5LeeNYwKHSPgYwUhwSMGkJ8KQpAWDSDKBI1A0gOjkNIqIcQmw6i0AkQQaRwiRHWBAJ8BQphQifFoGEUIERqKhDMdRExERRFSAACwSL1LQMoZRJFaNIHIqQEidBuM0VIGRIi4CwBgIgFAe1NB4C0mQCgEAPCROiSAYAoQFCkDdAkWclA%2BgeL6A0UeUVpDqNIB4NIRIADyLAGAFICRIrAtC2BaQ8fgaaiRCg6BqaQewmAZoEEkFIIpucGAeLVHgPU/ThGMGcCgchjB%2Bg6EgCI1AqpMjtKSN0UkwAWAiHISY1oSQynCVNvrJIeFiBGByAwVASzhJ7OMMcl6mAkiFHuCQPAAAvTYSQADq2QNLfM0LsVgiRLSGwUFwHxyiJB0BEUMqQ4j3EdK8XYAAHBEJIER7FbBAqEUwChWgQFwIQEg2oFD0FaB0CJUSigkuFOS8hGitEilIAVJgWAp4QB0SAexERTBcHsci5FXA4xlCFQoGidjHGkD1KEexph7EyvlfYxVyrkUIpkZ46QPiQB%2BMZaQYJYTRBaEVOQSg8SqVT3oLsIlFrSDZUipoQpEzYXwqkYi6Qajl55RRWijFWLLQ4oUAympTKWVssoDC6Qkq9RcE%2BKYT4Mb42fETcm6IarZGaqENq0g/jAmcu5by/lgrhWivFbCwNaaNXeOzYyiNUhwVSroK4itXig25tIJ9TIXKgA%3D%3D%3D) where I included both versions (in different namespaces) and a non-member-function version. ### Ungolfed **The function arg, `int r[]`, is an array of 0 / non-zero integers that indicate whether a given depth should be swapped, starting with the outer-most level.** ``` #include<algorithm> // for std::reverse #include<cstdint> // for intptr_t. GNU C defines __intptr_t, so we could use that... struct m{ __intptr_t d,l,a[]; // depth = 0 means values, >0 means pointers. // l = length //__intptr_t a[]; // flexible array member: array contiguous with the struct void R(int r[]) { if(*r) std::reverse(a, a+l); // *r && std::reverse() doesn't work because it returns void. if(d) // recurse if this isn't the bottom depth for(int i=0 ; i<l ; i++) // tree traversal ((m*)a[i])->R(r+1); // with the rest of the depth list } }; // struct m ``` When we recurse, we pass `r+1`, so checking the current depth is always `*r`. An earlier version just passed `r` unchanged, and checked `r[d]`. With a flexible array member, I needed to store some kind of last-level indicator because `a[]` is not a pointer, it's a true array with no indirection. But with a `intptr_t *a` member, I couldn't just have that be `nullptr` for the leaf level, because I want it to be values. Reversing the current level before or after the tree traversal shouldn't matter. I didn't try to do it *during*. I'm not *sure* that `std::reverse` is worth the byte count vs. a manual loop, especially if I can work in calling `R()` on each pointer exactly once somewhere inside that loop. But only if `d!=0` [Answer] # Mathematica, 7 bytes ``` Reverse ``` Function. Give it a nested list as the first argument, and the 1-based list of levels/dimensions to reverse as the second argument. [Try it online!](https://tio.run/##bVAxDsJADNt5RUaQbiC50hYh/oBYEUNBBTrAABXL6d5enFyrAuqQIbbjJL5X7a2@V21zrrruQlua7@t3/XzVi023ezaP9nA5hBDYkTjyjrLoKKwc5Y4KR6V2a0e8REHDEhUJDCVnKCg5V4ih5hIFtSwVEfWEqUArWbRBQD4ej5vZuLrfrCwMdXNS/stMMEkVg7X8EuNPyRcfTYxPOSpmpoafmityQ0hBvzY77lNa24p0sfbeNg2pFSbw6fUQ0jFln3GeRrUz2g@sRSHD9ArTcbwNt/Qx6uD31YmRCUyh7gM "Wolfram Language (Mathematica) – Try It Online") Finally, another challenge where Mathematica has a builtin! [Answer] # [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), 6 bytes ``` ∧(⍉⍥⇌) ``` [Try it!](https://uiua.org/pad?src=0_8_0__ZiDihpAg4oinKOKNieKNpeKHjCkKCmYgMV8wXzEgWwogIFtbMSAyIDMgNF0KICAgWzUgNiA3IDhdCiAgIFs5IDEwIDExIDEyXV0KCiAgW1sxMyAxNCAxNSAxNl0KICAgWzE3IDE4IDE5IDIwXQogICBbMjEgMjIgMjMgMjRdXV0KCmYgWzEgMV0gW1s3XV0KZiBbMV0gWzEgMiAzIDQgNSA2IDddCg==) Takes the array and a mask of which dimensions to reverse like `[1 0 1]`. ``` ∧(⍉⍥⇌) ∧( ) # fold over mask and array, using array as accumulator ⍥⇌ # reverse the array either 0 or 1 times ⍉ # transpose ``` ]
[Question] [ ### Definition The Alternating Power Fibonacci Sequence is formed as follows. 1. Start with the empty sequence and set **n** to **1**. 2. Compute **f**n, the **n**th non-negative [Fibonacci number](https://en.wikipedia.org/wiki/Fibonacci_number), with repetitions. **0** is the first, **1** is the second and the third, **2** is the fourth. All others are obtained by summing the two previous numbers in the sequence, so **3 = 1 + 2** is the fifth, **5 = 2 + 3** is the sixth, etc. 3. If **n** is odd, change the sign of **f**n. 4. Append **2n-1** copies of **f**n to the sequence. 5. Increment **n** and go back to step 2. These are the first one hundred terms of the APF sequence. ``` 0 1 1 -1 -1 -1 -1 2 2 2 2 2 2 2 2 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 ``` ### Task Write a full program or a function that takes a positive integer **n** as input and prints or returns the **n**th term of the APF sequence. If you prefer 0-based indexing, you can alternatively take a non-negative integer **n** and print or return the APF number at index **n**. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); may the shortest code in bytes win! ### Test cases (1-based) ``` 1 -> 0 2 -> 1 3 -> 1 4 -> -1 7 -> -1 8 -> 2 100 -> -8 250 -> 13 500 -> -21 1000 -> 34 11111 -> 233 22222 -> -377 33333 -> 610 ``` ### Test cases (0-based) ``` 0 -> 0 1 -> 1 2 -> 1 3 -> -1 6 -> -1 7 -> 2 99 -> -8 249 -> 13 499 -> -21 999 -> 34 11110 -> 233 22221 -> -377 33332 -> 610 ``` [Answer] # [Python 2](https://docs.python.org/2/), 30 bytes ``` f=lambda n:n<1or f(n/4)-f(n/2) ``` [Try it online!](https://tio.run/nexus/python2#FY1LCoAwDETXeorZaSFF6wdF1IuIC0UKgkaR3r8mbzGZPAKJfrq2ez828MCjez74nIvGWB2ViV5MwMlYHKEi1ISG0BF6gitLca1Eq01WTUW0IufKOqTJ@50cEAiZnTOSJ8HEHw "Python 2 – TIO Nexus") One-indexed. The sequence felt like a puzzle, something that Dennis generated by having a short way to express it. The power-of-two repetitions suggest recursing by bit-shifting (floor-dividing by 2). The alternating-sign Fibonacci recursion `f(n)=f(n-2)-f(n-1)` can be adapted to bitshift in place of decrementing. The base case works out nicely because everything funnels to `n=0`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` BLCÆḞ ``` **[Try it online!](https://tio.run/nexus/jelly#@@/k43y47eGOef@P7jnc/qhpjfv//9GGOgpGOgrGOgomOgrmOgoWOgqGBgZAMVMgYQpiAbkgEgSAwiAAVA4CsQA "Jelly – TIO Nexus")** ### How? Extending the Fibonacci series back into negative indexes such that the relation `f(i) = f(i-2) + f(i-1)` still holds: ``` i ... -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 4 5 ... f(i) ... -21 13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 ... ``` Going back from `i=0` the numbers are those we need to repeat **2n-1** times, and Jelly's Fibonacci built-in, `ÆḞ`, will calculate these. We can find the `-i` (a positive number) that we need by taking the bit-length of `n` and subtracting `1`. Since we want `i` (a negative number) we can instead perform `1-bitLength` and Jelly has an atom for `1-x`, `C`, the complement monad. ``` BLCÆḞ - Main link: n e.g. 500 B - convert n to a binary list [1,1,1,1,1,0,1,0,0] L - get the length 9 C - complement -8 ÆḞ - Fibonacci -21 ``` [Answer] # Mathematica, ~~43~~ ~~36~~ 24 bytes ``` Fibonacci@-Floor@Log2@#& ``` 7 bytes saved thanks to @GregMartin, and a further 12 thanks to @JungHwanMin. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~19~~ ~~17~~ ~~16~~ 11 bytes ``` lOiB"yy-]x& ``` Input is 1-based. [Try it online!](https://tio.run/nexus/matl#@5/jn@mkVFmpHVvh7qQUH6v2/78xCAAA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S/if45/ppFRZqRtbofY/wqWsIuS/IZcRlzGXCZc5lwWXoYEBl5GpAZcpkAaygQQIcBmBAJcxCAAA). ### How it works For 1-based input **n**, let **m** be the number of digits in the binary expansion of **n**. The **n**-th term in the output sequence is the **m**-th term in the Fibonacci sequence, possibly with its sign changed. One idea would be to iterate **m** times to compute terms of the Fibonacci sequence. This is easy with a `for each` loop using the array of binary digits. If the Fibonacci sequence were initiallized with **0**, then **1** as usual, iterating **m** times would result in **m+2** terms on the stack, so the top two numbers would have to be deleted. Instead, we initiallize with **1**, then **0**. That way the next generated terms are **1**, **1**, **2**, ... and only *one* deletion is needed. The sign could be dealt with by using another loop to change sign **m** times. But that's costly. It is better to integrate the two loops, which is done simply by *subtracting* instead of adding in the Fibonacci iteration. ``` l % Push 1 O % Push 0 iB % Input converted to binary array " % For each yy % Duplicate top two elements - % Subtract. This computes the new Fibonacci term with the sign changes ] % End x % Delete top number & % Specify that implicit display should take only one input % Implicitly display the top of the stack ``` [Answer] ## JavaScript (ES6), 33 bytes ``` f=(n,p=1,c=0)=>n?-f(n>>1,c,p+c):p ``` 1-indexed. A port of [xnor's answer](https://codegolf.stackexchange.com/a/108814/42545) would be 23: ``` f=n=>n<1||f(n/4)-f(n/2) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~83~~ ~~82~~ 79 bytes ``` def f(n,a=0,b=1): l=bin(n)[2:] for _ in l:a,b=b,a+b return a*-(len(l)%2or-1) ``` [Try it online!](https://tio.run/nexus/python2#DcpBCoAgEAXQvaf4m8AphXQpeJKIUFIQhhGkzm@99Zt3qahaTIq7ydFRUOCYm2ihw4dTofaBC03AIf0jm7RlhVGedwjSajUX0UyL78M6mvMD "Python 2 – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` BLµ’ÆḞN⁸¡ ``` Uses one-based indexing. [Try it online!](https://tio.run/nexus/jelly#@@/kc2jro4aZh9se7pjn96hxx6GF/4/uOdz@qGmN@///hjoKRjoKxjoKJjoK5joKFjoKhgYGQDFTIGEKYgG5IBIEgMIgAFQOAgA "Jelly – TIO Nexus") ## Explanation This method works if your Fibonacci function only supports non-negative arguments. ``` BLµ’ÆḞN⁸¡ Input: integer n B Binary digits of n L Length. len(bin(2)) = floor(log2(n))) µ Start new monadic chain on x = len(bin(2)) ’ Decrement ÆḞ Get Fibonacci(x-1) ⁸¡ Repeat x times on that N Negate. Return Fibonacci(x-1) if x is even else -Fibonacci(x-1) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes ``` Mg1-¢l ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=TWcxLaJs&input=MTAw) ### How it works As mentioned in other answers, the **n**th term in the alternating-sign Fibonacci series is the same as the **-n**th term in the regular series. **n** can be found by taking the bit-length of the input and subtracting one; negating this results in 1 minus the bit-length. ``` Mg1-¢l ¢l // Calculate the length of the input in binary. 1- // Subtract this from 1. Mg // Get the Fibonacci number at this index. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 10 bytes Uses 1-based indexing **05AB1E**'s Fibonacci function returns positive fib numbers less than *n*, meaning we'd have to generate more than necessary, get the correct one by index and then calculate the sign. So I doubt any method based around that will be shorter than calculating the numbers iteratively. Uses the realisation that we can initialize the stack with `1, 0` reversed to handle the case when `n=1` as described in [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/108813/47066). ``` XÎbgG‚D«`- ``` [Try it online!](https://tio.run/nexus/05ab1e#@x9xuC8p3f1RwyyXQ6sTdP//NwYBAA "05AB1E – TIO Nexus") **Explanation** ``` X # push 1 Î # push 0 and input b # convert input to binary g # get length of binary number G # for N in [1...len(bin(input))-1] do: ‚ # pair the top 2 elements of the stack in a list D # duplicate the list « # concatenate the 2 lists together ` # split into separate elements on the stack - # subtract the top 2 elements ``` [Answer] # [Perl 6](http://perl6.org/), 53 bytes ``` {flat(((0,1,*+*...*)Z*|<-1 1>xx*)Zxx(1,2,4...*))[$_]} ``` Straightforward implementation of the sequence, the way it was described. Zero-based. [Answer] # [Julia 0.5](http://julialang.org/), 19 bytes ``` !n=n<1||!(n/=4)-!2n ``` [Try it online!](https://tio.run/nexus/julia5#FcZBCoMwFIThtZ7iRRASGGkSE3ShpQfpMhXcTEVceveYfIt/JiuuXNx9K83XGsygPPP2P4WyU7SDx4iACTOctfDRIpYtv6SCrzBWpm0@x7nz2nTXxyTDW/qQvuxAKJr2x5Qf "Julia 0.5 – TIO Nexus") ### How it works This uses the same formula as [@xnor's Python answer](https://codegolf.stackexchange.com/a/108814/12012). The recurrence relation **g(n) = g(n-2) + g(n-1)** generates the negative terms of the Fibonacci sequence, which equal the positive terms with alternating signs. From anywhere in a run of **2**k repetitions of the same number, we can pick any repetition of the previous run of **2**k-1 numbers and the run of **2**k-2 numbers before those by dividing the index by **2** and **4**. Rather than the straightforward ``` f(n)=n<1||f(n÷4)-f(n÷2) # 25 bytes ``` we can redefine an operator for our purposes. Also, **f** will work just as fine with floats, so we get ``` !n=n<1||!(n/4)-!(n/2) # 21 bytes ``` Finally, if we update **n** with a division by **4**, wwe can write **n/2** as **2n** and omit a pair of parens, leading to the 19-byte function definition in this answer. [Answer] # [J](http://jsoftware.com/), 18 bytes ``` (%>:-*:)t.@<:@#@#: ``` Uses one-based indexing. Takes an input integer *n* > 0 and computes `floor(log2(n))` by finding the length of its binary representation and then decrements that value by one. It then finds the `floor(log2(n))-1`*th* coefficient of the generating function *x*/(1 + *x* - *x*2) which is the g.f for the negative-indexed Fibonacci values. [Try it online!](https://tio.run/nexus/j#FcY7CoAwEIThPqcYDEIiGjYvlEUldxGDnY33j9mv@GdaxcEw48nLxPZzZeeii2al7ut5YWZXB7LwCIhIWLHBEyFkQu7bf49AEIiitR8 "J – TIO Nexus") ## Explanation ``` (%>:-*:)t.@<:@#@#: Input: integer n #: Binary #@ Length <:@ Decrement ( ) The generating function x/(1+x-x^2) >: Increment x *: Square x - Subtract % Divide x by previous t. Get series coefficient at the index given by previous value ``` ]
[Question] [ Your task is to, given an unsigned integer `n`, find the largest number which can be created by removing a single byte (8 consecutive bits) of data. --- ## Example Given the number `7831`, we first convert it to binary (removing any leading zeroes): ``` 1111010010111 ``` We then find the consecutive group of 8 bits which, when removed, will yield the largest new result. In this case, there are 3 solutions, shown below ``` 1111010010111 ^ ^ ^ ^ ^ ^ ``` Removing this any of these yields `11111`, which we then convert back to its decimal value `31` for the answer. --- ## Test Cases ``` 256 -> 1 999 -> 3 7831 -> 31 131585 -> 515 7854621 -> 31261 4294967295 -> 16777215 (if your language can handle 32 bit integers) ``` --- ## Rules * It is guaranteed that the bit length of `n` will be larger than 8. * Your solution should theoretically work for any bit length of `n` larger than 8, but in practice, needs only work for integers **255 < n < 216** * Input/Output should be in decimal. * You may submit a full program or a function. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program (in bytes) wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` BḄ-8ƤṀ ``` A monadic link taking a number and returning a number. **[Try it online!](https://tio.run/##y0rNyan8/9/p4Y4WXYtjSx7ubPj//7@5hamJmZEhAA "Jelly – Try It Online")** ### How? Uses a nice [quick](https://github.com/DennisMitchell/jelly/wiki/Quicks), `Ƥ`, developed by [miles](https://codegolf.stackexchange.com/users/6710/miles)... ``` BḄ-8ƤṀ - Link: number B - convert to a binary list Ƥ - for loop over some slices to be determined... -8 - this is a negative nilad, therefore: use overlapping outfixes of length 8 - (exactly what the specification asks us to inspect) Ḅ - convert from a binary list to an integer (vectorises) Ṁ - maximum ``` [Answer] # [J](http://jsoftware.com/), 12 bytes ``` [:>./8#.\.#: ``` [Try it online!](https://tio.run/##y/r/P81WTyHayk5P30JZL0ZP2ep/anJGvkKagpGpGReUaWlpCWMaGhuaWpjCeOYWpiZmRoYwromRpYmlmbmRpanCfwA "J – Try It Online") ``` #: to binary 8 \. remove consecutive groups of eight #. convert each result to decimal >./ maximum [: do nothing, this lets me avoid parentheses ``` [Answer] # [Python 2](https://docs.python.org/2/), 41 bytes ``` f=lambda n:n>>8and max(n>>8,2*f(n/2)+n%2) ``` [Try it online!](https://tio.run/##FYxBCoMwEADP7Sv2UkjqgmTNxqygHyk9pEioUFcRD@3rU73NzGHW3/5elErJ/SfNrzGBdjoMMekIc/qak5Hu2WhNttIb2ZKXDRQmhQdxQBARhDY2DsE1jiOfxj7QETyJl9CS8LO7XtZt0h2MIhw7a8sf "Python 2 – Try It Online") [Answer] ## JavaScript (ES6), 54 bytes ``` f=(n,v=n>>8,b=1,m=0)=>b>v?m:f(n,(v^n)&b^v,b+b,v>m?v:m) ``` ``` <input type=number min=256 max=2147483647 oninput=o.textContent=f(this.value)><pre id=o> ``` Works up to 2\*\*31-1. Because someone asked for a bit-twiddling answer... [Answer] # [Pyth](https://pyth.readthedocs.io), 21 bytes ``` L&K.>b8eS,K+*2y/b2%b2 ``` This is a recursive function (must be called with `y`, or see the link). **[Try it here!](https://pyth.herokuapp.com/?code=L%26K.%3Eb8eS%2CK%2B%2a2y%2Fb2%25b2%3By&input=7831&test_suite=1&test_suite_input=7831%0A131585&debug=0)** [Answer] # Mathematica, 69 bytes ``` Max@Array[Drop[#&@@s,#;;#+7]~FromDigits~2&,Last[s=#~RealDigits~2]-7]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfN7HCwbGoKLEy2qUovyBaWc3BoVhH2dpaWds8ts6tKD/XJTM9s6S4zkhNxyexuCS62Fa5Lig1MQcmHKtrHqv2P6AoM6/EIS3axMjSxNLM3MjSNPY/AA "Wolfram Language (Mathematica) – Try It Online") This solution works for **large** numbers [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfN7HCwbGoKLEy2qUovyBaWc3BoVhH2dpaWds8ts6tKD/XJTM9s6S4zkhNxyexuCS62Fa5Lig1MQcmHKtrHqv2P6AoM6/EIS3a0CDO0MDAIPY/AA "Wolfram Language (Mathematica) – Try It Online") -3 bytes from KellyLowder [Answer] # [Python 3](https://docs.python.org/3/), 68 66 60 bytes -2 bytes thanks to [Mr. Xcoder!](https://codegolf.stackexchange.com/users/59487/mr-xcoder) -4 bytes thanks to [ovs!](https://codegolf.stackexchange.com/users/64121/ovs) -2 bytes thanks to [Erik the Outgolfer!](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) ``` lambda n:max(n%2**i|n>>i+8<<i for i in range(len(bin(n))-9)) ``` [Try it online!](https://tio.run/##FYxBDoIwEADP@ooNiUmL5dBCgSXYj6iHEqluAgshHDTx79UeZyaZ9bO/Fi5juNzi5Ofh4YG72b8Fn0ye05edo3Pb9wRh2YCAGDbPz1FMI4uBWLCUBUoZU@aUr8bWChBRQdOWWoEutW1tIlvV5i8qgxXWjUF7746HdSPeBSvICpcpCOkYfw "Python 3 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes ``` Floor@If[#<256,0,Max[#/256,2#0[#/2]+#~Mod~2]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n1aaZ/vfLSc/v8jBMy1a2cbI1EzHQMc3sSJaWR/ENlI2ALFitZXrfPNT6oxiY9X@BxRl5pVEA3XqO1SD1FhaWuqYWxgb6hgaG5pamALZpiZmRoY6JkaWJpZm5kaWprWx/wE "Wolfram Language (Mathematica) – Try It Online") This version can only handle inputs up to 2518-1, otherwise we run into Mathematica's stack size limit. (The bound may vary between Mathematica installations.) The second solution in this answer avoids that. # How it works A recursive approach based on the following logic: * The maximal value should be `0` for any input less than `256`, since taking a byte out of the number eats the whole number. This is our base case, which is why it's included even though the specs promise us we won't have to handle such inputs. * Otherwise, we take the `Max` of two options: eat the lowest byte (giving us the input divided by `256`) or chop off the lowest bit, recurse on the remaining integer, and append the lowest bit back when we're done. # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 55 bytes ``` Max@Table[Mod[#,m=2^k]+Floor[#/m/2^8]m,{k,0,Log2@#-8}]& ``` [Try it online!](https://tio.run/##DcxBC4IwFADgHyN06cXac5t7B2GnTgkduo0Jq7RE50AWBOJvX96@0xd8@nTBp@Hpc/@d69z4n7n7x9TZJr5sAaHGdnTHyxTjYgsWGLbaBVhHOMM1vtEUJ725Q74tw5zsXjCzolRARFDpkgMvudRytxQKOQgkQapCkpvLfw "Wolfram Language (Mathematica) – Try It Online") An alternate version that builds a table instead of recursion, so it works for numbers of any size that Mathematica can handle. [Answer] # [Retina](https://github.com/m-ender/retina), ~~71~~ ~~67~~ 64 bytes ``` .+ $* +`(1+)\1 $+0 01 1 . $`_$'¶ _.{7} A`_ O^` 1G` +1`\B :$`: 1 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLSztBw1BbM8aQS0XbgMvAkMuQS49LJSFeRf3QNq54vWrzWi4ux4R4Lv@4BC5D9wQubcOEGCcuK5UEKy7D//@NTM24LC0tucwtjIE6jQ1NLUwB "Retina – Try It Online") Link only includes the faster test cases, so as not to unduly overload Dennis's server. Edit: Saved 3 bytes thanks to @MartinEnder. Explanation: ``` .+ $* +`(1+)\1 $+0 01 1 ``` Convert from decimal to binary. ``` . $`_$'¶ _.{7} A`_ ``` Construct a list of strings obtained by deleting 8 consecutive digits in all possible ways. ``` O^` 1G` ``` Sort them in reverse order and take the first (largest). ``` +1`\B :$`: 1 ``` Convert back to decimal. (See @MartinEnder's [explanation](https://codegolf.stackexchange.com/a/102263).) [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~138~~ 134 bytes ``` i->{int l=0,m=0,x;String y=i.toString(i,2);for(;l<y.length()-7;m=x>m?x:m)x=i.valueOf(y.substring(0,l)+y.substring(l+++8),2);return m;} ``` [Try it online!](https://tio.run/##fY9NSwNBDIbv@ytynGG3Qy1qi9OtoCAIiocepYdpO62p87HMZMoupb99XdsVBaGBQPLmSci7U3s18JV2u/Vni7bygWDXaSIRGvGCkWT2T94ktyL0TjzgU19eoh69i8nqcIn5vZNVaWlwBSujYoRXhe6QRVLUST/Q9NmR3upQQF/MYNmQjlBCi4PZAR2BKYeF7bKWcwrottCUKMifG4bFiMuND0yaaSOMdlv6YHwwlrasZ/a@vrO87vi9Mkm/bVgjYlrG8@qwMDz/K5g8zyf8@2DQlIIDK4@t7F30n@89rsF2Xtj5gfcFKA6HDPqYN5G0FT6RqLo5sZMfoarKNGw8ubm@HV1xLk/88dh@AQ "Java (OpenJDK 8) – Try It Online") [Answer] # [ReRegex](https://github.com/TehFlaminTaco/ReRegex), ~~294~~ 275 bytes *Saved 19 bytes by using better 'function' definitions* I'd say this is pretty good for a Regex only language. The base lib does allow for conversion between Unary and Decimal (Which is needed as the challenge spec explicitly states decimal), but does not support Binary; So I had to write that as part of the script adding 120 bytes to it. ``` #import base b(\d*):(_*)\2_b/b1$1:$2b/b(\d*):(_+)\2b/b0$1:$2b/b(\d+):b/$1/b:b/0/B(_*):1/B$1$1_:/B(_*):0/B$1$1:/B(_*):B/$1/j(\d*),\1(\d)(\d{7})(\d*):/j$1$2,$1$2$3$4:,B:$1$4B/j(\d*),\1\d{0,7}:,?(.*)/,$2,/,((_+)_+),(\2),/,$1,/,(_+),(\1_*),/,$2,/^,(_*),$/d<$1>/j,b:u<(?#input)>b: ``` [Try it online!](https://tio.run/##TU7tCsIwDPzvUwjmRzuDWaYwCWNCn2M4LBviwA/mBoL47DN1DoU0yV3umrR1Wx/rxzAsTufbte3m/nCvZ94UVWTFlJEtktKTZ2CBRJtpsNSBwviPX1rxBExeS0wumIXJgXpL@eJ4xBN0Qd98/sSCtVp9z/RlxzXUqDjBkGANG0En2m/cz6LqGNOX4M6sIkuoakITztNAUyRWMXAgR4J1LY66PYYbEKjKgHNq0Eufmd3idLn1nc29DEO6XfMb "ReRegex – Try It Online") ## By Individual Regexes. ``` #import base b(\d*):(_*)\2_b/b1$1:$2b/ b(\d*):(_+)\2b/b0$1:$2b/ b(\d+):b/$1/ b:b/0/ B(_*):1/B$1$1_:/ B(_*):0/B$1$1:/ B(_*):B/$1/ j(\d*),\1(\d)(\d{7})(\d*):/j$1$2,$1$2$3$4:,B:$1$4B/ j(\d*),\1\d{0,7}:,?(.*)/,$2,/ ,((_+)_+),(\2),/,$1,/ ,(_+),(\1_*),/,$2,/ ^,(_*),$/d<$1>/ j,b:u<(?#input)>b: ``` ## Steps Firstly, we import the 'base' library, which gives two regexes. One which converts `u<numbers>` into unary. And one which converts `d<unary_underlines>` back into decimal. This is because the challenge requires IO in base10. Then we define a handful of regexes which convert unary into binary. ``` b(\d*):(_*)\2_b/b1$1:$2b/ b(\d*):(_+)\2b/b0$1:$2b/ b(\d+):b/$1/ b:b/0/ ``` The first of these, `b(\d*):(_*)\2_b/b1$1:$2b/` searches for `b`, optionally followed by some binary digits, then a `:`, Then any amount of underlines, followed by the exact same amount of underlines plus one, and finally another `b`. We then replace that with `b1` followed by the binary digits from before, `:`, and just the first half of the underscores, and finally the last `b`. So this checks if the unary is not divisible by two, and if so, prepends 1 to it's binary digits, then divides it minus one by two. The second one, `b(\d*):(_+)\2b/b0$1:$2b/` is almost idendical, however does not check for an extra `_`, meaning it only matches if it is divisible by two, and in this case prepends a `0` instead. The third one checks if we're out of unary digits, and if so, strips away the padding to just leave the binary digits. The last one checks if there never was any binary digits supplied, and in that case just leaves `0`. The next group of Regexes we define are to convert binary back into unary, and are slightly more simple. ``` B(_*):1/B$1$1_:/ B(_*):0/B$1$1:/ B(_*):B/$1/ ``` The first of this group, `B(_*):1/B$1$1_:/`, much like its antithesis, detects a `B`, followed by any amount of Unary digits, then `:1`. It doesn't check for the matching `B` in this case, as it is only searching for one digit at a time. If this is matched, it doubles the previously matched amount of unary digits and adds one, then removes the one. The second, `B(_*):0/B$1$1:/`, is almost idendical to the first, except matches a `0` rather than a `1`, and does not add an additional unary digit. The last of these, `B(_*):B/$1/`, checks if there are no more binary digits, and if so unwraps the unary. Unlike its antithesis, this does not need a special 0 case. Next we define the `j` regexes, which act as a splitting function. ``` j(\d*),\1(\d)(\d{7})(\d*):/j$1$2,$1$2$3$4:,B:$1$4B/ j(\d*),\1\d{0,7}:,?(.*)/,$2,/ ``` The first, `j(\d*),\1(\d)(\d{7})(\d*):/j$1$2,$1$2$3$4:,B:$1$4B/` does most of the heavy lifting. It searches for `j`, optionally followed by binary digits which are the "incrementer", then a comma followed by the incrementer then exactly 8 binary digits followed by the rest of the binary number, then a `:`. The first of the 8 digits is appended to the incrementer, thus incrementing it, then everything but those 8 digits from the binary input is appended after the `:` following a `,`. So (If we were using 2 digits instead of 8) `j,1001:` would become `j1:1001:,01` then `j10:1001,01,11`. Additionally, the appended array elements are wrapped in `B`s, to convert them back to unary. The other, `j(\d*),\1\d{0,7}:,?(.*)/,$2,/` checks if there are less than 8 binary digits left to check after the incrementer, and if so, removes everything other than the array wrapped in `,`s. Eg. `,_,___,` During and after the creation of the array we define the comparison regexes. ``` ,((_+)_+),(\2),/,$1,/ ,(_+),(\1_*),/,$2,/ ``` The first of these, `,((_+)_+),(\2),/,$1,/` checks a comma followed by some amount of underscores, then some more, followed by a comma, then the first amount of underscores, than a comma. It then replaces it with the total amount of underscores in the first element surrounded by `,`s. The latter, `,(_+),(\1_*),/,$2,/`, checks for a comma followed by some amount of underscores followed by another comma, then the same amount or more underscores, and a last comma. This will instead leave the right element. Finally, when there is on element left thus matching `^,(_*),$`, we remove the surrounding commas and convert back to decimal via `d<>`. Then no-more regexes can fire and the output is presented. The input is initially placed into the template `j,b:u<(?#input)>b:`, which first converts the decimal input to unary, eg `5` -> `j,b:_____b:`, then the resulting unary to binary, `j,101:` Then splits the binary (which doesn't work for the example), gets the largest element, converts back to decimal, and done. [Answer] # C (gcc), ~~91~~ bytes ``` j;m;t;f(x){for(j=m=0;t=x>>j+8;m<t?m=t:j++)t=t<<j|x%(1<<j);return m;} ``` -23 bytes from [Colera Su](https://codegolf.stackexchange.com/users/75905/colera-su) Supports up to `2**31-1` [Try it online!](https://tio.run/##XU7RaoQwEHzWr1gOhERTatRobMz1Q6wUEb0q6JUYi9Tm2228Fnr0ZWdndpmZ5uHSNPs@iFFo0aEVb91VoUGOMhRarufzEHAxFvp5lPppCAKspS6K4Wv1ELWIhWr1oiYYhdn7ScNY9xM6llpdGgLNW63A9y35wLC5znHR7axfm3pu55JVZVSBBNi2iKUEqCFbnucktkhjyjgjjDJLMs6SNKIkplF6PEU0yRIep0lGeMx5GmbGCNex3eGW3lvTUFgoYO4/22uH/lLx46/k32kCgqC/VXTelXXo0KlD3oKtj7eAPObLdCL35fuqDCsC99Y/Gv7/RitsyxnX7N8 "C (gcc) – Try It Online") Starts with the low 8 bits `(j=0)`, then goes up, changing output if the number with bits `[j,j+8)` cut out is bigger than our current, and continuing until x has no bits above `j+8` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` BJṡ8ḟ@€ƊịBḄṀ ``` [Try it online!](https://tio.run/##ASkA1v9qZWxsef//QkrhuaE44bifQOKCrMaK4buLQuG4hOG5gP///zEzMTU4NQ "Jelly – Try It Online") Saved bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)! [Answer] # JavaScript (ES6), ~~94~~ 91 bytes *-3 bytes thanks to Justin Mariner* ``` f=(n,d='',c=n.toString(2).match(`(${d}).{8}(.*)`))=>c?Math.max('0b'+c[1]+c[2],f(n,d+'.')):0 ``` Just throwing out a JavaScript string-based solution, but I'm hoping someone will post a separate bitwise-based solution so I might learn something. My solution recursively grabs an 8-bit chunk from the string, taking the maximum value that is found. ``` f=(n,d='',c=n.toString(2).match(`(${d}).{8}(.*)`))=>c?Math.max('0b'+c[1]+c[2],f(n,d+'.')):0 console.log(f(256)); console.log(f(999)); console.log(f(7831)); console.log(f(131585)); console.log(f(7854621)); console.log(f(4294967295)); ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 122+13=135 120+13=133 bytes ``` n=>{int m=0,i=0,t;for(var b=Convert.ToString(n,2);i<b.Length-7;m=t>m?t:m)t=Convert.ToInt32(b.Remove(i++,8),2);return m;} ``` [Try it online!](https://tio.run/##jY7BSsNAEIbP7lPscZemwSSmTdwmooIgVBBb6DlJx7rYnYXdSaCEPHuMguLJepg5DN//zd/4eWMdjK3XeOCbkycwijXHynv@3DNPFemGP7TYrDRSwKdV8m31Drd3JwJe8BGLsp@u3BSXgZ6G1Kt1oqscr4t7ix04Crd2Q256IDCIpdKrOlwDHuhtvlSmoNLc0LWR9At/REpiUYcvYGwHQs9mQSY/sw6odciNGkbFvut1Vu/5U6VRSNazi0nj7RHCndMEa40gfgqLOF1Iqf5m8jw/yyyzJDoLRUmUZuk/XOnVIv7SDWwYPwA "C# (.NET Core) – Try It Online") +13 for `using System;` I imagine there is a way of doing this with out using `Convert`. Either way, I'm sure this could be reduced. ### Acknowledgements -2 bytes thanks to Kevin Cruijssen ### UnGolfed ``` n=>{ int m=0, i=0, t; // convert n to a binary string, // go through removing each possible byte, // check if this is the biggest int so far for (var b=Convert.ToString(n,2); i<b.Length-7; m=t>m?t:m) t=Convert.ToInt32(b.Remove(i++,8),2); // remove 8 bits from position i, then convert from binary string to int return m; } ``` [Answer] # PHP, 67+1 bytes ``` do$r=max($r,$argn&($x=2**$i++-1)|$z=$argn>>8&~$x);while($z);echo$r; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/def23552a374ff3641de52e3ed9da2d8c8dc43b5). [Answer] # Pyth, 19 bytes ``` eSmi.>>.<.BQd8d2a6l ``` Alternative answer: ``` eSmi.<<8.>.BQdd2a6l ``` Explanation: ``` eSmi.>>.<.BQd8d2a6lQ | Implicit Q at the end, where Q = input m a6lQ | Map the over [0, 1, 2, ... , floor(log base 2 of Q) - 7] .BQ | Convert Q to binary string .< d | Cyclically rotate left by d > 8 | Get string from position 8 to end. .> d | Cyclically rotate right by d i 2 | Convert from binary string to integer eS | Find the last element of sorted list (maximum value) ``` The other answer uses a similar approach, except that it rotates right first, and gets all bits except the last 8. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~23~~ 21 bytes ``` Bn8-:"GB[]@8:q+(XBvX> ``` [Try it online!](https://tio.run/##y00syfn/3ynPQtdKyd0pOtbBwqpQWyPCqSzC7v9/cwtjQwA "MATL – Try It Online") ``` B % Implicitly grab input, convert to binary n8-: % Create list of 1,2,... n-8, with n the size of the binary string " % Loop over this list GB % Grab the input again, convert to binary once more. @8:q+ % Create indices of a slice of length 8 []( % Index into binary string, delete the slice XB % Convert the remainder from binary to integer vX> % Get the maximum number so far. ``` Sadly, `Bn8-:8:!+q&)` only produces the slices to be removed, not the remainder we'd like to keep. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 73 bytes ``` n->{int m=0,i=1;for(;i<n>>7;i*=2)m=Math.max(m,n&~-i|(n>>8&-i));return m;} ``` [Try it online!](https://tio.run/##TY9Pb4JAEMXvfoqJSc1igIgW/62Q2KRNevBkb8bDCquusrtkGayG0q9OkRDtbWZ@b97MO7ELc3TK1Sk@V0Km2iCc6pmbo0jcfa4iFFq5fdppYYYMRfRPszSG3bK7opPmu6RmUcKyDFZMKCg6AO20XbxoEYOsGVmjEeqw2QIzh8xqpABf@lPhR3t2Udf8wE0IO4F8@XZDDgFUygkLoRBkMLBF4NG9NoSKhQrDCRX9YGjJYMXw6Ep2JdJWvV9H/JCaTnuOsCxqOOZGgaRlRZubGRrOJFH8G2rbzbYY@mMbZrOZDZPpyLPBG3n@1L93/ut46JVWswbg7vSVx@TRppyfiQAnhGJ9y5BLV@fopnVM3JPuizeI59C1QVj0aSFZ2mQmj4gPVOd6Z9GRPL3m88YsUdb987JTVn8 "Java (OpenJDK 8) – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~81~~ 80 bytes ``` @(x)max(bin2dec(dec2bin(x*(c=2.^(0:(b=nextpow2(x+1)-8))))(:,[1:b b+9:end]))'./c) ``` [Try it online!](https://tio.run/##TclRC4IwFAXg936Fb96bbbWrU@9A6H9EgZsTfEiFpPbvl1FgBw6cjzO5pX362DdSyniGgPc2gB1G6ryDtbRuCHtwDckbnAzYZvRhmacXQcgUihrXgDlclLGJzdj4sbsipvLoMHbDY4ZUCJHirgfSZfLNR8z8p6rO1SaVK13r7dNFSeqngrjgsiLWGN8 "Octave – Try It Online") This is a different solution to my original attempt, saving a further 14 bytes. The code is broken down as follows: ``` @(x)max( ) bin2dec( )'./c (:,[1:b b+9:end]) dec2bin(x*( )) c=2.^(0: ) (b=nextpow2(x+1)-8) ``` On the sixth line the number of groups is calculated by finding the exponent of the next power of two larger than the input (number of bits in input number), and subtracting 7 as we are removing 8 bits from each group - the resulting number is stored in `b` for later. We then calculate an array of powers of two on the fifth line which is large enough for all the possible groups that can be removed. We save this in variable `c` for later. On the next line up (forth line), we multiply the input by the array of powers of two (essentially bit shifting each number up), and convert the result to binary. If we take the example of 7831, this results in a 2D array containing: ``` 000001111010010111 000011110100101110 000111101001011100 001111010010111000 011110100101110000 111101001011100000 ``` If we then chop out the centre 8 bits, that is equivalent to removing each of the groups of 8 bits. This is done by the third line. The resulting array is converted back to decimal on the second line. We also have to divide by `c` to undo the scaling that was done to each group initially. Finally on the first line an anonymous function is declared, and the maximum value from all groups is calculated. --- * Save 1 byte by using `nextpow2(x+1)` rather than `nnz(bin2dec(x))` --- --- ### Original attempt - ~~120 98~~ 95 bytes ``` @(x)max(bin2dec(reshape(repmat(a=(d=@dec2bin)(x)',1,b=nnz(a)-7)(d(255*2.^(0:b-1))'<49),[],b)')) ``` [Try it online!](https://tio.run/##TYrRCsIgGEbve4ru/P9QSafbjIS9RxRoOtrF1mgjRi9vRsH6bj4O59yvs3vG1FrOeWpgwd4t4LtBhniFR5xuboz5x97N4CwE22Qhc4C5JVRQb4fhBQ5ZhRBAar2T/AL7g2cCkRyVQXo6U48EMYVuGoEwxghu2tyW2@8@ZIz5o6ouxEqiELrWq9OqlOJHShplykoajekN "Octave – Try It Online") The code is split up as follows: ``` @(x)max( ) bin2dec( ) reshape( ,[],b)' repmat(a=(d=@dec2bin)(x)',1,b=nnz(a)-7)( ) d(255*2.^(0:b-1))'<49 ``` Basically it calculates a matrix containing the possible groups of values that can be removed, and then works out which ends up giving the largest number. Working line by line, the fifth line calculates the groups that can be removed. For example, take 7831. This is a 13bit number, giving the groups: ``` 1111100000000 1111000000001 1110000000011 1100000000111 1000000001111 0000000011111 ``` The result of the fifth line is a 2D logical array which can be used for indexing. The fourth line of the code converts the input to an array of the bits (represented as characters '0' and '1'), and then replicates it `n`-7 times (where `n` in number of bits) giving one line for each possible grouping. The group mask above is used to remove each of the possible groups. On the third line, the result is then reshaped to undo the unwanted flattening that resulted from applying the group mask. The second line converts back to an array of resulting decimal numbers. And the first line defines the anonymous function to be the maximum value of array of possible groups. --- [Answer] # [Perl 5](https://www.perl.org/), 78 + 1 (`-p`) = 79 bytes ``` map{$\=$"if($"=oct$s=~s/.{$_}\K.{8}//r)>$\}2..length($s=sprintf'0b%b',$_)-10}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saBaJcZWRSkzTUNFyTY/uUSl2LauWF@vWiW@NsZbr9qiVl@/SNNOJabWSE8vJzUvvSRDA6ikuKAoM68kTd0gSTVJXUclXlPX0KC2@v9/cwtjw3/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 55 bytes ``` ->n{(8../$/=~"%b"%n).map{|r|n>>8&(a=-1<<r-8)|n&~a}.max} ``` [Try it online!](https://tio.run/##JYzBCoQgFAB/RWKLAjW0NB@kPyIe7NBtJYTAJe3X3ZY9zgxMPLdP3XUlJly9onR8jfpu2q1pw0Df/rhyzMEY1fVeE7aukaghh@725ampVMuFxAgAMFrUxDBiExNK/EjMkj9i5jCDXDgI9x@mjA5kE95tcq7ULw "Ruby – Try It Online") [Answer] # Perl, 53 bytes (the `use 5.10.1` to bring perl to lanugage level 5.10.1 is free) Give the input number on STDIN. Will run out of memory for big numbers, but the 32-bit number in the input is not yet a problem ``` #!/usr/bin/perl use 5.10.1; $_=sprintf"%b",<>;/.{8}(?{\$F[oct"0b$`$'"]})^/;say$#F ``` ]
[Question] [ The Recursively Prime Primes is are sequence of primes such that ``` p(1) = 2 p(n) = the p(n-1)th prime ``` Here is an example of how one might calculate the 4th Recursively Prime Prime. ``` p(4) = the p(3)th prime p(3) = the p(2)th prime p(2) = the p(1)th prime p(1) = 2 p(2) = the 2nd prime p(2) = 3 p(3) = the 3rd prime p(3) = 5 p(4) = the 5th prime p(4) = 11 ``` You should write a program or function that when given n, outputs the nth Recursively Prime Prime. You may choose to use 0 based indexing if you wish in which case you must indicate so in your answer. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize your byte count. --- # Test Cases ``` 1 -> 2 2 -> 3 3 -> 5 4 -> 11 5 -> 31 6 -> 127 7 -> 709 8 -> 5381 9 -> 52711 ``` --- Relevant OEIS entry: [OEIS A007097](http://oeis.org/A007097) [Answer] # [Oasis](https://github.com/Adriandmen/Oasis), 3 bytes The program is **0-indexed**. Code: ``` <q2 ``` Uses the formula: **a(n) = nth\_prime(a(n-1) - 1)**, with the base case **a(0) = 2**. Code explanation: ``` 2 = a(0) < # Decrement a(n - 1) to get a(n - 1) - 1 q # prime(a(n - 1) - 1) ``` [Try it online!](https://tio.run/nexus/oasis#@29TaPT//38TAA "Oasis – TIO Nexus") [Answer] # Mathematica, 16 bytes ``` Nest[Prime,1,#]& ``` Anonymous function. Takes a number as input and returns a number as output. [Answer] # [Actually](https://github.com/Mego/Seriously), 7 bytes ``` 1@⌠DP⌡n ``` [Try it online!](https://tio.run/nexus/actually#@2/o8KhngUvAo56Fef//mwAA "Actually – TIO Nexus") Explanation: ``` 1@⌠DP⌡n 1 push 1 @ swap 1 with n ⌠DP⌡n do the following n times: DP decrement, prime at index ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 bytes *1 byte thanks to @Dennis.* ``` 1ÆN¡ ``` [Try it online!](https://tio.run/nexus/jelly#@294uM3v0ML///@bAAA "Jelly – TIO Nexus") ### Explanation ``` 1 Starting with n = 1, ÆN replace n by the nth prime ¡ (input) times. ``` [Answer] # JavaScript (ES6), 71 bytes ``` p=(n,x=1)=>n?p(n-1,(N=y=>x?N(++y,x-=(P=z=>y%--z?P(z):z==1)(y)):y)(1)):x ``` Ungolfed, you have three separate recursive functions: ``` P=(n,x=n)=>n%--x?P(n,x):x==1 N=(n,x=1)=>n?N(n-P(++x),x):x p=(n,x=1)=>n?p(n-1,N(x)):x ``` * `P` determines whether `n` is prime; * `N` finds the `n`th prime; * `p` recursively runs `N` on input `1` `n` times. [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` 1i:"Yq ``` [Try it online!](https://tio.run/nexus/matl#@2@YaaUUWfj/vyUA) ### Explanation ``` 1 % Push 1 i % Input n : % Range [1 2 ... N] " % For each (that is, do the following N times) Yq % k-th prime, where k is the input % End for each (implicit) % Display stack (implicit) ``` [Answer] # R, ~~98~~ 93 bytes *5 bytes thanks to @smci* Here is a horribly inefficient recursive solution: ``` f<-function(m,n=1){j<-1;for(i in 1:n){j<-numbers::nextPrime(j)};a<-ifelse(m==0,j,f(m-1,j));a} ``` Test Output: ``` f(6) [1] 127 f(10) ### takes almost a minute... YIKES!!! [1] 648391 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` ÎF<Ø ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cJ@bzeEZ//9bAgA "05AB1E – Try It Online") ### Explanation ``` ÎF<Ø Î # Push 0 and input F # Do input times... < # Decrement Ø # Get the nth prime (0-indexed) with n being the top of the stack ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` !¡!İp2 ``` [Try it online!](https://tio.run/##yygtzv7/X/HQQsUjGwqM/v//bw4A "Husk – Try It Online") Explanation: ``` !¡!İp2 ¡ Make an infinite list by repeatedly applying a function 2 Starting with 2 İp From the sequence of prime numbers ! Get the element at the given index (the previous number in the sequence) ! Get the element at index (implicit input) in that infinite list ``` [Answer] # Bash + common utilities, 55 Since we're doing recursive primes, here's a recursive answer: ``` ((SHLVL-2<$1))&&primes 2|sed -n "`$0 $1`{p;q}"||echo 1 ``` Since recursion level counting is based off the `$SHLVL` built-in variable, then the answer can be off if you're already a few shell levels deep. This is probably why this answer doesn't work on TIO. --- If that's no good, then here's a more conventional answer: # Bash + common utilities, 58 ``` for((i=$1;i--;));{ n=`primes 2|sed -n "$n{p;q}"` } echo $n ``` [Try it online](https://tio.run/nexus/bash#NY3BCsIwEAXv@YpHzUEPUfQmwX@pJFuyoLs1G@mh9turIt4GBmYGrWhkLV2NwIL5uN@fl4iszqghBPi/dnLpOsQN@D7eOHHDVEjQCqHQNVO9kdlhUG0/RNL8aRrqU75pbgadBJYqj20dtG63fPHHyCHE3S7On0E/Vr6T4fQyygiCzss8xsfS9W5xlIrCy5pVaH0D). [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~10~~ 8 bytes Saved 2 bytes thanks to Adám ``` ⌂pco⍣⎕⊢1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94P@jnqaC5PxHvYsf9U191LXIECT6XwEMCrgMuWAsIzjLGM4ygbNM4SwzOMsczrKAsywB "APL (Dyalog Extended) – Try It Online") `⍣` applies the function `⌂pco` (nth prime) to 1 n times (n is taken through STDIN (`⎕`)). ## Another previous solution, 10 bytes ``` ⊢∘⌂pco/⍴∘2 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/P@1R24RHXYsedcx41NNUkJyv/6h3C5BjBJQ5tOJR72ZLAA "APL (Dyalog Extended) – Try It Online") `⍴∘2` makes a vector of n 2's, then `/` reduces using the train `⊢∘⌂pco`. `⊢` ignores its left argument, `pco` finds the nth prime, given n on the right. More generally, `⊢∘f/n⍴s` applies `f` `n-1` times to `s`. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` 1$(‹ǎ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIxJCjigLnHjiIsIiIsIjkiXQ==) ``` 1$ # Push 1 and the input ( # Input times ‹ǎ # Decrement and get nth prime ``` [Answer] # [Haskell](https://www.haskell.org/), 58 bytes 1-indexed ``` f 1=2;f n=[x|x<-[2..],all((>)2.gcd x)[2..x-1]]!!(f(n-1)-1) ``` [Try it online!](https://tio.run/##LYyxCoMwFEX3fsUTHBJoAgpdrCl06NC5oziEmmgweUoMJYX@e6ri5cKFw@UMchmVtcm4efIBXt8lKMcf@DF@QqcwkF6Fu@8XmjQUorxqQNHEX6xZU3LenqW1hNxoyft3B5FuMLKibbOMaIKsoGuTkwYFdNMJ9sjVBzWDQ33Q2RsMuQbilewgh2Gb/VpV8MRAU7r8AQ "Haskell – Try It Online") **Explanation:** Uses the same 0-indexed prime-list access trick as [Adnan's answer](https://codegolf.stackexchange.com/a/110815/55329). Essentially straight-up follows the specification otherwise. ``` f 1=2; -- base case f n= -- main case [x|x<-[2..],all((>)2.gcd x)[2..x-1]] -- list of all primes [x|x<-[2..], -- consider all numbers [2..x-1] -- consider all smaller numbers all((>)2.gcd x) -- is coprime with them? (>)2. -- 2 is greater than gcd x -- gcd(x,lambda input) !!(f(n-1)-1) -- access the -- f(n-1)-th 1-indexed prime ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` ?K2ȯ!İp₀←ε ``` [Try it online!](https://tio.run/##yygtzv7/397b6MR6xSMbCh41NTxqm3Bu6////y0A "Husk – Try It Online") A recursive function. [Answer] # [Factor](https://factorcode.org/) + `math.primes.lists`, 57 bytes ``` : p ( m -- n ) [ 2 ] [ 1 - p 1 - lprimes lnth ] if-zero ; ``` [Try it online!](https://tio.run/##JY07DsIwEER7TjElFLYEHckBUJo0iAqlsKw1seQf9lLA5c1Cmle8Gc04YznXfrtO82VA8I0bouH1D12qj9T0pksl5reoxGj0fFGy1DDupnnAIwfXBxTsEaEUEg6444RFeISS4Mew7SEkOVjgnfpQzRj7GT6zkW6BloCMXfsX "Factor – Try It Online") ## Explanation Returns the 0-indexed member of the recursively-prime prime sequence. * `: p ( m -- n ) ... ;` Start a new word definition named `p` with stack effect `( m -- n )`, declaring it takes one thing from the data stack and leaves one thing on the data stack. * `[ 2 ] [ ... ] if-zero` Is the input `0`? Then return `2`. Otherwise, do `...`. * `1 - p` Apply `p` to the input minus one. * `1 - lprimes lnth` Return the nth prime number. [Answer] # [Wonder](https://github.com/wonderlang/wonder), 23 bytes ``` p\.{1\2@:^(- p -#0 1)1P ``` 1-indexed. Usage: ``` p\.{1\2@:^(- p -#0 1)1P}; p 3 ``` # Explanation ``` p\.{ #. Pattern matching syntax 1\2 #. Base case p(1)=2 @:^(- p -#0 1)1P #. Other cases p(n)=nthprime(p(n-1)-1) #. nthprime is 0-indexed } #. Trailing bracket is optional in this case ``` ]
[Question] [ Your challenge is to, given a matrix of nonnegative integers, remove all rows and columns that contain a 0. For example, with this matrix: ``` [[5, 3, **2**, 4, **1**], [**3**, **2**, **0**, **4**, **7**], [7, 1, **9**, 8, **2**], [3, 2, **1**, 5, **7**], [6, 4, **6**, 1, **2**], [**9**, **3**, **2**, **4**, **0**]] ``` Columns 3 and 5, along with rows 2 and 6 (in bold), contain a 0, so they should be removed, leaving: ``` [[5, 3, 4], [7, 1, 8], [3, 2, 5], [6, 4, 1]] ``` You may assume the input and the output are nonempty. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! ## Testcases ``` [[1, 2, 3], [4, 5, 6]] -> [[1, 2, 3], [4, 5, 6]] [[1, 2, 3], [4, 5, 0]] -> [[1, 2]] [[3, 6, 19], [4, 0, 18], [2, 19, 3]] -> [[3, 19], [2, 3]] [[5, 3, 2, 4, 1], [3, 2, 0, 4, 7], [7, 1, 9, 8, 2], [3, 2, 1, 5, 7], [6, 4, 6, 1, 2], [9, 3, 2, 4, 0]] -> [[5, 3, 4], [7, 1, 8], [3, 2, 5], [6, 4, 1]] [[4, 9, 4, 1], [2, 0, 6, 0], [3, 4, 1, 2], [9, 7, 8, 5], [3, 5, 2, 0]] -> [[4, 4], [3, 1], [9, 8]] ``` [Answer] # [R](https://www.r-project.org), 35 bytes ``` \(x,`?`=\(d)apply(x,d,all))x[?1,?2] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fVFdasMwDGavPYWhLxaoYDt2mhWyXGJvqaFhJTBIoJQW0rPsJRvsUBvsLrPkuCQwBiaWpe8v9tv7efxoy8_rpd0UX-u9HPBQHcq9PEJzOnW3cD5i03UAQ11prIyP0O-HH9mXfXM5vw7yRaqdNqh2OaAFWLWyhxV901ijMCgyFBaFQxFgBvEZYC02T6Kup7FHUU8A7_-hqz_oS0KA5ij0IzNUqApWoEYGmM3JGbXJmRMsVBx7GhbRqVZ83PIKzaBYpHSGO45HOcNy7hiG3aVC_HyeINpYyhA1Cyoj3FEZtfQynGVRmwwUm6l0S3fXLeeLFi4iAd3c3k7edBG00x_56ZXHMe6_) --- Alternative solution if the input contained `NA`s instead of `0`s: ### [R](https://www.r-project.org), 34 bytes ``` \(x,`?`=complete.cases)x[?x,?t(x)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fVHdSsMwFMbbPUXQmxw4kzRNujqoxRfwyrta2CjpGKxsrBXyLt5UwYfS9_De5KQdLQwhNCfnfH9N3j_O_ecu-3rr6mX6ffvKLW7yTVYdm9PBdOa-2ramBVvkFvOOWygD8ufmt84cGHZ8X5tDaxzP4vMTwII3WbPtznvLKy7WkUSxTgCVm9S8gYX_juMImUQWI1PINDIHk4gvAHds-ciKYhiXyIoBUJb_0MUV-pzgoAmy6IEYwlUpKfhGDBhPybFve2dKMFPR5ClJJBprQccVLdd0iumYTlJH0yghWEIdSbCLlIufTBMEG-UzBM3UlwGufRm0onk4RaJqNBBkJsZburiuKF-w0AEJqKf2avD2F-F3_0fl8Pp9H_Y_) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ¬ŒṪZœP@ẎZɗƒ ``` A monadic Link that accepts the matrix and yields the reduced matrix. **[Try it online!](https://tio.run/##y0rNyan8///QmqOTHu5cFXV0coDDw119USenH5v0/3C7@///0dGmOgrGOgpGOgomOgqGsTpcCtEQrgFYxBwsYg6U0lGw1FGwAErB1BiABU1haszA6s3AghA1lkgmGwBFYgE "Jelly – Try It Online")** ### How? ``` ¬ŒṪZœP@ẎZɗƒ - Link: list of lists of integers, M ¬ - logical NOT (vectorises) ŒṪ - truthy multidimensional indices Z - transpose -> [zero row indices, zero column indices] ƒ - start with {M} and reduce {that} by: ɗ - last three links as a dyad - f(Current, Indices): @ - with swapped arguments: œP - partition {Current} at {Indices} Ẏ - tighten Z - transpose ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` t!XAyXA3$) ``` Try at [MATL online](https://matl.io/?code=t%21XAyXA3%24%29&inputs=%5B5%2C+3%2C+2%2C+4%2C+1%3B+3%2C+2%2C+0%2C+4%2C+7%3B+7%2C+1%2C+9%2C+8%2C+2%3B+3%2C+2%2C+1%2C+5%2C+7%3B+6%2C+4%2C+6%2C+1%2C+2%3B+9%2C+3%2C+2%2C+4%2C+0%5D&version=22.8.0)! Or [verify all test cases](https://matl.io/?code=%60%0At%21XAyXA3%24%29%0A0cXDT&inputs=%5B1%2C+2%2C+3%3B+4%2C+5%2C+6%5D%0A%5B1%2C+2%2C+3%3B+4%2C+5%2C+0%5D%0A%5B3%2C+6%2C+19%3B+4%2C+0%2C+18%3B+2%2C+19%2C+3%5D%0A%5B5%2C+3%2C+2%2C+4%2C+1%3B+3%2C+2%2C+0%2C+4%2C+7%3B+7%2C+1%2C+9%2C+8%2C+2%3B+3%2C+2%2C+1%2C+5%2C+7%3B+6%2C+4%2C+6%2C+1%2C+2%3B+9%2C+3%2C+2%2C+4%2C+0%5D%0A%5B4%2C+9%2C+4%2C+1%3B+2%2C+0%2C+6%2C+0%3B+3%2C+4%2C+1%2C+2%3B+9%2C+7%2C+8%2C+5%3B+3%2C+5%2C+2%2C+0%5D&version=22.8.0). ### How it works ``` t % Implicit input. Duplicate ! % Transpose XA % Vertical-all: gives a logical vector containing true % for columns without zeros, or false otherwise y % Duplicate from below: pushes copy of input XA % Vertical-all 3$) % 3-input indexing: keeps the selected rows and columns % Implicit display ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~18~~ ~~16~~ 15 bytes -1 thanks to [coltim](https://codegolf.stackexchange.com/questions/269954/remove-falsy-rows-and-columns#comment585700_269964) ``` {x.&'1&/''+:\x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxVTjkOwkAM7POKqbJESGDvmY2/Qp03REL8nfEmEqKy59Ts2/t4zEHnZwj37XV8pmnHTRGRLKOgLv9YBk6o0E5CoKtF/khDKEi0Zqj5FX7NGhQdK+LglCXNKhVWkOtX4izOdHrasxXCRL5cjQ2FuHjvbxR9cg7zhLmrQzlLly/B6SfN) ``` 1&/''+:\x row-,column-wise zero-free? &' indices where true x. submatrix ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~82~~ ~~74~~ ~~65~~ 60 bytes *-13 bytes thanks to [Mukundan314](https://codegolf.stackexchange.com/users/91267). -9 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203).* ``` lambda m:[q for*q,r in zip(*filter(all,zip(*m)),m)if all(r)] ``` [Try it online!](https://tio.run/##bZBNDsIgEIX3PcUswcyCFm3VpCdBFjVKJOmfyEYvX4dp1WhkQZg337xHZrzHy9DrydWHqW2646mBbm@u4IawumIA38PDj2LlfBvPQTRti1x3UmInvQNSRJB2iudbvEENxpgcoUDQFsGsETYIpbWYwev8AdQPoGkGId8thKL3Nr2LJKbJb5wQUunOF0jxvEqVnhuUmCrCKoQthS69DX/lN59UzY2X51wpFqokVOy5Y6/iQ@TsyETJcPmV/TalQJtltGSIacW8vD3/YAy@j8KJKOX0BA "Python 3 – Try It Online") I wasn't going to post two answers but since nobody else is posting a Python answer that *doesn't* rely on NumPy... Port of [my Haskell answer](https://codegolf.stackexchange.com/a/269969), but I can't really take any credit for the final result. It all goes to [Mukundan314](https://codegolf.stackexchange.com/users/91267) and [att](https://codegolf.stackexchange.com/users/81203). I'll try my best to explain this wizardry. ## Explanation Said wizardry *really* takes advantage of Python's splat operator `*`. What it does essentially is unpack an iterable (in this case a two-dimensional list) into separate arguments for a function call. Let's start with a simple matrix `m`, and I'll document the transformations that happen to it along the way. ``` [[4, 9, 4, 1], [2, 0, 6, 0], [3, 4, 1, 2], [3, 5, 2, 0]] ``` First, `zip(*m)` transposes the list. Instead of passing `m` to the `zip` function as the list of rows it is, it's passed as separate arguments, effectively zipping the rows of the matrix together to create a list of the columns. ``` [(4, 2, 3, 3), (9, 0, 4, 5), (4, 6, 1, 2), (1, 0, 2, 0)] ``` Next, `filter(all, ...)` removes every column that has a zero in it by checking `all` of the column against Python's boolean logic: 0 is falsy and every other number is truthy. (Hey, that's half the challenge sorted!) ``` [(4, 2, 3, 3), (4, 6, 1, 2)] ``` Cool, that's the truthy columns. After that, `zip(*..., m)` is once again splatting the previous result and zipping it together with the original input. This basically transposes it back to the rows, except without the falsy columns, and then prepends it to the original rows. ``` [(4, 4, [4, 9, 4, 1]), (2, 6, [2, 0, 6, 0]), (3, 1, [3, 4, 1, 2]), (3, 2, [3, 5, 2, 0])] ``` Here comes an interesting bit. Remember what I said about the splat operator? Yeah, it does more than that. Kinda. `for *q, r in ...` effectively groups the rows-without-falsy-columns together, while keeping the original rows separate. The splat operator "collects" elements into `q` when iterating over something until another argument `r` is required. ``` [([4, 4], [4, 9, 4, 1]), ([2, 6], [2, 0, 6, 0]), ([3, 1], [3, 4, 1, 2]), ([3, 2], [3, 5, 2, 0])] ``` Now all that's left to do is get rid of the falsy rows and to do this, `q ... if all(r)` employs a similar trick to when the falsy columns were removed. While iterating over the previous result, if and only if `r` (or the original row) is truthy, keep `q`. ``` [[4, 4], [3, 1]] ``` [Answer] # [Python](https://www.python.org) + numpy, 32 bytes ``` lambda a:a[a.all(1)][:,a.all(0)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZJNTsMwEIUlljnF7GJLbpT0v5HSiwQvDE2oIbUtx0XkLGwqIbgTnAaPXdqKNpvMvO_NGyvO-5cZ3Farw0db3X_uXTtafkMndg8bAaIUtchE15GC8rpksc4pj76fu-eNcKJK07SuCwZjBhPOoJ4ymDGYcw6jNdwmyQ05vxwIlon3MihWR0_u6yXWYxRx9jgw-TOFQJz0cZOQ78cKJLHLg7BAYeEBA5-yxG0nRxGOEhzzYJ4HLThWF6Gnw8ZN03Pk8hw2O8cUnPvPlCRyZ7R1oPY7M4DoQZnENb3rofJZymTCWjGQ5lV0ZCu6NuudlYZQSqHVFlACqaCTqsl600lH0tE6pTxQVJHipUSKSk8oTxLkkmnEYV-ZgH8Gv7YlkoZGvwjsia6qgYabjrqxUjmCNPayBaVdsMeUsyltrNW2TOl_XSqzd2XKQF6h5s00j67ZINVX9EmHsYHGX-5wiO9f) -6 bytes thanks to att [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 15 bytes ``` ((⍸0≠∧/)¨⊢⍮⍉)⌷⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X0PjUe8Og0edCx51LNfXPLTiUdeiR73rHvV2aj7q2Q7k/Hd71DbhUW/fo67mR71rHvVuObTe@FHbxEd9U4ODnIFkiIdnMEgNSMQr2N9PPTraUEfBSEfBOFZHIdpER8FUR8EsNladS12di4AyA6zKjIH6dRQMLaHqDIBsCxDbCCQI0o9NE9A0Y7DxQB2GINUQngFYwBwkYA6U0FEAGmABlEGoMAS7BKzCDKzYDCwGVmGJZCjIrQA "APL (Dyalog Extended) – Try It Online") # [APL (Dyalog APL)](https://www.dyalog.com/products.htm), ~~19~~ ~~18~~ ~~17~~ 16 bytes -1 byte thanks to [@att](https://codegolf.stackexchange.com/users/81203/att) ``` ⊢⌷⍨B∘⍉,B←⊂∘⍸0≠∧⌿ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70qpTIxJz89PrEgZ8EqK7_E3NTigsTk1KWlJWm6Fjc1HnUtetSz_VHvCqdHHTMe9XbqOD1qm_CoqwnM22HwqHPBo47lj3r2LylOSi6-xejhBpLu7TN61NX8qG9qcJAzkAzx8Azm4gIygHJA-YlAllewv596dLShjoKRjoJxrI5CtImOgqmOgllsrDpUpbo6cVoMCGoxBpqro2BoCdVjAGRbgNhGIEGQWYQMANpiDLYWqNsQpBPCMwALmIMEzIESOgpAwyyAMggVhmAXglWYgRWbgcXAKiyRDAX7wco1LwUt_BcsgNAA) ``` ⊢⌷⍨B∘⍉,B←⊂∘⍸0≠∧⌿­⁡​‎⁠⁠⁠⁠⁠⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁢​‎⁠⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁣​‎⁠⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁤​‎⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠⁠‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁣‏⁠‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁤‏⁠⁠⁠‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠⁠‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌­ B←⊂∘⍸0≠∧⌿ ⍝ ‎⁡B = Monadic function to get indices of columns without zeros: ∧⌿ ⍝ ‎⁢ reduce each column on lcm 0≠ ⍝ ‎⁣ check if not equal to 0 (vectorized) ⍸ ⍝ ‎⁤ get indices of true values ⊂ ⍝ ‎⁢⁡ enclose B∘⍉ ⍝ ‎⁢⁢Apply B on transpose (first result) , ⍝ ‎⁢⁣catenate with B ⍝ ‎⁢⁤Apply B on argument (second result) ⊢⌷⍨ ⍝ ‎⁣⁡Keep only rows and columns in first and second result respectively 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Matlab](https://www.mathworks.com/products/matlab.html), ~~74 bytes(?)~~ 52 bytes *-22 bytes thanks to Luis Mendo because my first attempt was too readable.* [Try it online!](https://octav.onl/mbfvo809) Input for first test case would be `F([1,2,3;4,5,6])` To be honest, I just wanted to try the challenge and am pleasantly surprised to how neatly it can be solved Matlab, so I just wanted to share it. ``` function[m]=F(m);[r,c]=find(~m);m(r,:)=[];m(:,c)=[]; ``` [Answer] # Google Sheets, 72 bytes ``` =let(a,A1:E6,_,lambda(x,min(x)),filter(filter(a,byrow(a,_)),bycol(a,_))) ``` Put the array in cells `A1:E6` and the formula in cell `G1`. ![filter rows and columns.png](https://i.imgur.com/RbcSOKP.png) In Google Sheets, a formula cannot return a *completely empty* 2D array. When all rows or columns contain a zero, the formula will error out. [Answer] # JavaScript (ES6), 62 bytes *-2 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* ``` m=>(g=a=>a.filter((v,x)=>(+v?m:v).every(v=>v[x]|v)))(m).map(g) ``` [Try it online!](https://tio.run/##hY7LCsIwEEX3fkWWGRxD02ofQuqHhC5CTYvSF20JFfz3mkRBFwV3M2fOvcxdGTWV422YD11/1Wsl1lbktBZK5IpVt2bWI6UGF7B0by7t2QDTRo8PakRu5FI8DQDQFlirBlrDWvbd1DeaNX1NKyolRxIiiQok8ojkhCQuCoDdXy3Y1CKbR8KzjxfYOXVz6KDLb4VsW@TrbYI7@70FHiQOJPaAxBak9vI1uP/EG7GXY8@8kf2U@l/XFw "JavaScript (Node.js) – Try It Online") ### Commented ``` m => ( // m[] = input matrix g = a => // g is a helper function taking an array a[] a.filter((v, x) => // for each value v at index x in a[]: (+v ? m // if v is atomic, we use m[] (2nd pass on columns) : v) // otherwise, we use v (1st pass on rows) .every(v => // for each value v in the array chosen above: v[x] // test either v[x] (when removing columns) | v // or v (when removing rows) ) // end of every() ) // end of filter() )(m) // invoke g on m[] to remove rows .map(g) // invoke g on each row to remove columns ``` [Answer] # [J](http://jsoftware.com/), 15 bytes ``` *@*/#"1*@*/"1#] ``` [Try it online!](https://tio.run/##ZYzLCsIwEEX3fsUlFYthmkc1qQ1VgoKr4sJ9FyIWceMPSH89JulGcDHMnXMu8wpMlCP2DiUICi5OJXC69ufAPZcF02kxXQxhvbgcBW7u4CsxDZ2PblIdl6uP45LLbP/p4/58Y4SFwRKGsCHUhC1B0xxVvhpqEkJL2CU8uwhMcjZ3bAY1tT9fVPgC "J – Try It Online") * `*@*/"1` Boolean multiply across columns... * `#]` and use that to filter rows. * `#"1` then filter each of those remaining rows... * `*@*/` by the boolean filter obtained by multiplying all the rows together [Answer] # [Haskell](https://www.haskell.org) + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 38 bytes ``` f y=cr<<fn(e 0<(tx y!)<st)<eu<fn(e 0)y ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVBLasMwFKRbn2KyKTYoINuN7RT5CIXsjRemkYipnSa2DPVZuvGm9EzpaSo9KQmFbqQ3nzcD7_P70IxvsuuWy6rtT--Dxi7ww3lqula1co_dILtpL78mrdbF5VFhLl8HIdQxlOAi1B-YV5EYdSTk5Nlodu6fh2ctRz2iDIAKVRUzJAxpzVA9MWwYsro2EvtP4jcpNT6GeOs1bubCzokl7c7VaESDzRt7mdMmtyh1gmmxyNhyhsIUeW1D9fdOg1OirmkOcSJyS-SUtqWU5O6IKYscGZmzP623UFdVB0HftEeU6F8QngYIqAh0NHfCZXH_Lw) ## Alternate, 43 bytes ``` cr<<<g st<g cr<m(sQ<oti mn) ``` ``` g=tx><fn<e 0<<m ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY69DoIwFIX3PsV1g6QkgIshF3cHE5ybDkRabGwBaUncfBAXFuMz8TY2QNTlnpPv3L_n-1Laq9B6nDbKdG3v4DaUWkklKih6oYdKkDUoXoOT0W6KZH7uEbEG63zx3gT2hK1TYJqQ1Lm771E2KCBGNOvQwwnrLGQZMMYOjeOckwXlBIB5mtCYJpyy9KtbmvouADqnKff6j-JfODtOiClVMy80Rwi6HhBkCPOZ5Y1xXPQD) I kind of understand how it works but it's not easy to explain. First it tags each value with the minimum in its row, then it removes every column with a zero, then it removes every row with a zero tag. * `m(sQ<oti mn)` is the part that adds the tags. * `g cr` is the part that removes the columns (it also transposes the matrix) * `g st` is that part that removes the rows (it also transposes the matrix back) * `cr` removes the tags. # Reflection * There should be a non-infix version of `(!)`. * There should be precomposed versions of `e` and `ne`. * `oti` should probably have a 2 byte name. * The precendence of `@!` makes it incompatible with composition. I should tweak this. * There is already an "index map" a couple of index filters would be nice. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~15~~ 14 bytes ``` ⭆¹EΦθΠλΦλ⬤θ§πξ ``` [Try it online!](https://tio.run/##TYxBC4JAEIXv/Yp33IUJtFKTTl6CDoHQcdmDqJQwqC1b@O@3dZVwLo/5vjdTvypTDxU7V5qut@JhfTzv1ShiwhzXjm1rxJtQmqH51FawlIQVM6Fgnm1hb33TTmIkTDLMxTmlVEI4Eg6EEyHWtAPUskcBZQvKvCTkhLN325anyb@VhpM00LWVb95HWmu3//IP "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array Φ Filtered where λ Current row Π Product (is truthy if the row contains no zeros) E Map over remaining rows λ Current row Φ Filtered where π Inner row § Indexed by ξ Current column ⬤ Are non-zero for each row of θ Input array ⭆¹ Pretty-print the result ``` [Answer] # [Haskell](https://www.haskell.org/), ~~81~~ ~~63~~ ~~62~~ 59 bytes *-3 bytes thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656).* ``` n=notElem 0 f m=[[c|(x,c)<-zip[0..]r,n$map(!!x)m]|r<-m,n r] ``` [Try it online!](https://tio.run/##bZBBi4MwEIXv/opX2IPCVKJutUI99thfEHKQYlmpyYp6kNL/bidTd5eWzSFk3nzzXpiverw2XbcsrnLf07FrLFRwga20Pt/Dmc7RYXtre63i2AzkPmzdh5vNHFlzHw5bSw6DWaZmnEZU0NA6IaSEzBD0J2FHyI0JsB76D1BvQMYzhKRcCcXvvX@nXvSTrzgjrPKdrJCSeeWr7NngRF8xVhD2HLr2dvKV93xWM2n8eD4rJULhhUI8S/FK/4hEHIXIBc5fsn9NORAmCGzdOl4ab/SEsB9aNyHGJYJsc3kA "Haskell – Try It Online") ~~I *really* want to use the fact that Haskell has `product` in Prelude but... Never mind, I did it. :P~~ Never mind, the original approach allows for code shorter by a byte due to syntactical rearrangement. ## Explanation (slightly outdated) ``` f m -- define function f that takes matrix m | n <- notElem = -- alias notElem (element not in list) to p [[c -- store c | (x, c) <- zip [0..] r -- for every pair of index x and value c in r... , n 0 $ -- if 0 is not in the... map (!! x) m) -- ...xth element of every row in m (column) | r <- m -- for every row r in m... , n 0 r] -- if 0 is not in r (truthy) ``` [Answer] # APL+WIN, 17 bytes Prompts for input of matrix ``` (×/×m)⌿(×⌿×m)/m←⎕ ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##ZY1NCsIwEIX3OcXsqovSpvlpcwRB8QylUhFaFLrqBdSFihvpRdy76E1ykfgS4kpCMm9m3vtSn7p0N9bdcZ82XT0Mh8bZx2uztuenYFCrLRRn9npp3WKesnnql/b2gcTrm6yHAUYHC3MtK0jY@5sTKklSpFlCCfuf53EuwlyQJm6wyIlX8ECLaNCkYFCIFdjzUHOoEoeToSogEQG0BEZ6FHoTE7@PFElwJJlA8QyNK2JnkK3I/6L87gs "APL (Dyalog Classic) – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 11 bytes ``` (×∧/⍮∧⌿)⍛/⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@Pw9Ecdy/Uf9a4DUo969ms@6p0N5K347/aobcKj3r5HXc2Petc86t1yaL3xo7aJj/qmBgc5A8kQD89gkBqQiFewv596dLShjoKRjoJxrI5CtImOgqmOgllsrDqXujoXAWUGWJUZA/XrKBhaQtUZANkWILYRSBCkH5smoGnGYOOBOgxBqiE8A7CAOUjAHCihowA0wAIog1BhCHYJWIUZWLEZWAyswhLJUJBbAQ "APL (Dyalog Extended) – Try It Online") `⍨` using the argument as both parameter (list of masks, one per dimension) and data `/` filter the data using the parameter `(`…`)⍛` first pre-processing the paramter as follows:  `×` signum of  `∧/` row-wise LCM  `⍮` juxtaposed with  `∧⌿` column-wise LCM [Answer] # [R](https://www.r-project.org), 32 bytes ``` \(x)x[!rowSums(!x),!colSums(!x)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fVHNSsQwEMarTzHFSwZmIUmTbF3Ql9BbzUEWCoLLQt3FvsteuoKvJOjTmJk0SwsiBDKZ-f6SnM79-NHdfR4P3ar5hic14NBW_f794bh7U9WAVG33r-UQM-7n6qtTu-dD_zKordIbY0lvApJDvJ4NDIElqAkcgSdIAEv0iHgDq3to22kcCdoJEOM_dP0HfUlI0EBgboWhU9WIAjdqpHpOrrnNzpJgoeLF04qIKbWW41pWaibFpqSz0vEyCgIL0rECu0il-GGeINs4zpA1Gy4z3HOZtcwynBNRVwy0mOnyShfXteTLFj4jkfzc3k3e_BC8843i9L3jmPdf) Test suite stolen from [pajonk's answer](https://codegolf.stackexchange.com/a/269976/78274). [Answer] # [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), ~~15~~ 14 bytes ``` ⍉▽⊙⍉⊙▽∩/↧⟜⍉≠0. ``` [Try it!](https://uiua.org/pad?src=0_8_0__ZiDihpAg4o2J4pa94oqZ4o2J4oqZ4pa94oipL-KGp-KfnOKNieKJoDAuCgpmIFtbMSAyIDNdCiAgIFs0IDUgNl1dCgpmIFtbMSAyIDNdCiAgIFs0IDUgMF1dCgpmIFtbMyA2IDE5XQogICBbNCAwIDE4XQogICBbMiAxOSAzXV0KCmYgW1s1IDMgMiA0IDFdCiAgIFszIDIgMCA0IDddCiAgIFs3IDEgOSA4IDJdCiAgIFszIDIgMSA1IDddCiAgIFs2IDQgNiAxIDJdCiAgIFs5IDMgMiA0IDBdXQoKZiBbWzQgOSA0IDFdCiAgIFsyIDAgNiAwXQogICBbMyA0IDEgMl0KICAgWzkgNyA4IDVdCiAgIFszIDUgMiAwXV0K) -1 thanks to the new `⟜ on` modifier that dropped this morning. Keeps two masks on the stack of which rows should be kept on each axis, and filters the input matrix based on these. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` øDĀPÏøIĀPÏ ``` [Try it online](https://tio.run/##yy9OTMpM/f//8A6XIw0Bh/sP7/AE0///R0eb6igY6ygY6SiY6CgYxuooREN4BmABc5CAOVBCR8FSR8ECKINQARQzhaowAys2A4uBVVgiGWoQGwsA) or [verify all test cases](https://tio.run/##bY3NCoJAFIX3PYW4PoHjz6hBuG6V62QWRRK2MLExcNcb9Bi9QITQTlv3SnZntCBoNWe@e79zD8f1Jkv7k7nIi0rODDOq5xMzLlMp62lRZrlMt0RRt9fV7nXbtw/0XVN3zfMcdxdK@u3NZSVH/6/@cdt71CdJwmDDEUhceOBCwPhF1oAccLBQMwssoGDTn7b01INDigtGXCWLsk/ZB0OIAPbIGRUqzmlOfZqHozseckkYilQNJ6xU97vsU52nmacOCSHe). **Explanation:** ``` ø # Zip/transpose the (implicit) input-matrix; swapping rows/columns D # Duplicate this Ā # Check for each value whether it's NOT 0 (0 if 0; 1 otherwise) P # Take the product of each inner row Ï # Only leave the rows of the transposed matrix at the truthy (==1) positions ø # Zip/transpose the remaining rows back I # Push the input-matrix again ĀPÏ # Do the same # (after which the filtered matrix is output implicitly as result) ``` [Answer] # APL(NARS), 43 chars ``` {(c d)←1⍴⍨¨⍴⍵⋄c[↑¨k]←d[2∘⊃¨k←⍸0=⍵]←0⋄d/c⌿⍵} ``` test: ``` arr←3 3⍴⍳10⋄arr1←6 5⍴5 3 2 4 1 3 2 0 4 7 7 1 9 8 2 3 2 1 5 7 6 4 6 1 2 9 3 2 4 0 g←{(c d)←1⍴⍨¨⍴⍵⋄c[↑¨k]←d[2∘⊃¨k←⍸0=⍵]←0⋄d/c⌿⍵} g arr1 5 3 4 7 1 8 3 2 5 6 4 1 g arr 1 2 3 4 5 6 7 8 9 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` fm▼¹Tf▼T ``` [Try it online!](https://tio.run/##yygtzv7/Py330bQ9h3aGpAGpkP///0dHm@oY6xjpmOgYxupEg1gGQLY5kG2uY6hjqWOhYwQVN9QxBYubAeXNgDyQuCVUr0FsLAA "Husk – Try It Online") ### Explanation ``` fm▼¹Tf▼T T Transpose the input f▼ Filter out those rows (were columns) with a falsy minimum value T Transpose back f Filter the rows based on m▼¹ the minimum values of the rows in the original input ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=product`, 88 bytes ``` sub{map{[@$_[grep{//;product(map{$$_[$']}@_)}0..$#$_]]}@_[grep{product@{$_[$_]}}0..$#_]} ``` [Try it online!](https://tio.run/##LY5tC4IwEMe/yrBRCvOpsgdF8APUy16NMaw0BNMxZxDDr966oW/u7n@/H8eJSraJwXVuhvGu36XQtMCcvmQldBhmQvbP8aFcCzDs8YZNBfemKAjwCnNm0ywvZqGtxdk0KzCYbCi/Dhx16l6uce1Wn7L1jEv3BJ0JghozguiWoIigA1SbdjMgaGsTaEeCTgQlC0sAWNP79UI1fTcY/5oEURxBvzSDStObatp8@cn43R8 "Perl 5 – Try It Online") ]
[Question] [ [Gimbap](https://en.wikipedia.org/wiki/Gimbap)(김밥) is Korean food, somewhat looks like sushi roll. Here is Korean emoticon represent Gimbap : `@))))))))))` Your quest is make ASCII Gimbap cutter. # Rule Input is string made with only `@` and `)`. Output *cuts* every valid Gimbap with `)`, and then add `@` between them. So for example `@))` to `@) @)`. *Valid Gimbap* starts with `@` and followed by any amount of `)`. If there is no valid Gimbap, output is blank. # Input and output ``` Input | Output @))))) | @) @) @) @) @) @))))))) | @) @) @) @) @) @) @) @))@))) | @) @) @) @) @) @) | @) )) | @ | @@)@@@))) | @) @) @) @) @)@)@)) | @) @) @) @) @@@)) | @) @) ))@) | @) ``` # Winning condition This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. from [sandbox](https://codegolf.meta.stackexchange.com/a/17750/87110) [Answer] # [Haskell](https://www.haskell.org/), 32 bytes ``` f(')':s)=f s f s=do ')'<-s;"@) " ``` [Try it online!](https://tio.run/##fZDBboMwEETv/oqRVSlYMafc2iD50q9AHKwUUlQwVtZcqn573XXBCq2SYCx5583Oyn639NEOQ4xdsVO7Z1JVBxK8q7cJrBxLepFGQcbQUiBUqAuu0yc1Etn8Umlkeov/c5mHIQtZqsW3ks3RKGNupOSItO4wsyV5yHVoI0TROz8H0gj2cm4DKb777D57j9@XENMcEmd1tB4dFrsYbe9Y85feBTyhqFOO5gzNDerrT4VjCQ48rL15EtZoDTeF16Edk4A6dSXLfi8hm0Znm4rfp26wZ4rlyfsf "Haskell – Try It Online") Recursion beats using `span` for removing the initial `(`'s. **[Haskell](https://www.haskell.org/), 33 bytes** ``` f s=do ')'<-snd$span(<'@')s;"@) " ``` [Try it online!](https://tio.run/##fZDBjoIwFEX3fMVNYwKNZTVLMenGryAsGgUlQml4ZWP89um0A41o1LaLvnfuuzftRdG17jrnGtD@NCDlaZGTPm3IKJ0VqUw57ZjkYM7WZAl7lJmvw2ICgawO4wKRvuMvKvnVZCZzNesWsrpKLuUbl2gR9gcm1ySGPEKrJMlabSZLAlaN59oS92@f9K01@P@JZJhs4L7bK4MGszzpVat9z4ytttggK4OP8B7CD/D7U4Uihzf8WWZjEhZrAT3YQ1f3oYEyTAXJdsvAqkpEGXe/x6ZTZ3L50Zg/ "Haskell – Try It Online") [Answer] # JavaScript, ~~42~~ 41 bytes ``` s=>s.split(/(?<=@.*)\)/).fill``.join`@) ` ``` [Try It Online!](https://tio.run/##FcZBCoAgEEDRq0QrJ2i8QJYHaaGYhjE40kjXt1r8x7/84yXcuba58BF7Ml3MKiiVclNabYuxOMEOGjBlIufw4lychcH1wEWYIhKfKqkRAOzfx/f9BQ) [Answer] # [C (gcc)](https://gcc.gnu.org/), 53 bytes ``` i;f(char*_){for(i=1;*_;!i&*_++&&printf("@) "))i&=*_;} ``` [Try it online!](https://tio.run/##RY7BCoMwEETv@Yo0h5A1lrbnbSD/ISISmnYPVdH0UvHb08RauwvDg5mBcce7czESeuUe7Vg0MPt@VGQuWDR4IFk0Wks5jNQFr4QFLgBImmQu8dlSp2Bma5MHV9VmZimTT5Q/2tnumHXjVSxY@3fzf9FukLuCLcjSNq7SFE7mjHSd6H3rvQoOThuuUwBJ63J4hUmJ1GU5UVENyJb4AQ "C (gcc) – Try It Online") ``` i;f(char*_){for( *_; ) } //loop over the string: i=1; !i& i&=*_; //skip leading `)`s !i&*_++&&printf("@) ") //and print "@) "for each `)` thereafter ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~48~~ 47 bytes ``` x=>"@) ".repeat(x.split(/(?<=@.*)\)/).length-1) ``` [Try it online!](https://tio.run/##dVDNCsIwDL73KcpOrbBOzzoNgk@hQuus26SupatjB9@9dh3iYJqEQL4fQnIXnWgLWxuXNvoqfScsLuvHRZj90ylpcY59n28ToDhhVhopHOlZa1TtSEZ2mxzYgp5oRpmSTemqdEX9mgMdAr9wsE0KjfgP5svDH2PEUOQQxAYUYK4O0iFnKEwwNKyJAx9P4Yizm7YHUVSkx/kWF7pptZJM6ZJM3/G5nQc3Py7PYb1/Aw "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), ~~53~~ 49 bytes ``` x=>[...x].map(y=>y<"0"?m+=s&&"@) ":s=1,s=m="")&&m ``` [Try it online!](https://tio.run/##dVDdCoIwFL7fU4xdDEc17LaajaCnEGHLrAznxmai0LsvXUGCdc7hwPl@@ODcZStdbkvTrGp9LnwrLbyW6iTN4dFUhYUM@o4lKaW0y6iSJupZ0u9QjPZqwRzGiBOINo6tl44phhDBWPmt4GQs@IQDPRnwxn8wX57/MQYMBA7wsDjhfK4epGPPUD7BwBgTDkGdqcpGAEEv2h5lfos6yBKY69rpqqCVvkbTh0TdxzC4RRpnQ7x/AQ "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 60 bytes ``` x=>x.replace(/(@?)(\)*)/g,(_,a,b)=>a&&b.replace(/./g,"@) ")) ``` [Try it online!](https://tio.run/##dZBRC4IwFIXf9ytGD7IbNnsP7RL0KyratGXGcjJN9tB/t2mBgnU3BvvOORy4d9nKOrNF1axKc1FdKy3Ni0cqq92z0crSmHYuThy3qtIyUyxiuAV2hCVEecjOoQxTiBMZBOlo4V5aINAFQLcRCP3QF/VkcsmH/1BGHf8EB0YGjeDwICDO3d7anxnFCSN9zfARvK500Qgi@NXYvcxuzNE4oZkpa6MV1yZn090w9w34tDisT76@ewM "JavaScript (Node.js) – Try It Online") [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~10~~ 9 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` @sj∑L@) × ``` [Try it here!](https://dzaima.github.io/Canvas/?u=QCV1RkY1MyV1RkY0QSV1MjIxMSV1RkYyQ0AlMjklMjAlRDc_,i=JTI5JTI5JTI5JTI5JTI5QCUyOSUyOUAlMjklMjklMjk_,v=8) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 14 bytes ``` ^\)+|@ \) @) ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPy5GU7vGgYsrRpPLQVPh/38HTRDgglAQhgOE5gKRXA4Omg4OUBEQBNIgLhdIGQA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ^\)+|@ ``` Delete leading `)`s and all `@`s. ``` \) @) ``` Replace all `)`s with `@)`s. (Note: trailing space.) [Answer] # [Python 2](https://docs.python.org/2/), 39 bytes ``` lambda s:'@) '*s.lstrip(')').count(')') ``` [Try it online!](https://tio.run/##dY7RCsIgGIXvfYqf3ag1BnU5GPgWXVTEqq0JpqKOEfTu9mtBg5WKHL9zPGofYTB6G/vmEFV7P19b8DUVHOjKV8oHJy2jnPLqYkYdsozTIFUHm5qALyFAA66dTlLbMTBeeask5uAJlBNwnUe/Zx61dVKHRAjIHrTJGqSGfcCaNQV6xMpPrNg5o291UQLDVBl4FDwN7MXPzRZ58x/O1xd/LmZGskdE3gQXYpnGaJoLKmaMpGfy4QU "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ṣṀḊẎ”@pK ``` [Try it online!](https://tio.run/##y0rNyan8///hzsUPdzY83NH1cFffo4a5DgXe////1wQBAA "Jelly – Try It Online") -1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). [Answer] # [Perl 5](https://www.perl.org/) `-p`, 26 bytes ``` $_=s/^.*?@//&&'@) 'x y/)// ``` [Try it online!](https://tio.run/##dY3RCsIwDEXf@xUBZbOC1hefRMx/iMqQ6ipbW9oMFfx2a1sFB9MkBHLuTWKla5ZhfFhPvG0UCRB8u9itYASXzhOcjAPXaa30GaiWQDLCY@Wlh6ui2nQETkZTWxF9PG265sV@Pt2gEEVRIofyBnfBhQgBeQp4QKS9Ym/@Q/nq@GcxM5Y1hrkhRxy6ozXlgGKPsfQmD09jSRntw8w2Lw "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` ')Û'@KS'@ìðý ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fXfPwbHUH72B1h8NrDm84vPf/fwcHTQcg1tT8r6ubl6@bk1hVCQA "05AB1E – Try It Online") **Explanation** ``` ')Û # trim leading ")" '@K # remove all "@" S # split to list of characters '@ì # prepend "@" to each ðý # join on spaces ``` [Answer] ## Batch, 58 bytes ``` @set s=%1@ @set s=%s:*@=(% @set s=%s:@=% @echo%s:)=@) % ``` Takes input as a command-line parameter. Explanation: ``` @set s=%1@ ``` Suffix an `@` in case the input doesn't contain any. ``` @set s=%s:*@=(% ``` Delete up to the first `@`, replacing it with a `(` to ensure that the string is not empty (because `%:%` doesn't work on empty strings). The `(` also makes the `echo` work if the rest of the string is empty. ``` @set s=%s:@=% ``` Delete any remaining `@`s. ``` @echo%s:)=@) % ``` Expand any remaining `)`s. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 10 bytes ``` Z¡¦JS'@ìðý ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/6tDCQ8u8gtUdDq85vOHw3v//NTUdHIDIQVNTEwA "05AB1E (legacy) – Try It Online") [This bug](https://chat.stackexchange.com/transcript/message/50573719#50573719) forces me to use the legacy version. This is the code for the current version of 05AB1E (11 bytes): ``` '@¡¦JS'@ìðý ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f3eHQwkPLvILVHQ6vObzh8N7//zU1HRyAyEFTUxMA "05AB1E – Try It Online") Port of my Jelly answer. [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), 15 bytes ``` r/^\)+|@/ ¬mi'@ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVM&code=ci9eXCkrfEAvIKxtaSdA&input=IkBAKUBAQCkpKSI) ``` r/^\)+|@/ ¬mi'@ :Implicit input of string r :Remove /^\)+|@/ : "@"s and leading ")"s ¬ :Split m :Map i'@ : Prepend "@" :Implicit output, joined with spaces ``` ## Alternative ``` e/^\)/ è\) Æ"@) ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVM&code=ZS9eXCkvIOhcKSDGIkAp&input=IikpKUBAKUBAQCkpKSI) ``` e/^\)/ è\) Æ"@) :Implicit input of string e :Recursively remove /^\)/ : Leading ")" è\) :Count remaining ")"s Æ :Map the range [0,Count) "@) : Literal string :Implicit output, joined with spaces ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 49 bytes ``` ,[[-<+>>++++<]>[[-]<<<[[.>]<---------.[-]]>[-]],] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fJzpa10bbzk4bCGxi7YC8WBsbm@hoPbtYG10Y0AOKAuWAhE7s//8ODpoOQKypCQA "brainfuck – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 15 bytes ``` f/@\)+/ ËÅç"@) ``` Saved 2 bytes thanks to @Shaggy. [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVA&code=Zi9AXCkrLyDLxeciQCkg&input=IkBAKUBAQCkpKSI) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` œl”)ḟ”@⁾@ jⱮ ``` [Try it online!](https://tio.run/##y0rNyan8///o5JxHDXM1H@6YD6QcHjXuc1DIerRx3f///zU1HRw0gQBIAAA "Jelly – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 34 bytes ``` {~map {'@)'xx.chars-1},m:g/\@\)+/} ``` [Try it online!](https://tio.run/##dY/NjoIwFIXX9iluDBmsOjBsZqExuVs38wLIosF2hqQgoZhAGHx1vFSCxJ/@pf3uOeemuSz0d5fWH2rXNZdU5NC4yN2q8uI/UZjPoF2nm1//gAe@8ttuy9SpAGe5//F0kkkDDZul/sJbcnDhn3Z/9bcEa3CSDHZwcb6Gp6xyGZfyaGEwQBGXZ6EJqQXpOdFETaSZHCXUaWZEDXMlEr0BCg/JEcGoDUdbBIMnHMzRnIJbkNrIe04ujJnknM7lg561HfJ@0M@QTxe78ReVex3fGC1jtsbQHsgRn9Uk7ecTxQljfRv7uAI "Perl 6 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, 28 bytes ``` $_= ~/@/&&'@) '*$'.count(?)) ``` [Try it online!](https://tio.run/##LYoxDoAwDAP3viJDRQgC@gIgP0GCBQbaCsrAwtMJRMWWfE7k/ZwuifvqE1hXgx3beQlbrAGhBxQ7dnA7dkWBTICVxXYOp0/lQCTCpDIZuXCm0TTMxPx/1B/1NDp7Qkxr8Ic08QU "Ruby – Try It Online") **Explanation** ``` # -p gets a line of STDIN $_= # Set output to ~/@/ # Find first '@' in input # nil (falsey) if not found && # If found, set output to '@) ' # Sliced gimbap * # Repeat $' # In the string after the first '@', .count(?)) # ... count the number of ')' # -p outputs the contents of $_ # nil outputs as a blank string ``` [Answer] # Java 10, 49 bytes ``` s->s.replaceAll("^\\)+|@+","").replace(")","@) ") ``` [Try it online.](https://tio.run/##bVDLjgIhELz7FZ0@0Zl1PkCzhv2A9eLRR8IiGlzEydBjYtRvH2HEg85AQqgquqjugzqr8WH732qnQoBfZf11BGA9m3qntIF5ggALrq3fgxb5Emga@fsoHoEVWw1z8PANbRjPQlmbysXiH@cEblYrKm6ywC9EeikCKWJJgNROk0nV/Llokr3OJ7uFY8ySv1uuQdEzCJvAIlamhV2Id26AlQPkO@7pH1CSlEMuaX@SskelBNibV9dj9yCP1Pqq4dzl4hLYHMtTw2UVRXZedHKBE8DCl/oJKbve2wc) [Answer] # [sed](https://www.gnu.org/software/sed/), 30 bytes ``` s/)\?@\()\?\)/\1/g; s/)/@) /gp ``` [Try it online!](https://tio.run/##K05N0U3PK/3/v1hfM8beIUYDSMZo6scY6qdbKwDF9B00FfTTC/7/19R0ACIg1vyvmwcA "sed – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~91~~ ~~90~~ ~~85~~ ~~71~~ ~~70~~ ~~59~~ 57 bytes ``` StringReplace@{(StartOfString~~")"..)|"@"->"",")"->"@) "} ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE7876Zg@z@4pCgzLz0otSAnMTnVoVojuCSxqMQ/DSJcV6ekqaSnp1mj5KCka6ekpAPkAmkHTQWl2v8BQBUlDlpuCvoOCtVAMRBQ0lGAsuBsBzgTRELZYMJB08EBIQuCEKYDlAHSC7QHAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 20 bytes ``` *?}\@z/>zxz\@\)0"@) ``` [Try it online!](http://pythtemp.herokuapp.com/?code=*%3F%7D%5C%40z%2F%3Ezxz%5C%40%5C%290%22%40%29+&input=%29%40%29%29%40%29%29%29&debug=0) Note that there is a trailing space at the end of the program. This one is (or rather, started out as) a rather direct translation of the Python 2 answer (though the lstrip part was surprisingly difficult). Explanation: ``` * # repeat string ? # repeat count: ternary }\@z # condition: check whether input contains @ / # if condition is true: count occurrences of one string in another > # array slice: all elements of array (or string) from a specific index and upwards z # the thing to slice (input) xz\@ # the index first occurrence of \@ in z \) # string to count occurrences of (\x is shorthand for "x") 0 # value when ternary condition is false "@) " # the string to be repeated (automatically terminated by end-of-line) ``` [Answer] # [krrp](https://github.com/jfrech/krrp), 63 bytes ``` ^":\L,^*':?#?E'E!-@1#!r'?=#!f'$64.-?*L$64.L$41.L$32.-@0#!r'.0". ``` [Try it online!](https://tio.run/##yy4qKvivaPc/TskqxkcnTkvdyl7Z3lXdVVHXwVBZsUjd3lZZMU1dxcxET9deywdE@6iYGAIJYyM9XQcDkBI9AyW9/zE@CooOIGkFRU2QAi4uOwUfBx9NGHRF46OJOaCKgGk4HyrqAFbngK4WjjXh6hA8qNmu///lF5Rk5ucV/9fVLS4pAgA "krrp – Try It Online") --- # Explanation ``` ^": ~ take the string as a parameter named `"` \L ~ import the list module ,^*': ~ apply a binary function ?#?E' ~ if the string is empty, E ~ return the empty string; else !-@1#!r' ~ define `-` as the cut Gimbap ?=#!f'$64. ~ if an at sign is seen, - ~ return the cut Gimbap; else ?* ~ if an at sign has been seen, L$64.L$41.L$32.- ~ return a Gimbap piece together ~ with freshly cut Gimbap; else @0#!r' ~ proceed to cut .0". ~ to zero and the above taken string ``` [Try it online!](https://tio.run/##fVLBjtowFLznKyawEmK1QbvtqoddFXJBveQTqlUc8kKsJbZlm7b00E9vaptAgLXqKLH8MuMZP8@71qpPl4iMP6ip4YJQLktYiYpgW8KOdVXNQL@UJmO4FP3b5CVKt@z9SDFWc7EFM2BQTLOOLGkIN9coJ2WC70V0A94pqe1RlRuLTtb7HSV4eLufvXyEM6V2BydRccH0Ac1ebKzzlwCr6Wo9@4AHby7tcQPqlD08OALWMT@AJrvXIrACduC@gnaGPC/N8qdpqmc3vFMns9J3wdM3e4tvvKuY8rTV12nazO6@PC@uaN4hE2AWhm@Fd2iIRDCILGrw0uEoMfrD6j5KuxZqncnKKV3IofDuirvnJ/f5/GmRHXknPTYoQXHauFuXW3IWdALEo@XHT25bNC5Frbu2qFnkj5FmAkrLDbnwuFQ6XoLF42QRC6DEb9LSnawODWGV/EEhlmK4uN4lL81D39O5P9v/o/cK07py6zY0SbJEkRfz07MeZcnYm58BMNby60qYz@uhmgdcfos9v/MzblwNe6/7v1L56Js@y9xB/wE "krrp – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 42 bytes ``` ''+($args|sls '(?<=@.*)\)'-a|% m*|%{'@)'}) ``` [Try it online!](https://tio.run/##hY5bDsIgEEX/WcXEUGFq6wKMjSzExDRK1QS1ljaalK4d6UNF0@jAB8w5cyG/3GShD1IpS7OktozNOE2LvTZaaWB8tUzEPMQ1sjg1AZxCE9RMIGvQNoQITsBVxF2rLRaBO4G3GX4aY86IKf6G9fTd6X3P@LoKFGIk1Y9s1w8ufOo/7H0GwUAAdcfo8ZxXZQRU3nO5LeUOEqCbHhVSV6p0jSnNBrEDE8oHFsvraxAXz4kJaewD "PowerShell – Try It Online") Unrolled: ``` $arrayOfCuttedGimbaps = $args|select-string '(?<=@.*)\)' -AllMatches|% Matches|%{'@)'} ''+($arrayOfCuttedGimbaps) # toString and output ``` ]
[Question] [ # The challenge The [plastic number](https://en.wikipedia.org/wiki/Plastic_number) is a number related to the golden ratio, with many interesting mathematical properties. As such, there are many approaches that can be used to calculate the number. In order to precisely specify the number for the purposes of this challenge, we'll use the following definition (although there are plenty of equivalent definitions, and you can use any definition you wish as long as it comes to the same number): > > The plastic number is a real number *ρ* such that *ρ*³=*ρ*+1. > > > Your challenge is to write a program or function which takes an integer *x* as input (with *x* > 1), and produces an approximation to *ρ* as output, such that the larger the value of *x* gets, the closer the output gets to *ρ* (with at most finitely many exceptions; staying at the same value counts as "closer" for this purpose), and for any positive number *δ*, there's some input *x* to your program that produces an output that's within *δ* of *ρ*. # Clarifications * If you're outputting via a method that inherently outputs strings (e.g. the standard output stream), you can format output either in decimal (e.g. `1.3247179572`), or as a ratio of two integers with a `/` character between them. * If you're outputting as a value within your programming language (e.g. returning from a function), it must be of a fixed-point, floating-point, or rational type. (In particular, you can't use data types that store numbers symbolically, unless they're used only to hold the ratio of two integers. So if you're using Mathematica or a similar language, you'll need to include the extra code to actually generate the digits of the output.) * Your answer must work in a hypothetical variant of your language in which integers can be arbitrarily large, and memory (including stack) is unlimited. You may *not* assume that floating-point arithmetic in your language is arbitrarily accurate, but must instead use its actual accuracy (meaning that outputting a floating-point number is only going to be possible in languages where the accuracy of floating-point numbers can be controlled at runtime). * *x* can have any meaning you want (so long as increasing it gives more accurate outputs). I imagine that most submissions will have it control the number of digits of output to produce, or the number of iterations of the algorithm used by your program to converge on the plastic number, but other meanings are acceptable. # Testcase Here are the first few digits of the plastic number: ``` 1.32471795724474602596090885 ``` More digits are available [on OEIS](https://oeis.org/A060006). # Victory condition As usual for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shorter is better, measured in bytes. However, feel free to post answers even if they don't win, so long as they add something (e.g. a different language, or a different algorithm) to the existing answers. [Answer] # [Python 2](https://docs.python.org/2/), 49 bytes ``` n=x=input() while n**3/x/x<n+x:n+=1 print n,'/',x ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8@2wjYzr6C0REOTqzwjMydVIU9Ly1i/Qr/CJk@7wipP29aQq6AoM69EIU9HXV9dp@L/f0MDEAAA "Python 2 – Try It Online") The idea is to express the `ρ` with `ρ³=ρ+1` as a fraction `n/x` whose denominator `x` is the input accuracy parameter. We take `(n/x)³=n/x+1` and clear denominators to get `n³=x²(x+n)`. Since the LHS increases in `n` faster than the RHS, we can approximate the equality point `n` as the smallest with `n³≥x²(x+n)`. The code counts up `n` until this is the case, starting at `x` which is smaller. A small byte save is to divide both sides by `x²` to write `n³/x²≥x+n` (negated in the `while` condition). This is floor division in the code, but the fractional part lost is negligible. A same-length alternative instead puts `x` as the numerator: **[Python 2](https://docs.python.org/2/), 49 bytes** ``` n=x=input() while x**3/n/n<n+x:n-=1 print x,'/',n ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8@2wjYzr6C0REOTqzwjMydVoUJLy1g/Tz/PJk@7wipP19aQq6AoM69EoUJHXV9dJ@//f0MDIAAA "Python 2 – Try It Online") [Answer] # Mathematica, 20 bytes ``` #^3-#-1&~Root~1~N~#& ``` Mathematica's builtin `Root` function gives the solutions to a polynomial equation `f[x] == 0`. ### Explanation ``` #^3-#-1&~Root~1~N~#& & (* Function *) #^3-#-1& (* A pure-function polynomial, x^3-x-1 *) ~Root~1 (* Find the first root *) ~N~# (* approximate to (input) digits *) ``` ### Sample I/O ``` In[1]:= f=#^3-#-1&~Root~1~N~#&; f[1] Out[1]= 1. In[2]:= f[9] Out[2]= 1.32471796 In[3]:= f[100] Out[3]= 1.324717957244746025960908854478097340734404056901733364534015050302827851245547594054699347981787280 ``` [Answer] # Mathematica, 27 bytes ``` x/.Solve[x^3==x+1>2,x]~N~#& ``` *-1 byte from Martin* *-2 bytes from ovs* **input** > > [27] > > > **output** > > {1.32471795724474602596090885} > > > [Answer] # [sed](https://www.gnu.org/software/sed/), ~~67~~ 60 (59+1) bytes ``` s,^,1/1/1 , :;s,(1*/(1*)/(1*).*)1$,\2\3/\1, t s,(/1*).*,\1, ``` [Try it online!](https://tio.run/##K05N@f@/WCdOx1AfCBV0uKysi3U0DLX0gVgTTOhpaRqq6MQYxRjrxxjqcJVwAeX1weI6QP7//4bI4F9@QUlmfl7xf11XAA) +1 for the `-E` flag (ERE instead of BRE). Input and output are both unary: input 11111 for x=5 e.g. Output is a fraction of two unary numbers: the aforementioned 11111 input yields output 11111/1111 (5/4 in decimal). Approximates the plastic number as a fraction between to consecutive elements of the [Padovan sequence](https://en.wikipedia.org/wiki/Padovan_sequence). [Answer] ## Mathematica, 27 bytes ``` Nest[(1+#)^(1/3)&,1,#]~N~#& ``` Uses a truncated approximation of the nested cubic radical form **³√(1+³√(1+³√(1+...)))**. While the output will always have *x-1* decimal places, the result is actually less accurate than that, because the expression converges more slowly than one digit per iteration (*x* is also used as the number of nested radicals that are computed). For example *x = 100* gives ``` _________________________________________________________________________ 1.324717957244746025960908854478097340734404056901733364534015050302827850993693624204577670741656151 ``` where the overlined part is correct. [Answer] # [Octave](https://www.gnu.org/software/octave/), 50 bytes ``` @(n)char(digits(n)*0+vpasolve(sym('r^3-r-1'))(1)); ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI08zOSOxSCMlMz2zpBjI0zLQLitILM7PKUvVKK7M1VAvijPWLdI1VNfU1DDU1LT@n6ZhqsmVpmFooPkfAA "Octave – Try It Online") Defines an anonymous function, with`n` the desired number of digits of output. This answer abuses that `digits` returns the current setting for the number of digits in variable precision arithmetic. This means we can just use it in an anonymous function without errors about 'Too many output arguments'. Other than that, it's really straightforward: `vpasolve` is short for Variable-Precision Arithmetic Solve, with the precision set by the last call of `digits`. Since `vpa` is a Symbolic data type in Octave, which is banned per the spec, we just wrap the whole function in `char(...)` to get string output. Note that in `solve` and `vpasolve`, the `f==0` is implied, so `r^3==r+1` has been replaced by `r^3-r-1 (==0)` [Answer] # MATL (27 28 bytes) ``` 7BG:"t@)y@Q)+h]tG3+)yG2+)/ ``` My first solution (27 bytes) [Try it online!](https://tio.run/##y00syfn/39zJ3UqpxEGz0sFQW1M7I7bE3Vhbs9LdSFtT//9/Q7Ovefm6yYnJGakA) It's certainly not optimal, I'm still getting used to MATL. ## Explanation: I create a [Padovan sequence](https://en.wikipedia.org/wiki/Padovan_sequence) up to input+3 then find the ratio of the last two numbers. ``` 7B % Turn 7 into binary to give 1 1 1 G:" % For k=1:input do... t@) % Existing sequence member k y@1+) % Existing sequence member k+1 +h % Add them together and concatenate to the sequence array ] % End loop tG3+) % Final sequence member yG2+) % Second last sequence member / % Divide to approximate ρ ``` ## Proper fraction output (35 bytes) (28 bytes, @Sanchises): However, the first solution doesn't fulfill the need for arbitrary precision being the floating point limit of default MATL settings. So rather than adding several bytes to extend this precision, it's simpler to take the proper fraction route and write a fraction of the final two integers in the (N-1)th and Nth elements of the truncated Padovan sequence. e.g "114/86" 7BG:"t@)y@1+)+h]tG3+)V'/'YcyG2+)VYc ``` 7BG:"t@tQh)sh]tJ)V47hyJq)Vh& ``` Courtesy of user @Sanchises. :) [Try it online!](https://tio.run/##y00syfn/39zJ3UqpxKEkMEOzOCO2xEszzMQ8o9KrUDMsQ@3/f0Ozr3n5usmJyRmpAA) ## Non-iterative evaluation: Notably, my shortest code for [the 'exact' version](https://en.wikipedia.org/wiki/Plastic_number) is (23 bytes): ``` 1-1h69X^12**108+1I/^6/s ``` [Try it online!](https://tio.run/##y00syfn/31DXMMPMMiLO0EhLy9DAQtvQUz/OTL/4//@vefm6yYnJGakA) ...but doesn't give arbitrary precision. I wonder if anyone can adjust this to fulfill the rules (use the input etc) and still add less than 5 bytes? :P [Answer] # [M](https://github.com/DennisMitchell/m), ~~15~~ 14 bytes ``` ²×3’ *3Ḥ‘÷Ç Ç¡ ``` [Try it online!](https://tio.run/##ASEA3v9t///CssOXM@KAmQoqM@G4pOKAmMO3w4cKw4fCof///zU "M – Try It Online") ### Algorithm This uses rationals and Newton's method. Specifically, for input **x**, the first **x** iterations with starting value **x** are applied. We're trying to find a specific root of the polynomial **p(t) = t³ - t - 1**. Newton's method achieves this by taking a starting value **t0** – sufficiently close to **ρ** – and recursively defining a sequence by **tn+1 = tn - p(tn) / p'(tn)**. Since **p'(t) = 3t² -1**, we get **tn+1 = tn - (tn³ - tn - 1)/(3tn² - 1) = (3tn³ - tn - tn³ + tn + 1) / (3tn² - 1) = (2tn³ + 1) / (3tn² - 1)**. Note that the initial approximation **x** gets progressively worse as **x** increases. While the output for **x = 3** is slightly less precise than the output for **x = 2**, since Newton's method converges quadratically to **ρ**, this shouldn't be an issue for large values of **x**. ### How it works ``` Ç¡ Main link. Argument: x Ç¡ Call the second helper link x times, which initial argument x. *3Ḥ‘÷Ç Second helper link. Argument: t *3 Compute t³. Ḥ Unhalve; yield 2t³. ‘ Increment; yield 2t³+1. Ç Call the first helper link with argument t. ÷ Divide the left result by the right one. ²×3’ First helper link. Argument: t ² Compute t². ×3 Compute 3t². ’ Decrement; yield 3t²-1. ``` [Answer] # [Julia 0.5](http://julialang.org/), ~~44~~ 40 bytes ``` |(x,r=1)=x<1?r:~-x|big(2r^3+1)//(3r^2-1) ``` Uses rationals and Newton's method. [Try it online!](https://tio.run/##yyrNyUw0/f@/RqNCp8jWUNO2wsbQvsiqTreiJikzXcOoKM5Y21BTX1/DuCjOSNdQ839afpFChUJmnoKGoZWhgSYXZ5GCrQJQN5BVUJSZV5KTp1Gko6Ck8KizQ0FJRyEtJz@xRKNIU5MrNS/lPwA "Julia 0.5 – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 19 bytes ``` {{(⍺+⍵*÷3)*÷3}/⍵/1} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG9qQMCjtgnGJv@rqzUe9e7SftS7VevwdmNNEFGrD@TpG9b@TwMqedTb96ir@VHvmke9Ww6tN37UNhGoOTjIGUiGeHgG/09TMORKUzACYmMgNgFiUyA2A2JDAwMDAA "APL (Dyalog Extended) – Try It Online") Uses the cube root approximation method, which very, very slowly creeps towards the value of the plastic number. ## Explanation ``` {{(⍺+⍵*÷3)*÷3}/⍵/1} ⍵ → input ⍵/1} replicate 1 ⍵ times { }/ reduce by inner fn: *÷3 cube root of ⍵*÷3 cube root of right arg ⍺+ plus left arg ``` [Answer] # [Rust](https://www.rust-lang.org/), 66 bytes ``` |n|{let mut i=(1,1,1);for _ in 0..n{i=(i.1,i.2,i.0+i.1)}(i.1,i.2)} ``` [Try it online!](https://tio.run/##RUzLDsIgELzzFWtPbESk9ibBXzEmlmSTsjUVTpRvRzAxZg4zmdeW3rF6hvAglpiXOYK/epY0XfB066S6dHXn/ZuGFIGcHFUDWr9ucAdiMFpzbj7pUZFuI22OTWP5OViqFf1AcgrqOfMa0Hk5GbTitRHHhQ9yyOWcy6D@FStK/QA "Rust – Try It Online") Uses the padovan sequence to approximate the plastic number. Returns a tupled `(num,denom)`. A readable version that works with arbitrary precision integers can be found [here](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&code=use%20num%3A%3ABigUint%3B%0A%0Afn%20main()%7B%0A%20%20%20%20let%20f%3Afn(i32)-%3E(BigUint%2CBigUint)%20%3D%20%7Cn%7C%7B%0A%20%20%20%20%20%20%20%20let%20mut%20i%3D(1u32.into()%2C1u32.into()%2C1u32.into())%3B%0A%20%20%20%20%20%20%20%20for%20_%20in%200..n%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20let%20tmp%20%3D%20%26i.0%2B%26i.1%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20i%3D(i.1%2Ci.2%2Ctmp)%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20(i.1%2Ci.2)%0A%20%20%20%20%7D%3B%0A%20%20%20%20let%20(num%2Cdenom)%20%3D%20f(900)%3B%0A%20%20%20%20println!(%22%7B%7D%2F%7B%7D%22%2Cnum%2Cdenom)%3B%0A%7D). [Answer] # AWK, 34 bytes ``` {for(;$1^3>$1+1;)$1=($1+1)^(1/3)}1 ``` Step by step: ``` { # $1 is the input (a positive integer) for(;$1^3>$1+1;) # as long as $1 cubed is bigger than the input plus one $1=($1+1)^(1/3) # assigns $1 this new value: cube root of $1 plus one } 1 # prints $1 ``` [Try it online!](https://tio.run/##SyzP/v@/Oi2/SMNaxTDO2E7FUNvQWlPF0FYDxNKM0zDUN9asNfz/34jLmMuUy9CAy8zEnMvS0NjQxMwcAA "AWK – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 23 bytes ``` U[X3m¹/¹/¹X+›#X>U]X'/¹J ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/NDrCOPfQTn0witB@1LBLOcIuNDZCHcj1@v/f0AAIAA "05AB1E – Try It Online") --- Direct port of <https://codegolf.stackexchange.com/a/126822/59376> by xnor. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` AIθθAθνW‹∕∕Xν³θθ⁺νθA⁺ν¹νI∕νθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DObG4RKNQU0ehUNOaCypWqKOQB@SVZ2TmpCpo2Gh45pW4ZJZlpqQisbS0NPJ0FIzBGiFYGyRQqKmpyaUABFCjwIKGmiADuQKKMvNKIBYizIHq@f/f0MjY/L9u2X/d4hwA "Charcoal – Try It Online") Link to verbose mode. Also I apparently messed up `Divide` and `IntDivide` :| Uses the same method as the Python and JavaScript answers. [Answer] # [NewStack](https://github.com/LyamBoylan/NewStack), 14 bytes ``` ¹Fᵢ{E2x³⁺÷3x²⁻ ``` ### Break down: ``` ¹ Add arbitrary number 1 to the stack. Fᵢ{ Define for loop with a user's input amount of itterations. E Define new edit for element 0 (element 0 being the 1 added. earlier). 2x³⁺÷3x²⁻ update x to equal (2x^3+1)/(3x^2-1). (x = element 0). ``` ### How it works: The formula (2x3+1)/(3x2-1) comes from the simplification of [Newton's method](https://en.wikipedia.org/wiki/Newton%27s_method) for the equasion x3=x+1. You can find it [here](https://www.wolframalpha.com/input/?i=simplify%20x-(x%5E3-x-1)%2F(3x%5E2-1)). Repeating this process an infinite amoune of times converges to the plastic number. It's rate of convergence is rather quick at around 2.6 decimals per iteration. ``` INPUT ITERATION >> VALUE 0 >> 1 1 >> 1.5 2 >> 1.3478260869565217 3 >> 1.325200398950907 4 >> 1.3247181739990537 5 >> 1.3247179572447898 6 >> 1.324717957244746 <- 16 decimal precision in 6 iterations! ... 100 >> 1.324717957244746 ``` # Padovan sequence alternative, 27 25 17 bytes ``` ¹Fᵢ{[ƨ2+ƨ3]ℲƤƨ/ƨ2 ``` ### Break down: ``` ¹ Append first element of Padovan sequence. Fᵢ{ Ⅎ Define for loop of user's input amount of iterations. [ƨ2+ƨ3] Append sum second and third to last elements. Ƥƨ/ƨ2 Print ratio of last two elements. ``` -2 bytes by choosing better print strategy -8 bytes by choosing better way to index stack ### How it works: As the [Padovan sequence](https://en.wikipedia.org/wiki/Padovan_sequence) continues, the ratio of the last two elements converge to the plastic number. ``` INPUT ITERATION >> VALUE 0 >> 1 1 >> 2 ... 10 >> 1.3157894736842106 ... 89 >> 1.324717957244746 <- 16 decimal precision in 89 iterations ... 100> > 1.324717957244746 ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 35 bytes ``` ->x{n=1;n+=0.1**x while n**3-n<1;n} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf166iOs/W0DpP29ZAz1BLq0KhPCMzJ1UhT0vLWDfPBihR@79AIS3aMJYLRBlBKGMIZRL7HwA "Ruby – Try It Online") [Answer] ## Clojure, 46 bytes ``` #(nth(iterate(fn[i](Math/pow(inc i)(/ 3)))1)%) ``` Uses the iterated cube-root formula. This is a bit more interesting but longer: ``` (def f #(apply comp(repeat %(fn[i](Math/pow(inc i)(/ 3)))))) ((f 10)1) 1.3247179361449652 ``` [Answer] ## Javascript, 36 bytes ``` f=(x,n=x)=>n**3/x/x<n+x?f(x,++n):n/x ``` Works the same as the top python answer. No `console.log` was included because if you run `f(x)` in console it will be logged automatically. ``` f=(x,n=x)=>n**3/x/x<n+x?f(x,++n):n/x console.log(f(300)) ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 38+3 = 41 bytes ``` 11\n; ?!\}2,:01{::::}**-+0(?$-{+{1-:} ``` Expects the input to be present on the stack at program start, so +3 bytes for the `-v` flag. [Try it online!](https://tio.run/##S8sszvj/39AwJs@ay14xptZIx8rAsNoKCGq1tHS1DTTsVXSrtasNda1q////r1umYGoAAA "><> – Try It Online") Effectively performs a binary search to narrow in on the output value. Increasing `x` increases the number of iterations to perform. *Edit: refactored calculation slightly to save 1 byte, previous version:* ``` 11\n; ?!\}2,:0{::::}**$-1-0)?$-{+{1-:} ``` [Answer] # k, 27 bytes ``` {"/"/$1_|x({y,z,x+y}.)/3#1} ``` [Try it online!](https://tio.run/##y9bNz/7/v1pJX0lfxTC@pkKjulKnSqdCu7JWT1PfWNmwVl3R0MDg/38A "K (oK) – Try It Online") This assumes infinite integers (which, alas, is not true). It uses the [Padovan sequence](https://en.wikipedia.org/wiki/Padovan_sequence). [Answer] # TI-BASIC, 21 bytes ``` :Prompt X //Prompt for input, 3 bytes :While X //While X, 3 bytes :³√(1+Y→Y //Calculate cube root of 1+Y and store to Y, 7 bytes :DS<(X,0 //Decrement X and skip next command (which doesn't do anything), 5 bytes :End //End While loop, 2 bytes :Y //Display Y, 1 byte ``` Uses this [recursive formula](https://en.wikipedia.org/wiki/Plastic_number#Recurrences). Interestingly, hard-coding the number and rounding it gives the same byte-count: # TI-BASIC, 21 bytes ``` :Prompt X //Prompt for input, 3 bytes :.5√(3 //Store √(3)/2 to Ans, 5 bytes :Ansֿ¹cosh(3ֿ¹coshֿ¹(3Ans //Store the plastic number to Ans, 9 bytes :round(Ans,X //Round the plastic number X decimal digits, 4 bytes ``` Uses this [trigonometric formula](https://en.wikipedia.org/wiki/Plastic_number#Trigonometry). [Answer] ## [C#](https://tio.run/##tVI7b8IwEN75Fad0iE2DIaBOiKlSpUpQRaJqB8RgEhcsJXZlXyAVym9PnYRX6NwbPNx9j/tOju0g00pXVW6l2sLyx6LIpr045dZCdOyBK4scZQx7LRNYcKmIRePAqzVws7W0wbTIup61sjoV7NNIFHOpBImcmBN4y7ONMEQqZBE3VpCavRqtKaXThl3Wz61j6wN/@FDcm8ovIAXMZjCmcGnWZQTmRoEXDkNvepnsuYEEZnfKBQwgpGz5nUok/tCnXcLGEdr7MJdxLwyyd/2qcDImSR2ji44d@ho1WYW3gNNWbT72ok3GkXjHUTk8hqUXdCOQMfTd3XHHIn0gmwAmFB6vjbhu0A7D7bVspIkSh5ML8R/8oNlowYsPnubiiqJsLtQWd5QGXefJnbO7bt8lG/yT@/kf9Mqqqp5@AQ), 317 bytes ``` using m=System.Math;a=x=>{if(a==0)return "1/1";var d=a(x-1).Split('/');var b=int.Parse(d[0]);var c=int.Parse(d[1]);return string.Format("{0}/{1}",(2*m.Pow(b,3)+m.Pow(c,3)).ToString(new string('#',int.MaxValue.ToString().Length)),(3*m.Pow(b,2)*c-m.Pow(c,3)).ToString(new string('#',int.MaxValue.ToString().Length)));}; ``` It returns the result as a fraction. ### Explanation It uses the Newton's method with x iterations for finding the root of the polynomial p^3-p-1=0. The formula is x\_n=1-(f(x\_(n-1)))/(f'(x\_(n-1))), and x\_0 is a starting point. The polynomials derivative is 3p^2-1, and let's say x\_(n-1)=b/c. Then, by using the above formula we get, that x\_n=(2 b^3+c^3)/(3 b^2 c-c^3). Let's also say, that we start from 1, this will happen, when x=2, because x>1, and is an integer. Idented, and commented code: ``` using System; string PlasticNumber(int x) { if (x == 2) return "1/1"; //If x=2, we return our starting value, but we need to return it as a fraction var d = PlasticNumber(x - 1).Split('/'); var b = System.Convert.ToInt32(d[0]); var c = int.Parse(d[1]); //We parse the previous value of the fraction, and put it into two variables return string.Format("{0}/{1}", (2 * Math.Pow(b, 3) + Math.Pow(c, 3)) .ToString(new string('#', int.MaxValue.ToString().Length)), (3 * Math.Pow(b, 2) * c - Math.Pow(c, 3)) .ToString(new string('#', int.MaxValue.ToString().Length))); //We return the result as a fraction, but it's important not to return it in scientific notation, because that will cause issues in the parsing process } ``` [Answer] # PHP, 86 bytes ``` for($p=[1,1,1];$i++<$argn;)$p[]=bcadd($p[$i],$p[$i-1]);echo bcdiv($p[$i+1],$p[$i],$i); ``` [PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/06b11e67f076ef77255504ca2566fedc36e1df4d) Creates the [Padovan Spiral](https://oeis.org/A134816) and print the ratio of the last two numbers. [Answer] # Axiom, 96 bytes ``` h(n:NNI):Float==(n>1.E5=>-1;n:=n+1;j:=digits(n::PI);r:=solve(x^3-x=1,10.^-n);digits(j);rhs(r.1)) ``` results ``` (31) -> [h(i) for i in 0..10] (31) [1.0, 1.3, 1.33, 1.325, 1.3247, 1.32472, 1.324718, 1.324718, 1.32471796, 1.324717957, 1.3247179572] Type: List Float ``` how you can see h(2) should be 1.32 and not 1.33 so there is some error in last digits Then there would be this one of 110 bytes ``` g(n:NNI):Float==(n>1.E5=>-1;n:=n+1;j:=digits(n::PI);x:=sqrt(23./108);r:=(.5+x)^(1/3)+(.5-x)^(1/3);digits(j);r) ``` It use the formula for resolve equation of III grade of type x^3-3\*p\*x-2\*q=0 in the case q^2-p^3>=0 that is m=sqrt(q^2-p^3) and x=(q+m)^(1/3)+(q-m)^(1/3) In our case r^3-r-1=0 this can be written as r^3-3\*(1/3)r-2\*(1/2)=0 so p=1/3 q=1/2 m=1/4-1/27=23/108 x=(0.5+m)^(1/3)+(0.5-m)^(1/3) this one that use Newton iteration with start point r=1 ``` f(n:NNI):Float==(n>1.E5=>-1;n:=n+1;j:=digits(n::PI);e:=10^-n;r:=1.;repeat(v:=(r^3-r-1)/(3*r^2-1);abs(v)<e=>break;r:=r-v);digits(j);r) ``` it change in the function, digits value for obtain one obj of n+1 digits afther the float point. At end the digits() value is assigned back to preciding value. ]
[Question] [ Given \$A = (a\_1,\dots,a\_k)\ k\ge2 \$ a sequence of positive integers, in which all elements are different. Starting from \$i=2\$, while \$a\_i\in A:\$ *(until the last element)* * If \$d=|a\_i-a\_{i-1}|\$ is not already in \$A\$, append \$d\$ to \$A\$ * Increase \$i\$ **Output** the completed sequence. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") ## Example ``` In: 16 21 11 2 16 21 11 2 5 --^ 16 21 11 2 5 10 --^ 16 21 11 2 5 10 9 --^ 16 21 11 2 5 10 9 3 --^ 16 21 11 2 5 10 9 3 --^ 16 21 11 2 5 10 9 3 1 --^ 16 21 11 2 5 10 9 3 1 6 --^ 16 21 11 2 5 10 9 3 1 6 --^ 16 21 11 2 5 10 9 3 1 6 --^ Out: 16 21 11 2 5 10 9 3 1 6 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 5 bytes ``` Δ¥Ä«Ù ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3JRDSw@3HFp9eOb//9GGZjoKRoY6CoZAbBQLAA "05AB1E – Try It Online") ``` Δ until the output doesn't change: ¥Ä absolute differences « concatenate to the original input Ù only keep unique values ``` [Answer] # [Python 2](https://docs.python.org/2/), 57 bytes ``` l=input() d=0 for i in l:l+={abs(d-i)}-set(l);d=i print l ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8c2M6@gtERDkyvF1oArLb9IIVMhM08hxypH27Y6MalYI0U3U7NWtzi1RCNH0zrFNpOroCgzr0Qh5///aEMzHQUjQx0FQyA2igUA "Python 2 – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~17~~ 16 bytes ``` (~.@,2|@-/\])^:_ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Ner0HHSMahx09WNiNeOs4v9r/k9TMDRTMDJUMDRUMAIA "J – Try It Online") ### How it works ``` (~.@,2|@-/\])^:_ ( )^:_ until output does not change 2 /\] for each neighboring pair |@- get the absolute difference , append the result to the list ~.@ and remove duplicates ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 40 bytes ``` ->a,i=0{a|=[(p(a[i])-a[i+=1]).abs];redo} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ9PWoDqxxjZao0AjMTozVlMXSGrbGsZq6iUmFcdaF6Wm5Nf@T4uONjTTMTLUMTTUMYqN/Q8A "Ruby – Try It Online") Takes an array `a` as input and adds unique new elements to it using the set append operator `|=`. Terminates by throwing a rescuable TypeError (which is [now allowed](https://codegolf.meta.stackexchange.com/a/24552/92901)) when attempting to subtract beyond the last element of the array. By that point all of the required output has already been printed to STDOUT. --- # [Ruby](https://www.ruby-lang.org/), 48 bytes ``` ->a,i=0{a|=[(p(A).-a[i+=1]||0).abs]while A=a[i]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ9PWoDqxxjZao0DDUVNPNzE6U9vWMLamxkBTLzGpOLY8IzMnVcHRFigeW/s/LTra0EzHyFDH0FDHKDb2PwA "Ruby – Try It Online") This version avoids the TypeError at a cost of 8 bytes. [Answer] # [R](https://www.r-project.org/), ~~68~~ 57 bytes ``` v=scan();while(any(F-(F=v)))v=unique(c(v,abs(diff(v))));v ``` [Try it online!](https://tio.run/##K/r/v8y2ODkxT0PTujwjMydVIzGvUsNNV8PNtkxTU7PMtjQvs7A0VSNZo0wnMalYIyUzLU0DJKNpXfbf0IzLyJDL0JDLiOs/AA "R – Try It Online") *Edit: -9 bytes thanks to Giuseppe, and -2 more from `(F-(F=v))` (had to be tested to see whether that would work...)* Boringly follows the instructions in the question, in the same order... [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 bytes [SBCS](https://en.wikipedia.org/wiki/SBCS) ``` {⍵,⍵~⍨|2-/⍵}⍣≡ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR71YdIK571LuixkhXH8isfdS7@FHnwv9pCo/aJig86u171NX8qHfNo94th9YbP2qb@KhvanCQM5AM8fAMBqoyNFMwMlQwNFQwAgA "APL (Dyalog Unicode) – Try It Online") Same method as the J answer; I came up with this on my own :) also ended up being 3 bytes shorter, at least atm. [Answer] # [Perl 5](https://www.perl.org/) -pl, 58 bytes ``` $d=abs$a[$;]-$a[++$;],/\b$d\b/||s/$/ $d/ while(@a=split)>$ ``` [Try it online!](https://tio.run/##DcZBDkAwEADAr@xhD4RaK@EixAe8AIc2lWjS0KjExdstp5mwnr4WQdtpE1FP2C7qJ8v@5DQbtLOh54mEBGgJ7s35NRl0F4N3V9qjCDdQMTBD9R7hcsceRY11UXIpKvgP "Perl 5 – Try It Online") Ungolfed: ``` # with -pl the special var $_ is initialized with the input line string while( @a = split # array @a = the numbers currently in the $_ special var and $i++ < @a # and the $i index (counter) is less than the length of @a # in the golfed version $; is used instead of $i ){ $d = abs $a[$i] - $a[$i-1] # $d = non-zero absolute diff btw element $i and $i-1 and !/\b$d\b/ # and $d unseen before? \b is "borders" around digits and s/$/ $d/ # and if so append space and $d to $_ } # with -pl the current $_ and \n is printed ``` Run: ``` $ echo 16 21 11 2 | perl -pl program_58_bytes.pl 16 21 11 2 5 10 9 3 1 6 ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), 9 bytes ``` e⟨:ọȯ¦|⟩° ``` [Try it online!](https://tio.run/##ASYA2f9nYWlh//9l4p@oOuG7jcivwqZ84p@pwrD//1sxNiAyMSAxMSAyXQ "Gaia – Try It Online") Note that the documentation states that `ȯ` is `sign of z` when `z` is a numeric type, but it's actually `abs`... ``` e # eval input as Gaia code (push as a list) ⟨ ⟩° # until there's no change: : # dup the list ọ # take the differences ȯ¦ # take the absolute values | # and set union ``` [Answer] # perl -M5.010 -a, 79 bytes ``` @F{@F}=@F;{$d=abs($F[0]-$F[1]);$F{$d}++or$F[@F]=$d;say shift@F;@F>1&&redo}say@F ``` [Try it online!](https://tio.run/##K0gtyjH9/9/BrdrBrdbWwc26WiXFNjGpWEPFLdogVhdIGsZqWqu4AYVrtbXzi4ACDm6xtiop1sWJlQrFGZlpJUBNDm52hmpqRakp@bVAYQe3//8NzRSMDBUMDRWM/uUXlGTm5xX/1/U11TMwNPivmwgA "Perl 5 – Try It Online\"/@ODflvIZmZEOpOaR3KGTj8960fSwwUghXJ0m4db3uQggBa@Tq/Gn6nt97TIhTdB1ZUnZNXEkZrirARSAGs687Wv@VjbzeLNg2cQ/ \"Perl 5 – Try It Online") Reads in a line of input, with the integers space separated. Outputs the sequence with each number on a different line. How does it work? It gets the input in the array `@F` (due to the `-a` command line argument). In the hash `%F` it stores the numbers already in `@F` (here we use the given that all numbers in sequence are positive integers†). Then, in a loop, we find the distance between the first two elements of `@F`; if not seen before, we add it to `@F` (and `%F`). We then remove the first element of `@F` and print it. We exit the loop if only one element is left, which is printed just before exiting the program. †The sequence can never contain a zero, as that requires two subsequent elements to be the same, but that is not allowed. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` W⁻Eθ↔⁻κ∧λ§θ⊖λθFι⊞θκIθ ``` [Try it online!](https://tio.run/##LYo9C8IwFEV3f8UbXyAO6dClk@jiUOheOsT0SUJj0uZD@@9jKl64XDj3KC2D8tKW8tHGEmBvXI7YyxU3DpdH9DYn@tOlEjejrZPubqb9cG6kAr3IJaoP@4XDxhg8fQA0DIYc9SEurDsNwbiEVxkTVqUrZRxFy6ERHERtM03l/LZf "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` W⁻Eθ↔⁻κ∧λ§θ⊖λθ ``` Generate the absolute differences between adjacent elements of the input and filter out those appearing in the input. ``` Fι⊞θκ ``` While there were any new values, push them to the input and repeat. ``` Iθ ``` Output the result. [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage/wiki), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) ``` ;IAQƲÐL ``` -1 byte thanks to *@JonathanAllan*. [Try it online.](https://tio.run/##y0rNyan8/9/a0zHw2KbDE3z@//8fbWimY2SoY2ioYxQLAA) **Explanation:** ``` # Full program taking a single list argument ÐL # Repeat until the result no longer changes, Ʋ # using the previous four links as monads: I # Get the forward differences of the current list A # Take their absolute values ; # Merge it to the current list Q # And uniquify it # (after which it is output implicitly as result) ``` [Answer] # [K (Kona)](https://github.com/kevinlawler/kona), 14 bytes ``` {?x,_abs-':x}/ ``` [Try it online!](https://tio.run/##y9bNzs9L/P8/zaravkInPjGpWFfdqqJW/3@agqGZgpGhgqGhgtF/AA "K (Kona) – Try It Online") Similar to J and APL answers. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` u{+GaM.:G2 ``` [Try it online!](https://tio.run/##K6gsyfj/v7Ra2z3RV8/K3ej//2hDMx0FI0MdBUMgNooFAA "Pyth – Try It Online") ``` u{+GaM.:G2 u Apply inner function until a repeat is found, current value G, starting with input .:G2 Find all sublists of length 2 aM Absolute difference between each pair +G Append to G { Deduplicate Implicit print ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), ~~10~~ 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` £=âUäa ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=oz3iVeRh&input=WzE2IDIxIDExIDJd) ``` £=âUäa :Implicit input of array U £ :Map = :Reassign to U, for the next iteration â :Setwise union of U and Uä :Consecutive pairs of U a : Reduced by absolute difference ``` [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 45 bytes ``` {|$_,{|keys abs([-] @_[++$,$++])∖@_}...^!*} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/ukYlXqe6Jju1slghMalYI1o3VsEhPlpbW0VHRVs7VvNRxzSH@Fo9Pb04Ra3a/8WJlQppGtGGZjoKRoY6CoZAbBSraf0fAA "Perl 6 – Try It Online") ### Explanation ``` { } # Anonymous codeblock ... # Generating a sequence |$_, # Starting with the input { } # Where we add to the sequence abs([-] ) # The absolute difference @_[++$,$++] # Of the next pair of elements |keys ∖@_ # Set subtracting the sequence ...!* # Continue until we run out of pairs ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~57~~ ~~51~~ 46 bytes *-11 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203)!* ``` #//.a_:>Keys@Counts@Join[a,Abs@Differences@a]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@19ZX18vMd7Kzju1stjBOb80r6TYwSs/My86UccxqdjBJTMtLbUoNS85tdghMVbtf0BRZl5JdFp0taGZjoKRoY6CIRAb1cbGWv8HAA "Wolfram Language (Mathematica) – Try It Online") Pure function. Takes a list as input and returns another list as output. It just repeatedly appends the absolute differences to the end of the list and removes duplicates, until the list no longer changes. [Answer] # JavaScript (ES6), 63 bytes ``` f=(a,i=0)=>(v=a[i]-a[++i])?f([...new Set(a).add(v>0?v:-v)],i):a ``` [Try it online!](https://tio.run/##DcuxDoMgEADQX2G8i3ARhw4m6Ed0JAwXweYaA00118@nDm98b1Y@t698LldbLr3vAdhKGDEsoIGjJMdxGCThukMkolp@5lkuYCTOGXQZV52dYrKCM/et1bMdhY72gjv4hzWTt8bfpoTY/w "JavaScript (Node.js) – Try It Online") [Answer] # [Io](http://iolanguage.org/), 59 bytes Port of the Python 2 answer. ``` method(x,a :=0;x foreach(i,x=x push((i-a)abs)unique;a=i);x) ``` [Try it online!](https://tio.run/##DcexDoQgDADQX@nYJpiIww1H@JNbqkJoouAJJP17dHjDkzIifD38xhlaKjuq4fezU4jlDrwlFKNe4eo1IcrExGulnuXfg2Mv5JRGxENqQ/sxsFgD9rUQwXVLbkceDw "Io – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~84~~ ~~68~~ 66 bytes *Edit: Saved ~~16~~ 18 bytes thanks to @Neil !! This answer is now mildly competitive :P* ``` \d+ * ^ # {`#( _+)(_*)(\1(_*).*) $1$2#$3 $2$4 )D` _+ ^ |# _+ $.& ``` [Try it online!](https://tio.run/##FYpBCsIwFAX37xQP8itJCoX3U3sCoZcobQRduHEh7vTuMa5mGOZ1fz@eV7UhrrVttxEZOwLxqSHyGFM8coqb/phygsk8WKG5zUiX2hfs/Aagi02n1rTQRYkOnSlnQU@dMwqXHw "Retina – Try It Online") Not the shortest answer to this question, but it was fun to golf anyway :) **Explanation** ``` \d+ * ``` Convert each input number to unary (using `_`'s) ``` ^ # ``` Insert a `#` at the start of the input ``` {` )` ``` Run the following 2 stages in a loop until the input stops changing: ``` #( _+)(_*)(\1(_*).*) $1$2#$3 $2$4 ``` Take the two numbers to the right of the `#` and remove the maximal number of `_`'s from each. This results in the absolute difference between the two numbers. Append this result to the end of the list. ``` D` _+ ``` Deduplicate. If the number that was just added matches a number already in the list, remove it. ``` ^ |# _+ $.& ``` Once the loop breaks, remove the `#` and leading space, and convert back to decimal [Answer] # [Java (JDK)](http://jdk.java.net/), 90 bytes ``` l->{for(int i=0,v;i+1<l.size();)if(!l.contains(v=Math.abs(l.get(i++)-l.get(i))))l.add(v);} ``` [Try it online!](https://tio.run/##ZU9Na8MwDL33V2g3e0nM0sMu@YCx02A99Th2cBMnVebYwVYyupLfnjlZYYwJhN7TE@@hTk4y6eqPBfvBOoIucDESanGf7f7tmtFUhNasYqWl93CQaOC6AxjGk8YKPEkKY7JYQx80diSHpn17B@laz7dTgGdr/Ngrl7@ip/zFkGqVK0tooFh0Ul4b6xgaAiwe4inDKM218PilGM84NuxOi8oaCvaeTcVB0lnIk2datIoYRhFPbpCH0kLWNZt4Ni/ZFv4nE3RgUIBRn/DknLxsask27IX0K2fpYwz7NIY09J7zH59GyKpSA7HV4rY7XjypXtiRxBD@Jm1@1Xk3L98 "Java (JDK) – Try It Online") [Answer] # [PHP](https://php.net/), ~~96~~ 78 bytes ``` for($a=$argv;$n=$a[++$i];print"$n ")in_array($v=abs($n-$a[$i+1]),$a)?:$a[]=$v; ``` [Try it online!](https://tio.run/##DYqxCsMwDAV/JYQ32DgdlKFDHJMPKaaoQ1svilGCIV@veDnu4Oq/2rrVzu@uDpzA@msR0uUVAkqOVYucI2QYfZE3q/Ll0BJ/Dgd59A0lUPYT2G9Lz5zQopnR02YyIptv "PHP – Try It Online") EDIT: 18 bytes saved with the help of Domenico Modica, thanks! [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 50 bytes ``` #//.l:_[___,b_,a_,___]:>l<>d/;FreeQ[l,d=Abs[b-a]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1lfXy/HKj46Pj5eJyleJzFeB8iKtbLLsbFL0bd2K0pNDYzO0UmxdUwqjk7STYyNVfsfUJSZVxKd5qAcq1YXnJyYV1fNVW1opmNkqGNoqGNUy1X7HwA "Wolfram Language (Mathematica) – Try It Online") Takes a sequence with any head. If the sequence is already complete, returns it unchanged. Otherwise, returns the completed sequence in a `StringJoin`. `<>` ([`StringJoin`](https://reference.wolfram.com/language/ref/StringJoin.html)) is short, flattens `List`s, does not operate on integer (non-string) arguments, and is `Flat`. It's also not `Orderless`, so can store ordered data. ``` _[ ] (* match a nonatomic expression with any head, *) l: (* and name it l. it contains: *) b_,a_, (* two adjacent numbers, b,a, *) ___, ___ (* as close to the front as possible, *) /; (* subject to the condition that *) FreeQ[l,d=Abs[b-a] (* |b-a| is not in l. *) #//. :>l<>d (* while the condition holds, append |b-a|. *) ``` [Answer] # APL(NARS), 22 chars, 44 bytes ``` {⍬≡k←∪⍵∼⍨∣2-/⍵:⍵⋄∇⍵,k} ``` test: ``` f←{⍬≡k←∪⍵∼⍨∣2-/⍵:⍵⋄∇⍵,k} f 16 21 11 2 16 21 11 2 5 10 9 3 1 6 f 2 3 4 5 2 3 4 5 1 ``` [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 47 bytes ``` [ [ dup differences vabs ∪ ] to-fixed-point ] ``` [Try it online!](https://tio.run/##LYuxDcIwFAV7pngLJJJTUMAAiIYGUUUpHPtbfJHYlv0TgRA9szAWixgFKE9357SRkMrpuD/sNrhQ8jRg1HKus2jhLGzyj2dayj9Mnk2wBBPGnr3@iphI5BYTe8F2tbpDrdEoKIUGj9KihZ0iLDtHibyhjFn3Ge/nCx0kVI6vZKsYlr8rRg8D6vIB "Factor – Try It Online") ## Explanation * `[ ... ] to-fixed-point` Do `[ ... ]` to the input until it stops changing. ``` ! { 16 21 11 2 } dup ! { 16 21 11 2 } { 16 21 11 2 } differences ! { 16 21 11 2 } { 5 -10 -9 } vabs ! { 16 21 11 2 } { 5 10 9 } ∪ ! { 16 21 11 2 5 10 9 } (set union) ! (etc...) ``` ]
[Question] [ First, let's talk about [Beatty sequences](https://en.wikipedia.org/wiki/Beatty_sequence). Given a positive irrational number ***r***, we can construct an infinite sequence by multiplying the positive integers to ***r*** in order and taking the floor of each resulting calculation. For example, [![Beatty sequence of r](https://i.stack.imgur.com/skq6L.png)](https://i.stack.imgur.com/skq6L.png) If ***r*** > 1, we have a special condition. We can form another irrational number ***s*** as ***s*** = ***r*** / (***r*** - 1). This can then generate its own Beatty sequence, ***B***s. The neat trick is that ***B***r and ***B***s are *complementary*, meaning that every positive integer is in exactly one of the two sequences. If we set ***r*** = ϕ, the golden ratio, then we get ***s*** = ***r*** + 1, and two special sequences. The *lower Wythoff sequence* for ***r***: ``` 1, 3, 4, 6, 8, 9, 11, 12, 14, 16, 17, 19, 21, 22, 24, 25, 27, 29, ... ``` and the *upper Wythoff sequence* for ***s***: ``` 2, 5, 7, 10, 13, 15, 18, 20, 23, 26, 28, 31, 34, 36, 39, 41, 44, 47, ... ``` These are sequences [A000201](https://oeis.org/A000201) and [A001950](https://oeis.org/A001950) on OEIS, respectively. ### The Challenge Given a positive input integer `1 <= n <= 1000`, output one of two distinct values indicating whether the input is in the *lower Wythoff sequence* or the *upper* sequence. The output values could be `-1` and `1`, `true` and `false`, `upper` and `lower`, etc. Although your submitted algorithm must theoretically work for all inputs, in practice it only has to work with the first 1000 input numbers. ## I/O and Rules * The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * The input and output can be assumed to fit in your language's native number type. * 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. [Answer] ## JavaScript (ES6), ~~50~~ 35 bytes ``` f=(n,s="1",t=0)=>s[n-1]||f(n,s+t,s) ``` ``` <input type=number min=1 oninput=o.textContent=this.value&amp;&amp;f(this.value)><pre id=o> ``` Outputs `1` for lower and `0` for upper. Explanation: Partial lists of boolean values can be constructed using a Fibonacci-like identity: given two lists, starting with `1` and `10`, each subsequent list is the concatenation of the previous two, resulting in `101`, `10110`, `10110101` etc. In this case it's slightly golfier to have a fake 0th entry of `0` and use that to construct the second element of the list. [Answer] # [Python](https://docs.python.org/2/), 25 bytes ``` lambda n:-n*2%(5**.5+1)<2 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPSjdPy0hVw1RLS89U21DTxuh/QVFmXolCWmZOSWqRRppOUWJeeqqGoY6hgaGm5v//AA "Python 2 – Try It Online") Uses the very simple condition: > > `n` is in the lower Wythoff sequence exactly if `-n%phi<1`. > > > Note that the modulo result is positive even though `-n` is negative, matching how Python does modulo. > > **Proof:** Let `a = -n%phi`, which lies in the range `0 <= a < phi`. We can split > `-n` modulo `phi` as `-n = -k*phi + a` for some positive integer `k`. > Rearrange that to `n+a = k*phi`. > > > If `a<1`, then `n = floor(n+a) = floor(k*phi)`, and so is in the lower > Wythoff sequence. > > > Otherwise, we have `1 <= a < phi` so > > > > ``` > n+1 = floor(n+a) = floor(k*phi) > n > n+a-phi = k*phi - phi = (k-1)*phi > > ``` > > so `n` falls in the gap between `floor((k-1)*phi)` and `floor(k*phi)` > and is missed by the lower Wythoff sequence. > > > This corresponds to this code: ``` lambda n:-n%(5**.5/2+.5)<1 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPSjdPVcNUS0vPVN9IW89U08bwf0FRZl6JQlpmTklqkUaaTlFiXnqqhqGOoYGhpub//wA "Python 2 – Try It Online") We save a byte by doubling to `-(n*2)%(phi*2)<2`. [Answer] # [Haskell](https://www.haskell.org/), 26 bytes ``` (l!!) l=0:do x<-l;[1-x..1] ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyNHUVGTK8fWwColX6HCRjfHOtpQt0JPzzD2f5FttCGQYWAQy5WbmJlnm5tY4KtQUJSZV6KiEB1dUQNUXaSTplBha5scW5NsoxttqGMQG/v/X3JaTmJ68X/d5IICAA "Haskell – Try It Online") No floats, unlimited precision. Thanks for H.PWiz for two bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` L5t>;*óså ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fx7TEzlrr8Obiw0v//zc0NQcA "05AB1E – Try It Online") --- 0 means upper, 1 means lower. **Try the first 100: [Try it online!](https://tio.run/##MzBNTDJM/W9oYODup3R4v62Svd9/H9MSO2utw5v9Di/9b1v7HwA "05AB1E – Try It Online")** --- ``` CODE | COMMAND # Stack (Input = 4) ===========+===================#======================= L | [1..a] # [1,2,3,4] 5t>; | (sqrt(5) + 1)/2 # [phi, [1,2,3,4]] * | [1..a]*phi # [[1.6,3.2,4.8,6.4]] ó | floor([1..a]*phi) # [[1,3,4,6]] så | n in list? # [[1]] ``` --- **Raw Command Dump:** ``` ---------------------------------- Depth: 0 Stack: [] Current command: L ---------------------------------- Depth: 0 Stack: [[1, 2, 3, 4]] Current command: 5 ---------------------------------- Depth: 0 Stack: [[1, 2, 3, 4], '5'] Current command: t ---------------------------------- Depth: 0 Stack: [[1, 2, 3, 4], 2.23606797749979] Current command: > ---------------------------------- Depth: 0 Stack: [[1, 2, 3, 4], 3.23606797749979] Current command: ; ---------------------------------- Depth: 0 Stack: [[1, 2, 3, 4], 1.618033988749895] Current command: * ---------------------------------- Depth: 0 Stack: [[1.618033988749895, 3.23606797749979, 4.854101966249685, 6.47213595499958]] Current command: ó ---------------------------------- Depth: 0 Stack: [[1, 3, 4, 6]] Current command: s ---------------------------------- Depth: 0 Stack: [[1, 3, 4, 6], '4'] Current command: å 1 stack > [1] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` N%ØpỊ ``` [Try it online!](https://tio.run/##y0rNyan8/99P9fCMgoe7u/4bGhgEHW5/1LTmPwA "Jelly – Try It Online") Saved 1 byte thanks to [xnor's Python golf](https://codegolf.stackexchange.com/a/166893/59487). --- ### [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ×€ØpḞċ ``` [Try it online!](https://tio.run/##ARkA5v9qZWxsef//w5figqzDmHDhuJ7Ei////zM2 "Jelly – Try It Online") Returns **1** for lower and **0** for upper. ``` ×€ØpḞċ – Full Program / Monadic Link. Argument: N. ×€ – Multiply each integer in (0, N] by... Øp – Phi. Ḟ – Floor each of them. ċ – And count the occurrences of N in that list. ``` Checking \$(0,\:N]\cap \mathbb{Z}\$ is most definitely enough because \$\varphi > 1\$ and \$N > 0\$ and therefore \$0 < N < N\varphi\$. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 78 bytes ``` ([{}]()){<>{}((([()]))){{<>({}())}{}(([({})]({}{})))}<>([{}]{}<>)}<>({}()){{}} ``` [Try it online!](https://tio.run/##HYsxDoBACAS/s1tYWBgb40cIxVmYGI2FLeHtuHcN7Azs8bXrnc6n3VWwSAcZ2x4JwECnUAwJMrs2ZbqGlpRuvRYKA8ZjRGbVvKw/ "Brain-Flak – Try It Online") Outputs nothing for lower and `0` for upper. Changing to a more sensible output scheme would cost 6 bytes. [Answer] # [Python 2](https://docs.python.org/2/), ~~39~~ ~~33~~ 32 bytes -6 bytes thanks to Mr. Xcoder -1 byte thanks to Zacharý ``` lambda n,r=.5+5**.5/2:-~n//r<n/r ``` [Try it online!](https://tio.run/##TY7BDoIwEETvfsXeEFypXVoRIl@iHDBKNIHSNBjjxV@vQ@LBwxzey3am/j3fJyexb85x6MbLtSPHocntxmZZbpXU249TKhydCtGHh5spGabXLdQJj51f93zSTAWTYdozHZgqJg2lBYHUsLpE4AVe4AVeLAIvVZuufsVP7/@LcYmj5e0OwYYGakwIWMCCbgEXyxfQWYAL7BiwAZuyTSl@AQ "Python 2 – Try It Online") Returns `False` for lower and `True` for upper [Answer] # [Julia 0.6](http://julialang.org/), 16 bytes ``` n->n÷φ<-~n÷φ ``` [Try it online!](https://tio.run/##yyrNyUw0@19u@z9P1y7v8PbzbTa6dWD6f25igQZQsKAoM68kJ09DSSXPSkFFo1wjT1NTSVNHwdDKyEDz/39jMwA "Julia 0.6 – Try It Online") While playing around with the numbers, I came across this property: floor(n/φ) == floor((n+1)/φ) if n is in the upper Wythoff sequence, and floor(n/φ) < floor((n+1)/φ) if n is in the lower Wythoff sequence. I haven't figured out *how* this property comes about, but it gives the correct results at least upto n = 100000 (and probably beyond). --- Old answer: # [Julia 0.6](http://julialang.org/), 31 bytes ``` n->n∈[floor(i*φ)for i∈1:n] ``` [Try it online!](https://tio.run/##yyrNyUw0@19u@z9P1y7vUUdHdFpOfn6RRqbW@TbNtPwihUygmKFVXuz/3MQCDaCagqLMvJKcPA0llTwrBRWNco08TU0lTR0FQysjA83//43NAA "Julia 0.6 – Try It Online") Returns `true` for lower and `false` for upper Wythoff sequence. [Answer] # [Arn](https://github.com/ZippyMagician/Arn), [9 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn) ``` 2>6Yx!¦ü# ``` [Try it!](https://zippymagician.github.io/Arn?code=cGhpLTE8JXBoaQ==&input=Mjk=) # Explained Unpacked: `phi-1<%phi` I found another way of calculating this: > > ![n % phi > phi + 1](https://latex.codecogs.com/png.latex?%5Clarge&space;n%5Cmod&space;%5CPhi&space;%3E&space;%5CPhi&space;-&space;1) > > is true if `n` is in the Lower Wythoff Sequence > > > This example merely uses this formula (it was shorter than `1>((n_)%phi`). And here is how it works: ``` phi Builtin for the Golden Ratio - Minus 1 Literal one < Is less than _ Variable initialized to STDIN, implied % Modulo phi ``` Returns true if lower, false if upper [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes ``` #~Ceiling~GoldenRatio<#+1& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8V@5zjk1MyczL73OPT8nJTUvCCiVb6Osbaj2X9OaK6AoM6/Ewb0ov7TAqTI6KDEvPTXa0MAgVkchLfY/AA "Wolfram Language (Mathematica) – Try It Online") An integer `n` is in the lower Wythoff Sequence iff `ceil(n/phi) - 1/phi < n/phi`. ## Proof that `ceil(n/phi) - 1/phi < n/phi` is... Sufficient: 1. Let `ceil(n/phi) - 1/phi < n/phi`. 2. Then, `ceil(n/phi) * phi < n + 1`. 3. Note `n == n/phi * phi <= ceil(n/phi) * phi`. 4. Hence, `n <= ceil(n/phi) * phi < n + 1`. 5. Since `n` and `ceil(n/phi)` are integers, we invoke the definition of floor and state `floor(ceil(n/phi) * phi) == n`, and `n` is in the lower Wythoff sequence. Necessary; proof by contrapositive: 1. Let `ceil(n/phi) - 1/phi >= n/phi`. 2. Then, `ceil(n/phi) * phi >= n + 1`. 3. Note `n + phi > (n/phi + 1) * phi > ceil(n/phi) * phi` 4. Hence `n > (ceil(n/phi) - 1) * phi`. 5. Since `(ceil(n/phi) - 1) * phi < n < n + 1 <= ceil(n/phi) * phi`, `n` is not in the lower Wythoff sequence. [Answer] ## [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~21~~ ~~19~~ 13 bytes ``` ⊢∊∘⌊⍳×1+∘÷⍣=≢ ``` -6 bytes from Adám after conversion to tacit function. [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HXokcdXY86Zjzq6XrUu/nwdENtIOfw9ke9i20fdS76n/aobcKj3r5HXc2Petc86t1yaL3xo7aJj/qmBgc5A8kQD8/g/2kKhlxpCkZAbAzEJiC2JQA "APL (Dyalog Extended) – Try It Online") ### Old answer: ``` {⍵∊⌊((1+∘÷⍣=1)×⍳⍵)} ``` Uses the same approach as [Magic Octopus Urn's answer.](https://codegolf.stackexchange.com/a/166883/80214) -2 bytes from ZippyMagician. Prints 1 for upper and 0 for lower sequence. ## Explanation ``` {⍵∊⌊((2÷¯1+5*÷2)×⍳⍵)} ⍳⍵ Generate list of 1 to n (2÷¯1+5*÷2)× Multiply it by the golden ratio ⌊ Floor the entire list ⍵∊ is n in the list? ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR79ZHHV2Pero0NAy1H3XMOLz9Ue9iW0PNw9Mf9W4GSmrW/k971DbhUW/fo67mR71rHvVuObTe@FHbxEd9U4ODnIFkiIdn8P80BUOuNAUjIDYGYhMQ2xIA "APL (Dyalog Extended) – Try It Online") [Answer] # [Pyth](https://pyth.readthedocs.io), 8 bytes ``` /sM*.n3S ``` [Try it here!](https://pyth.herokuapp.com/?code=%2FsM%2a.n3S&test_suite=1&test_suite_input=1%0A3%0A4%0A6%0A8%0A9%0A11%0A2%0A5%0A7%0A10%0A13%0A15&debug=0) Returns **1** for lower and **0** for upper. [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 bytes Returns **true** for lower and **false** for upper. ``` õ_*MQ fÃøU ``` [Try it online!](https://tio.run/##HY0xCkIxEAX7nGJrWfnuJvr9h7BQsBIRCy1EMXwUD@CZBPscLE4MvGImZHI55ket5XOYrNZyLu/y3dY6vW1C2AVTiSpJZaGyVBlUDGXOkIa1nuEd73jH@5zhfZB2uk6u99dpDFxz0x7MGGEDja7DDjtBh2P7l1CEI/EEJzj1/9ozZ2r7Hw "Japt – Try It Online") ## Explanation: ``` õ_*MQ fÃøU // Implicit U = Input õ // Range [1...U] _ // Loop through the range, at each element: *MQ // Multiply by the Golden ratio f // Floor à // End Loop øU // Return true if U is found in the collection ``` [Answer] # Java 10, ~~77~~ ~~53~~ 52 bytes ``` n->{var r=Math.sqrt(5)/2+.5;return(int)(-~n/r)<n/r;} ``` Port of [@Rod's Python 2 answer](https://codegolf.stackexchange.com/a/166887/52210). -1 byte thanks to *@Zacharý*. [Try it online.](https://tio.run/##LY7BbsJADETvfIXFKatVFqjEpUv6B3DhWDiYsLRLg5d6nUgVSn89OMBlLHs043fGDsvz8WeoG8wZ1hjpNgGIJIFPWAfYjCvAIaUmIEFdqAVkvF77iUoWlFjDBggqGKj8uHXIwNUa5dvlX5ZiaWZv1i09B2mZxrwpyn@asVmp@H7wY8@1PTTa86rrUjzCRWGKrXCkr889oHmSnBI/GGK18BBX1WI@12mtebgA278s4eJSK@6qUWn0pZ2@72RqySm@ebH3wx0) --- **Old ~~77~~ 76 bytes answer:** ``` n->{for(int i=0;i++<n;)if(n==(int)((Math.sqrt(5)+1)/2*i))return 1;return 0;} ``` -1 byte thanks to *@ovs*' for something [I recommended myself last week.. xD](https://codegolf.stackexchange.com/questions/166415/find-the-10-adic-cube-root-of-3/166422#comment402310_166422) Returns `1` for lower; `0` for upper. [Try it online.](https://tio.run/##RU/LjsIwDLzzFRanmIhui8SFkP0DuHAEDqG0u2aLyyYuEkL99pKWSlz8GNsz44u7u/nl/NfllQsBNo74OQEglsKXLi9g27cDALnqI6OJSDuJIYgTymELDBY6nn8/y9oPS2RTQ1qv2SCViq3tUVRq4@Q3Cf9e1BJ1hl@LGSH6QhrPkJmxSE3bmZ7/1pyqyD/K3Gs6wzUaVDvxxD/7Izh8u/vIZgZobbM0jVlrHKYAu0eQ4prUjSS3eCoVK9LT1UGmmpP4Fo4/td0L) **Explanation:** ``` n->{ // Method with integer as both parameter and return-type for(int i=0;++i<=n;) // Loop `i` in the range [1, `n`] if(n==(int)((Math.sqrt(5)+1)/2*i)) // If `n` is equal to `floor(Phi * i)`: return 1; // Return 1 return 0;} // Return 0 if we haven't returned inside the loop already ``` `i*Phi` is calculated by taking `(sqrt(5)+1)/2 * i`, and we then floor it by casting it to an integer to truncate the decimal. [Answer] # [Haskell](https://www.haskell.org/), ~~153~~ ~~139~~ ~~126~~ 79 bytes *Unlimited Precision!* ``` l=length f a c|n<-2*l a-c,n<0||l a<a!!n=c:a|1>0=a g x=x==(foldl f[][1..x+1])!!0 ``` [Try it online!](https://tio.run/##Fcm9DsIgEADgvU9xJA7@tQHjZDhfpGG4IFDi9TSVgYF3R92@5Fvo8wzMvTNykFSWIQKBb2LHy5GBRn8Wq1v70ZJSgv5Gzdw10pCgYkXcxxc/GOLsZjNN9WTcQSndV8qC7y1L2cXMJWyQ/n/Vrn8B "Haskell – Try It Online") ## Explanation Instead of using an approximation of the golden ratio to calculate the result meaning they are prone to errors as the size of the input rises. This answer does not. Instead it uses the formula provided on the OEIS that `a` is the unique sequence such that ``` ∀n . b(n) = a(a(n))+1 ``` where `b` is the ordered compliment. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` ≥ℕ;φ×⌋₁? ``` [Try it online!](https://tio.run/##Dcq9CoJgFMbxWzm880E89k2Dl9EQDSWvKYiaH4iIQxai1NASXUHU2NLS2gV0Db43Ymd44A/PbxOtLSf3gq3RF5kANwbXh8SRIDKzUPVLVQfVPIQXZDISmmqeIg1DzpLxIk@cwLYhlrtU@pbURPdpy@596VV7V8fr/Fd/b@p8UtXe7PslIRgIA4QhwghhjDBBmCLMEEjn8U8MiAUxITbEiFgRM2Jn6Ks/ "Brachylog – Try It Online") The predicate succeeds if the input is in the lower Wythoff sequence and fails if it is in the upper Wythoff sequence. ``` ℕ There exists a whole number ≥ less than or equal to the input such that ;φ× multiplied by phi ⌋₁ and rounded down ? it is the input. ``` If failure to terminate is a valid output method, the first byte can be omitted. [Answer] # [cQuents](https://github.com/stestoltz/cQuents), 5 bytes ``` ?F$`g ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/395NJSH9/38jAA "cQuents – Try It Online") ## Explanation ``` ? output true if in sequence, false if not in sequence each term in the sequence equals: F floor ( $ index * `g golden ratio ) ) implicit ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` t:17L*km ``` [**Try it online!**](https://tio.run/##y00syfn/v8TK0NxHKzv3/38jSwA "MATL – Try It Online") ### Explanation ``` t % Implicit input. Duplicate : % Range 17L % Push golden ratio (as a float) * % Multiply, element-wise k % Round down, element-wise m % Ismember. Implicit output ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 20 bytes **Solution:** ``` x in_(.5*1+%5)*1+!x: ``` [Try it online!](https://tio.run/##y9bNz/7/v0IhMy9eQ89Uy1Bb1VQTSCpWWBlZ/v8PAA "K (oK) – Try It Online") **Explanation:** ``` x in_(.5*1+%5)*1+!x: / the solution x: / save input as x ! / generate range 0..x 1+ / add 1 * / multiply by ( ) / do this together %5 / square-root of 5 1+ / add 1 .5* / multiply by .5 _ / floor x in / is input in this list? ``` [Answer] # TI-BASIC (TI-84), 18 bytes ``` max(Ans=iPart((√(5)+1)/2randIntNoRep(1,Ans ``` Input is in `Ans`. Output is in `Ans` and is automatically printed. Prints `1` if input is in the lower sequence or `0` if it's in the upper sequence. Coincidentally, this program will only run for \$0<N<1000\$ . **Example:** ``` 27 27 prgmCDGFA 1 44 44 prgmCDGFA 0 ``` **Explanation:** ``` max(Ans=iPart((√(5)+1)/2randIntNoRep(1,Ans ;full program, example input: 5 randIntNoRep(1,Ans ;generate a list of random integers in [1,Ans] ; {1, 3, 2, 5, 4} (√(5)+1)/2 ;calculate phi and then multiply the resulting ;list by phi ; {1.618 4.8541 3.2361 8.0902 6.4721} iPart( ;truncate ; {1 4 3 8 6} Ans= ;compare the input to each element in the list ;and generate a list based off of the results ; {0 0 0 0 0} max( ;get the maximum element in the list and ;implicitly print it ``` --- **Note:** TI-BASIC is a tokenized language. Character count does *not* equal byte count. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 5 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ╒φ*i╧ ``` [Try it online.](https://tio.run/##y00syUjPz0n7///R1Enn27QyH01d/v@/IZcxlwmXGZcFlyWXoSGXoRGXoQmXoYEBlxGXKZc5kMVlaMxlaAqUMAYA) **Explanation:** ``` ╒ # Push a list in the range [1, (implicit) input-integer] φ* # Multiply each value by the golden ratio 1.618033988749895 i # Floor each by casting it to an integer ╧ # Check if the (implicit) input-integer is in this list # (after which the entire stack joined together is output implicitly as result) ``` ]
[Question] [ # Problem Starting from `n=2` dice: * Roll `n` dice, with each number 1 to 6 equally likely on each die. * Check if their sum equals the most probable sum for `n` dice, that is `3.5*n`. + If they're equal, terminate. + Otherwise, print `n`, and repeat from the start with `n+2` dice Your code doesn't have to do this procedure exactly, but should give random output probabilistically equivalent to it, based on [our definition of randomness](https://codegolf.meta.stackexchange.com/a/1325/20260). Your program should output all of the numbers on their own line; for example, if the program got up to 8 dice and rolled the most probable number with 8 dice, the output would be: ``` 2 4 6 ``` # Example Run On 2 dice, `7` is the most probable sum. Let's say the numbers rolled were `2` and `3`. Then, you would print `2`. On 4 dice, `14` is the most probable sum. Let's say the numbers rolled were `3`, `4`, `2`, and `5`. Then, the sum is `14`, so the program would terminate here. The final output in this case is `"2"`. # Rules * [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest solution in bytes wins * [Standard Loopholes Apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * The [meta definition of randomness](https://codegolf.meta.stackexchange.com/a/1325/42649) applies * You may use functions as well as programs [Answer] # [Python 2](https://docs.python.org/2/), 70 bytes ``` from random import* n=2 while eval("+randrange(6)-2.5"*n):print n;n+=2 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VoceXZGnGVZ2TmpCqkliXmaChpg@SBOD1Vw0xT10jPVEkrT9OqoCgzr0QhzzpP2xZozte8fN3kxOSMVAA "Python 2 – Try It Online") The trick is to compute the sum by `eval`ing a string the looks like ``` '+randrange(6)-2.5+randrange(6)-2.5' ``` with `n` copies of the expression concatenated. The `randrange(6)` outputs a random number from `[0,1,2,3,4,5]`, which is shifted down by `2.5` to have average of `0`. When the sum if `0`, the `while` condition fails and the loop terminates. An alternative using `map` was 4 bytes longer: ``` from random import* n=2 while sum(map(randrange,[6]*n))-2.5*n:print n;n+=2 ``` I've found a bunch of equal-length expressions for a die shifted to mean zero, but none shorter ``` randrange(6)-2.5 randint(0,5)-2.5 randrange(6)*2-5 uniform(-3,3)//1 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 13 bytes ``` `@E6y&Yrs@7*- ``` [Try it online!](https://tio.run/##y00syfn/P8HB1axSLbKo2MFcS/f//695@brJickZqQA "MATL – Try It Online") ### Explanation ``` ` % Do...while top of the stack is truthy @E % Push 2*k, where k is the iteration index starting at 1 6 % Push 6 y % Duplicate 2*k onto the top of the stack &Yr % Array of 2*k integers distributed uniformly in {1, 2, ..., 6} s % Sum @7* % Push 7*k - % Subtract % End (implicit). If the top of the stack is non-zero, the loop % proceeds with the next iteration. Else the loop is exited. % Display stack (implicit) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -5 bytes with help from Leaky Nun (moving from count up to recursion) ``` ‘‘6ṗX_3.L⁶S?Ṅß ``` A full program printing the results separated by newlines (an extra space and newline are also printed, and the program errors at the end). **[Try it online!](https://tio.run/##y0rNyan8//9RwwwgMnu4c3pEvLGez6PGbcH2D3e2HJ7////XvHzd5MTkjFQA "Jelly – Try It Online")** - any time 6 dice are surpassed TIO kills this due to memory usage, but it works in principle - it also takes ~40s to do so. A more friendly 15 byte version that does not take so long or require so much memory is available **[here](https://tio.run/##y0rNyan8//9RwwwgMnu4qzviUdOaeGM9n0eN24LtH@5sOTz///@vefm6yYnJGakA "Jelly – Try It Online")**. ### How? Recursively rolls 2 more dice until the sum of the faces each reduced by 3.5 is zero, printing the number of dice as it goes, when the zero is reached it attempts to use a space character causing a type error. ``` ‘‘6ṗX_3.L⁶S?Ṅß - Main link: no arguments (implicit left=zero) ‘ - increment (initial zero or the previous result) ‘ - increment (= # of dice to roll, n) 6 - literal 6 ṗ - Cartesian power - all possible rolls of n 6-sided dice with faces 1-6 X - pick one of them 3. - literal 3.5 _ - subtract 3.5 from each of the roll results ? - if: S - sum the adjusted roll results (will be 0 for most common) L - ...then: length (number of dice that were rolled) ⁶ - ...else: literal ' ' (causes error when incremented in next step) Ṅ - print that plus a newline ß - call this link with the same arity (as a monad with the result) ``` [Answer] # TI-BASIC, 28 bytes ``` 2→N While mean(randInt(1,6,N)-3.5 Disp N N+2→N End ``` **Explanation** * `randInt(1,6,N)` generates a list of N random numbers from 1 to 6 * `mean(randInt(1,6,N)-3.5` gets the average of the rolls shifted down by 3.5 * `While` continues until the average expression equals zero (the most probable sum) [Answer] # [R](https://www.r-project.org/), 49 bytes ``` n=2 while(sum(sample(6,n,T)-3.5)){print(n) n=n+2} ``` `sample(6,n,T)` generates `n` (pseudo)random samples from the range `1:6` with replacement. Subtracting 3.5 from each element yields a result whose `sum` is 0 (falsey) if and only if it's the most common value. [Try it online!](https://tio.run/##K/r/P8/WiKs8IzMnVaO4NFejODG3AMg008nTCdHUNdYz1dSsLijKzCvRyNPkyrPN0zaq/f8fAA "R – Try It Online") Skips the odd dice rolls. [Answer] # Java 8, ~~123~~ ~~149~~ ~~113~~ 108 bytes ``` ()->{for(int n=0,s=1,i;s!=n*7;){for(i=s=++n*2;i-->0;s+=Math.random()*6);if(s!=n*7)System.out.println(n*2);}} ``` Or **107 bytes** if we use [an `Object null` as unused parameter](https://codegolf.meta.stackexchange.com/questions/12681/are-we-allowed-to-use-empty-input-we-wont-use-when-no-input-is-asked-regarding) instead. +26 bytes for a bug-fix, correctly pointed out by *@Jules* in the comments. -41 bytes thanks to *@OliverGrégoire*'s great thinking! **Explanation:** [Try it here.](https://tio.run/##PY6xDoIwEIZ3n@LcWrBEHXRo6hvA4mgczlK0CFdCq4kxPLYzVjEul/y5@@7/aryjcJ2huryOukHvIUdLzxmApWD6CrWB4hMB7s6WoBmXMQ2zOHzAYDUUQKBgZFzsnpXrWQSB1HLh1WphpZ8rSraSTyvlVZpSspZWiN1S@lTlGC5Zj1S6lvFkw6Wt2MTw/cMH02buFrKuj18bYhHlchhG@envbqcm9v80vnptlGf7EK/PhyMgn8wp@2sP44uc0Kgv5g0) ``` ()->{ // Method without parameter nor return-type for(int n=0, // Amount of dice s=1, // Sum i; // Index s!=n*7;){ // Loop (1) as long as the sum doesn't equal `n`*7, // because we roll the dice per two, and 3.5*2=7 for(i=s=++n*2; // Reset both the index and sum to `n`*2, // so we can use random 0-5, instead of 1-6 // and we won't have to use `+1` at `Math.random()*6` i-->0; // Inner loop (2) over the amount of dice s+=Math.random()*6 // And increase the sum with their random results ); // End of inner loop (2) if(s!=n*7) // If the sum doesn't equal `n`*7 System.out.println(n*2); // Print the amount of dice for this iteration } // End of loop (1) } // End of method ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~22~~ 20 bytes -2 Bytes thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) ``` [YF6L.RO}7Y*;ïQ#Y=ÌV ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/OtLNzEcvyL/WPFLL@vD6QOVI28M9Yf//f83L101OTM5IBQA "05AB1E – Try It Online") ### Explanation ``` [YF6L.RO}7Y*;ïQ#Y=ÌV [ # Infinite loop start YF } # Y times... (Y defaults to 2) 6L.R # Push a random number between 1 and 6 (why does this have to be so looooong ._.) O # Sum 7Y*;ï # Push 3.5 * Y as an int Q # Is it equal to 3.5 * Y? # # If so: Quit Y # Push Y = # Print without popping ÌV # Set Y to Y + 2 ``` [Answer] # R, ~~48~~ ~~44~~ 42 bytes A 5-byte improvement on [Giuseppe's answer](https://codegolf.stackexchange.com/a/126090/59052). ``` while(sum(sample(6,F<-F+2,1)-3.5))print(F) ``` This (ab)uses the fact that `F` is a variable by default assigned to `FALSE` which coerces to `0` and can then be incremented, saving us the need to initialize a counter variable. [Answer] # [PHP](https://php.net/), 75 bytes ``` for($d=2;(++$i*7/2-$r+=rand(1,6))||$i<$d;)$i%$d?:$d+=1+print"$d ".$r=$i=""; ``` [Try it online!](https://tio.run/##DcQxDoMwDAXQvceIfqWkhlYwUIlgcRaEi/ASIosx1@4ceMPLe67TnO@3wzyE@@iJoK/vp29hxLYk8V0zhFAKdILEAH1C5hFC3FE2TaeDPNwbxlB2Ltb6T0e7Luv@uwA "PHP – Try It Online") [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 41 bytes ``` 0{2+.n\.[{6rand.+5-}*]{+}*!!*.}{}while;;; ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/36DaSFsvL0YvutqsKDEvRU/bVLdWK7Zau1ZLUVFLr7a6tjwjMyfV2tr6//@vefm6yYnJGakA "GolfScript – Try It Online") [Answer] # Mathematica, 47 bytes ``` For[n=1,Tr@RandomInteger[5,2n++]!=5n,Print[2n]] ``` *-5 bytes from LLlAMnYP* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` [N·ÌD6Lã.R7;-O_#, ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/2u/Q9sM9LmY@hxfrBZlb6/rHK@v8//81L183OTE5IxUA "05AB1E – Try It Online") **Explanation** ``` [ # loop over N in 0... N·Ì # push N*2+2 D # duplicate 6L # push range [1 ... 6] ã # cartesian product (combinations of N*2+2 elements in range) .R # pick one at random 7;- # subtract 3.5 from each dice roll O_# # if sum == 0 exit loop , # otherwise print the copy of N*2+2 ``` [Answer] ## Batch, 109 bytes ``` @set/an=%1+2,s=n*5/2 @for /l %%i in (1,1,%n%)do @call set/as-=%%random%%%%%%6 @if %s% neq 0 echo %n%&%0 %n% ``` Rather annoyingly, `random` is a magic environment variable, so it only gets replaced with a random value during environment expansion, which normally happens before the for loop starts. `call` makes it happen each time through the loop, but then you need to double the `%` signs to prevent the expansion from happening before the loop. The fun starts because we want to modulo the result by 6, which requires a real `%` sign, which now has to be doubled twice. The result is six consecutive `%`s. [Answer] # JavaScript (ES2015), 75 78 bytes ``` f=(n=2)=>[...Array(n)].reduce(a=>a+Math.random()*6|0,n)==3.5*n?'':n+` `+f(n+2) ``` Outputs a string of results separated by newlines Edit: saved a byte thanks to Shaggy, added 4 bytes to start function at 2 **Explanation** ``` f=n=> [...Array(n)] // Array of size n .reduce( // Combine each item a=>a+Math.random()*6|0, // Add a random roll between 0 and 5 for each item n) // Start at n to correct rolls to between 1 and 6 ==3.5*n // Compare total to most probable roll total ? '' // If true, end : n+'\n'+f(n+2) // Otherwise, output n and continue ``` ``` f=(n=2)=>[...Array(n)].reduce(a=>a+Math.random()*6|0,n)==3.5*n?'':n+` `+f(n+2) let roll = _ => document.getElementById('rolls').innerHTML = f(); document.getElementById('roll-button').onclick = roll; roll(); ``` ``` <button id="roll-button">Roll</button> <pre id="rolls"></pre> ``` [Answer] # php - 89 Characters ``` $r=0;$n=2;while($r!=$n*3.5){$r=$i=0;while($i<$n){$r+=rand(1,6);$i++;}print $n." ";$n+=2;} ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~84~~ ~~80~~ ~~79~~ ~~77~~ ~~75~~ ~~80~~ ~~78~~ 76 bytes ``` i;f(s,j){for(;s;s?printf("%d\n",i):0)for(j=i+=2,s=i*7/2;j--;)s-=1+rand()%6;} ``` [Try it online!](https://tio.run/##LYlBCsIwEADveYUUCrs2wdqDBZfgR7yEtNENNJVsb6XP9hy1OKdhxpuH96UwBRAdcQ1zBhKS2ytzWgJU9XBPlWa8tvh70XJjOy2Wj/2po2gMoRh7brJLA2B9oa1MjhOgWtXhi@xj4WmEFpH2FuAvaivvNBvv/HP8AA "C (gcc) – Try It Online") [Answer] # Haskell ~~133~~ 132 bytes ``` import System.Random;import Control.Monad s k=do n<-replicateM k$randomRIO(1,6);if sum n==7*div k 2 then pure()else do print k;s(k+2) ``` Credit to @Laikoni for the suggestions in the comments below. [Answer] # **Octave 55 bytes** ``` n=2; while mean(randi(6,n,1))-3.5!=0 n n=n+2; end ``` Inspired by Andrewarchi's answer. If someone has any pointers to even shorten it, they are welcome. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 20 bytes ``` K2WnsmhO6K*K3.5K=+K2 ``` [Try it online!](https://tio.run/##K6gsyfj/39soPK84N8PfzFvL21jP1NtW29vo////X/PydZMTkzNSAQ "Pyth – Try It Online") [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 40 bytes ``` {[1,r|g=g+_r1,6|]~g=r*3.5|_X\g=0?r┘r=r+2 ``` Thispretty much literally does what the challenge asks for; seems the shortest way to get the distribution right. ## Explanation ``` { DO infinitely [1,r| FOR a=1, a<=r (at start, r == 2), a++ g=g+ Add to g (0 at start) _r1,6| a random number between 1 and 6 incl. ] NEXT ~g=r*3.5 IF the result of all dice rolls equals the expected value |_X THEN quit \g=0 ELSE, reset the dice total ?r┘ PRINT the number of dice used r=r+2 and add 2 dice. END IF and LOOP are courtiously provided by QBIC at EOF. ``` [Answer] # [Rexx (Regina)](http://www.rexx.org/), 78 bytes ``` x=2 do forever t=0 do x t=t+random(6) end if(t=x*3.5)then exit say x x=x+2 end ``` [Try it online!](https://tio.run/##Fcs9CoAwDEDhPafo6A@KKLrlMKWNtIMt1CDx4M6xHR98r5CIquAKPpszF3qoAOPSUsAYRh6LTT5f3dEDJQ/x7Bhl2Oa950CpGpLIcNu3DoIyro2pfilPzrpAPw "Rexx (Regina) – Try It Online") [Answer] # JavaScript (ES6) - 69 Characters ``` r=n=>n?r(n-1)+(Math.random()*6|0)-2.5:0;f=(n=2)=>r(n)?n+` `+f(n+2):"" console.log(f()) ``` **Explanation**: ``` r=n=> # Roll n dice n? # If there is a dice left to roll r(n-1) # Roll n-1 dice +(Math.random()*6|0) # Add a random number from 0 .. 5 -2.5 # Subtract 2.5 so sum of average is 0 :0 # Else total is 0 ``` and: ``` f=(n=2)=> # Start with n = 2 r(n) # Roll n dice ?n+"\n"+f(n+2) # If non-zero then concatenate n, newline and # result for n+2 dice :"" # If zero (average) terminate. ``` [Answer] # [Calc2](https://github.com/hstde/Calc2) 0.7, ~~119~~ ~~118~~ 111 bytes ``` using"runtime";for(n=2,d=0;d!=3.5*n;Console.WriteLine(n),n+=2)for(i=d=0;i++<n;)d+=Math.Int(Random().Next(1,7)); ``` ungolfed: ``` using "runtime"; var d = 0; var r = Random(); for(var n = 2; d != 3.5 * n; Console.WriteLine(n), n += 2) { d = 0; for(var i = 0; i < n; i++) d += Math.Int(r.Next(1,7)); } ``` I could do without the Math.Int() but unfortunately in 0.7 the Random().Next() functions have a bug where they all return doubles instead of ints. It has been fixed but only after this question was posted. I'm not gonna win anything, but hey, nice proof of concept. Edit: * removed unnecessary space between using and "runtime" (-1 byte) Edit2: * removed var r and create a new Random where it's needed (-4 byte) * changed i=0,d=0 to i=d=0 (-2 byte) * incremented i after check (-1 byte) [Answer] # [Ruby](https://www.ruby-lang.org/), 52 bytes ``` s=x=2;(s=0;p x.times{s+=rand(6)-2.5};x+=2)while s!=0 ``` ### Explanation ``` s=x=2; # sum=2, x=2 ( )while s!=0 # while sum != 0: s=0; # reset the sum p # print x.times{ }; # repeat x times: s+= # Add to sum: rand(6) # random int in 0..5 -2.5 # subtract average # (implicitly return x for printing) x+=2 # Increment x by 2 ``` [Try it online!](https://tio.run/##KypNqvz/v9i2wtbIWqPY1sC6QKFCryQzN7W4uljbtigxL0XDTFPXSM@01rpC29ZIszwjMydVoVjR1uD//695@brJickZqQA "Ruby – Try It Online") [Answer] # Javascript, 87 chars ``` for(n=2;eval('+'.repeat(n).replace(/./g,x=>x+(Math.random()*6|0)))!=2.5*n;n+=2)alert(n) ``` Test with `console.log` instead of `alert`: ``` for(n=2;eval('+'.repeat(n).replace(/./g,x=>x+(Math.random()*6|0)))!=2.5*n;n+=2)console.log(n) console.log('Done') ``` [Answer] ## lua, 102 bytes ``` function r(n,t) for d=1,n do t=t+math.random(1,6)end return t==n*3.5 or print(n)or r(n+2,0)end r(2,0) ``` Or the more readable version ``` function r(n,t) --recursive function does its magic, t is given to safe usage bytes(no local) for d=1,n do --roll n dice and count them up to the total (t) t =t+math.random(1,6) end return t==n*3.5 or --check if t==n*3.5. If it is then it ends print(n) or --t != n*3.5 thus print n. print returns nil r(n+2,0) --both the check and the return value from print are false thus r gets executed. end r(2,0) --start the process ``` A more cheaty version for 96 bytes ``` function r(n,t,m)t=t+m(1,6)+m(1,6)return t==n*3.5 or print(n)or r(n+2,t,m)end r(2,0,math.random) ``` This pretty much works the same as the first but reuses the rolls from earlier calls. Because of this I can remove the for loop. Both are tested in lua 5.2 [Answer] # [Perl 6](http://perl6.org/), 48 bytes ``` .say for 2,*+2...^{3.5*$_==sum (1..6).pick xx$_} ``` ]
[Question] [ Given \$ i = \sqrt{-1} \$, a base-\$ (i - 1) \$ binary number \$ N \$ with \$ n \$ binary digits from \$ d\_{0} \$ to \$ d\_{n - 1} \$ satisfies the following equation. $$ N = d\_{n - 1} (i - 1) ^ {n - 1} + d\_{n - 2} (i - 1) ^ {n - 2} + \cdots + d\_{1} (i - 1) + d\_{0} $$ For example, a decimal number \$ 15 \$ is \$ 100011101 \$ in base-\$ (i - 1) \$ since, $$ (i - 1) ^ {9 - 1} + (i - 1) ^ {5 - 1} + (i - 1) ^ {4 - 1} + (i - 1) ^ {3 - 1} + (i - 1) ^ {1 - 1} $$ $$ = 16 + (-4) + (2 + 2i) + (-2i) + 1 = 15 $$ This is a list of \$ 0 \$ to \$ 9 \$ converted to base-\$ (i - 1) \$. ``` 0 0 1 1 2 1100 3 1101 4 111010000 5 111010001 6 111011100 7 111011101 8 111000000 9 111000001 ``` Given a decimal integer as input, convert the input to a base-\$ (i - 1) \$ binary number, which is then converted again to decimal as output. For example, ``` 15 -> 100011101 -> 285 (in) (out) ``` You may assume that the input is always \$ \ge 0 \$, and the output will fit in the range of \$ [0, 2^{31})\$. --- ### Test cases ``` 0 -> 0 1 -> 1 2 -> 12 3 -> 13 4 -> 464 5 -> 465 6 -> 476 7 -> 477 8 -> 448 9 -> 449 2007 -> 29367517 9831 -> 232644061 ``` [Answer] # [Python](https://www.python.org), 49 bytes (@xnor) ``` lambda n:3*int(f"{n+a^a:b}",4)&a+a//12 a=2**34//5 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3DXMSc5NSEhXyrIy1MvNKNNKUqvO0E-MSrZJqlXRMNNUStRP19Q2NuBJtjbS0jE309U2hGt0KisDqNSw1NRWUFUxMLLlgIkYGBuZgQSNLYzNzU0NzuIylhbEhRMbYyMzExMDMEGLaggUQGgA) ## Old [Python](https://www.python.org), 51 bytes ``` lambda n:3*int(f"{n+a^a:b}",4)&a+a//12 a=0xcccccccc ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3jXMSc5NSEhXyrIy1MvNKNNKUqvO0E-MSrZJqlXRMNNUStRP19Q2NuBJtDSqSoQCq1a2gCKxDw1JTU0FZwcTEkgsmYmRgYA4WNLI0NjM3NTSHy1haGBtCZIyNzExMDMwMIaYtWAChAQ) ### How In polar coordinates the base is \$b\_k = \sqrt 2^k \times e^{\frac{3ki\pi} 4}\$. From this it is easy to verify $$ \begin{align} 1 &= b\_0 & 2 &= b\_2+b\_3 & -4 &= b\_4 & -8 &= b\_6+b\_7 \\ 16 &= b\_8 & 32 &= b\_{10}+b\_{11} & -64 &= b\_{12} & &\ldots \end{align} $$ *Display 1* Observations: 1. as the size of the base is \$\sqrt 2\$ we need twice the number of 'bits' than in standard binary. 2. Bits 1, 5, 9, ... are never used. This is encoded by the bitmask `0b ... 1101 1101 1101 = 0xdddddddd = a + a//12` 3. Standard bits 2,3,6,7,10,11,... occur with a negative sign. This is encoded by the bitmask `0b ... 1100 1100 1100 = 0xcccccccc = a`. We can do the transformation in two steps: from standard base S = 1,2,4,8,16,32,... to 'alternating' A = 1,2,-4,-8,16,32,... and then from A to final base C (for 'complex'). Step 1, S->A: Because of observation 3 if any of the bits of `a` is set in the input *n* (S bits) we need to borrow from the next higher bit. If that bit is also in `a` or was already set in *n* we need to borrow from the next higher bit and so on. One can check that the right cascade of carries is triggered by simply adding *n* and `a`. One can also check that afterwards the not in `a` A bits are already correct whereas the in `a` A bits are all wrong. In other words we need to `xor` with `a` and that completes step 1. Step 2, A->C: For this we just need to look up the bit pairs from display 1. One way of doing this is to repeat all bits and then mask as explained in observation 2. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 17 [bytes](https://github.com/abrudz/SBCS) Full program. Counting up from `¯1` (exclusive) check if the binary representation interpreted as base `¯1J1` matches the input. ``` 1+⍣(⎕=¯1J1⊥2⊤⊣)¯1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97b@h9qPexRqP@qbaHlpv6GX4qGup0aOuJY@6FmsC@SAl/9MUuBQMuECkIZg0ApPGYNIETJqCSTMwaQ4mLcCkJUSXKQA "APL (Dyalog Extended) – Try It Online") --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), 28 [bytes](https://github.com/abrudz/SBCS) ``` {0=⍵:0⋄(16×∇-⌊⍵÷4)+12⊥2 2⊤⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9rA9lHvViuDR90tGoZmh6c/6mjXfdTTBRQ7vN1EU9vQ6FHXUiMFILkEKFT7P@1R24RHvX2P@qZ6@j/qaj603vhR20QgLzjIGUiGeHgG/9d41LtKJ@3QCk0FAx0ge7Olpo6RgYG5gqWFsSEA "APL (Dyalog Unicode) – Try It Online") The Python implementation on OEIS can be simplified to $$ f(n) = \begin{cases} 0 & \text{if } n = 0 \\ 16 f(-\lfloor{n \over 4}\rfloor) + [0,1,12,13][n \bmod 4] & \text{otherwise.} \end{cases} $$ `12⊥2 2⊤⍵` is a short way of expressing the mod-4 mapping using the base conversion primitives, everything else should map 1-to-1 to the mathematical notation. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 33 bytes Implementation of the formula mentioned in my other answer. Borrowed the `3-n>>2` from a comment by [AnttiP](https://codegolf.stackexchange.com/users/84290/anttip). ``` f=n=>n&&1-(n&3)&13^1|f(3-n>>2)<<4 ``` [Try it online!](https://tio.run/##BcHdCoMgGADQe5/CixCFT8lsq1h5tyfocmwk/a0RGiYjaD17O@djvmZt/bQEbl3Xn@dQ2UpbQiSnlihGpHrJ30AVt1onrCzT84bQIwYJCShI4QJXyCCHApI4zqDIlXyKwfm7ad8UYbzhSuPW2dXNvZjdSJto30RwdfCTHSkTi@nqYHygKTsw1zjaB7qxo2GInX8 "JavaScript (Node.js) – Try It Online") The `(n&3)` could be `n%4` in Python, but Javascript handles negative dividends differently. While one could have come up with the magic formula `1-(n&3)&13^1` by hand, I used Lynn's [pysearch](https://github.com/lynn/pysearch) to find it. | `(n&3)` | `1-(n&3)` | `1-(n&3)&13` | `1-(n&3)&13^1` | | --- | --- | --- | --- | | 0 | 1 | 1 | 0 | | 1 | 0 | 0 | 1 | | 2 | -1 | 13 | 12 | | 3 | -2 | 12 | 13 | [Answer] # [R](https://www.r-project.org/), ~~54~~ 51 bytes Or **[R](https://www.r-project.org/)>=4.1, 44 bytes** by replacing the word `function` with a `\`. *Edit: -3 bytes thanks to [Polichinelle](https://codegolf.stackexchange.com/users/110836/polichinelle).* ``` f=function(n)`if`(n,16*f(-(n%/%4))+n%%4*6-5*n%%2,0) ``` [Try it online!](https://tio.run/##K/r/P802rTQvuSQzP08jTzMhMy1BI0/H0EwrTUNXI09VX9VEU1M7T1XVRMtM11QLyDDSMdD8n6ZhoMmVk1hQkFOpYWhlZKCTpvkfAA "R – Try It Online") Based on [formula found by @ovs](https://codegolf.stackexchange.com/a/243119/55372). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` Bḅ-ı=ʋ1# ``` [Try it online!](https://tio.run/##y0rNyan8/9/p4Y5W3SMbbU91Gyr/P9z@qGnN//8GOoY6RjrGOiY6pjpmOuY6FjqWAA "Jelly – Try It Online") Let \$f(n)\$ be the function described in the question. We use the fact that \$f(n) \ge n\$ for al \$n = 0,1,2,...\$ to save a couple of bytes. ## How it works ``` Bḅ-ı=ʋ1# - Main link. Takes n on the left ʋ - Group the last 4 links into a dyad g(k, n): B - Convert k to binary ḅ-ı - Convert this to base -ı (-1+1j) = - Does this equal n? 1# - Find the first k ≥ n, such that g(k,n) is true ``` [Answer] # JavaScript, 42 bytes ``` f=(x,y=0)=>x|y&&x+y&1|2*f(1-y-x>>1,x-y>>1) ``` [Try it online!](https://tio.run/##DYpBDsIgEAC/svFAWCmmePBS4S9NBbNauw0Ywyb9O5I5zBzmNf/msmTav7bs9Ij5w9s7SmvJ6zqIH9GHeohS1Yhyx/WctLNiawhuqFa6sCXOoAk8jBMQ3D24Ww9jEBbeCq/xsvKzDwZOHQNJE@LU/g "JavaScript (SpiderMonkey) – Try It Online") `f(x,y)` produces the base-\$(-1-i)\$ representation of \$ x+iy \$ (which is identical to the base-\$(-1+i)\$ representation for real numbers) reinterpreted as binary, for integers \$x,y\$. `x|y` is zero iff `x` and `y` are both zero; the `&&` short-circuits to produce zero in that case. Otherwise, `x+y&1` gives the ones digit of the base-\$(-1-i)\$ representation of \$ x+iy \$ (since all higher digits contribute an even amount to `x+y`), and the recursive call produces the rest of the digits. [Answer] # [Factor](https://factorcode.org/), ~~82~~ 78 bytes ``` :: f ( m -- n ) m [ 0 ] [ 4 / ⌊ neg f 16 * m 4 rem "\0 \r"nth + ] if-zero ; ``` [Try it online!](https://tio.run/##HY09bsJAEEaVFuUQT1QEZLD5xxwA0dCgVCGF5cyChb1r1kuRIC6AOGUu4ozSjD7N996MyfLgfPu@3@42KVUWTpzFWykpXZ6Vzf9qeLVF7r6ERi5Xsbk01F5C@K59YQPrznaXcnSladMUQ4@KKMLypuGDmE@dU0b8Ph9YOSqSzOlrOcVLRfcQv7wefNfq84HChYl@xDvW7U3lhDETJWfMWbBkRTJjHMcLVstJwl1vG5WqrGbY/gE "Factor – Try It Online") This is a direct implementation of the recursive [formula](https://codegolf.stackexchange.com/a/243119/97916) given by @ovs. And for posterity, my original answer: # [Factor](https://factorcode.org/) + `lists.lazy math.unicode`, 85 bytes ``` [ 0 lfrom [ >bin reverse 49 swap indices C{ -1 1 } swap n^v Σ = ] with lfilter car ] ``` [Try it online!](https://tio.run/##JY5PDsFAGMX3TvEuoFEUJWwsxMZGrIRkTL@mE9NpfTOtIE7jPq5UI7N8f/J7LxfSVdwd9tvdZg6trLORFs8HSuGKqBZsiWHp1pCRZHElNqRRMzn3qFkZF4ot/TE2iMYoWWUUaFj0ei8MEGOIEcZIMMEUM6SIE7y7o490zlWJI1YXZcDUkh/FOIW9ixrKZOq/vH6hH3vKO9jm3OL7wRIn3JUrPENp569KwTh1pW9E3Q8 "Factor – Try It Online") ## Explanation Tries every number starting from 0 until it finds a match, in a brute force way. Slow for the larger inputs, but should theoretically eventually finish. * `0 lfrom [ ... = ] with lfilter car` Apply `...` to every number >= 0 until it equals the input. For instance, for input 15 and n=285... ``` ! 15 285 >bin ! 15 "100011101" reverse ! 15 "101110001" 49 ! 15 "101110001" 49 swap ! 15 49 "101110001" indices ! 15 V{ 0 2 3 4 8 } (get indices of the 1s) C{ -1 1 } ! 15 V{ 0 2 3 4 8 } C{ -1 1 } (i-1) swap ! 15 C{ -1 1 } V{ 0 2 3 4 8 } n^v ! 15 V{ 1 C{ 0 -2 } C{ 2 2 } -4 16 } Σ ! 15 15 (sum) = ! t ``` [Answer] # x86\_64 machine code, 31 bytes (or 27 bytes) ``` \x81\xc7\xcc\xcc\x00\x00\x81\xf7\xcc\xcc\x00\x00\xb8\x55\x55\x55\x55\xc4\xe2 \x43\xf5\xc0\x8d\x04\x40\x25\xdd\xdd\xdd\xdd\xc3 ``` [Try it online!](https://tio.run/##bY7haoMwFIV/L09xSSkkoxZbdbW49kWWIZrENbDFoXGkG3t2l@gglu3HgY9zzz338uiF83GlNH8dhITH3gjVbi/nsSwrYzpVD0aWJSG95Ea1muCtkdZgSinwS9VBrfTTM5wQZjbfMcsPTnxWHM/yfvOPX@fMZtmteMqs3GNflyZuzVu@QrgVN0od750nxK14gos/H1/7j7KqlftUaQPkvqHEAYWTf7pAaCVko7SE987ZxNIZGoLXAqIzrAXTeAN2A40bUoR8y1ulNKHwhe4W4fpqZM/0FJ9O9OpTtg1xZyhEsKPFb5zEARfuPmASMA2YBXwIeAiYBzwueuN4kTnmyXSzk2boNMQF@h5/AA) **assembly** ``` add edi, 0xcccc xor edi, 0xcccc mov eax, 0x55555555 pdep eax, edi, eax lea eax, [rax + rax * 2] and eax, 0xdddddddd ret ``` This is a port of [the amazing solution from @loopywalt](https://codegolf.stackexchange.com/a/243137/108859). See his post for a detailed explanation of the algorithm. [`pdep`](https://www.felixcloutier.com/x86/pdep) is an interesting instruction which solves a problem that otherwise needs some sort of loop or a look-up table. It executes in constant time fast on any Intel hardware that supports it, but on AMD chips before Zen3, [it was a slow microcoded instruction with variable latency](https://uops.info/table.html?search=pdep%20(r32%2C%20r32%2C%20r32)&cb_lat=on&cb_tp=on&cb_uops=on&cb_HSW=on&cb_ZEN2=on&cb_ZEN3=on&cb_measurements=on&cb_base=on&cb_bmi=on&cb_others=on). The sequence of 6 instructions has a blazing [estimated throughput of 2 cycles](https://bit.ly/3JNhfPc). The first two instructions can be modified to save 4 bytes, but it will run a bit slower. ``` mov ax, 0xcccc add edi, eax xor edi, eax ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~33~~ 32 bytes ``` f=n=>n&&f(3-n>>2)*16|6*(n&2)|n&1 ``` [Try it online!](https://tio.run/##bZrdzl21EYbPcxVfe4ASSiuP/0c0nPUqEKoQTSoqlFSBIg5679TzPuPVH1UCP6O97NcznvGy9873t29//vbH7z59//effv/h41/e/frr@7cf3n714bPP3r9uv//w1Vf1zec2/zk/f/3hs/rmnx8@s1@/fPXq/cdPL69/ePfTyy8vb1/Klwd/fPvih7/73ZtXLy/fffzw48cf3v3hh49/ff3LFy/vX//y5s2Xr/7z01rKigfB/33mu1k8C8azVx/fff/jn3/@9od/vPvx7auvyxev7PxXz//ti1d99mjGadaMZp2m72g8HpRoTv@6ajRnRN09mjOijhnNGVHnjuaMaHUXtRatV7Ut2pjotCPamOq0Z2Qre6uNsVaK2hhbYsLTNj3tamPsaFNtjB3h6Glj7KhFrelpVRtjW@9qY2wLh08bY4@Lal1Pi9pYF9seXost6KX05ODz8F5cMCIQXdwRhYjetpqU3l67J9FbPpPS89p30uEsSYOtJlv268mBn2Mm0StzJ9ErvSQt@9Vk6NVaIlPigIo3uKD8C3r2K0nV1QmkJhtUvMEB5V9wQfkXRK/VkjSoeIP410pP4l@zmcQ/qzuJnvWSRM@sJlv260mtX9/k41Dr173spPP5LknLfjWpfPRFvRyit2wm0ZvUy6Fnv5KU3jDycdig8hEcsM3kgtTLIXpOvRzin6@axD@nXg7xz6mXQ@mdctxJh8R7aBD/Dlv260nprcX@OERvEe8hegv/Di371ST7o9aeZH9U4j1kv1XycejZryTZb4X9cYheId5D9Ar5OESv1J08etN3lEvAhAg20IRwLTCEcCywAjPSEJDKnAVIZbYKGl06OCon@VFugRWwCC7g@jCWPmB0qUAqXjqQL24TyJe9N3C6FBAq1aP8A02IiALhS1XpB5Y@lC9Vdb/OAVCAVFarQCoq@YBUVPCBUDm7cwMXFNGBCbG6gUaXDqSi12wAXza@bPmiEg8Q0SKiqJ85llb3YAhR3IElRKoDTpcCIkdjKNMHUhmzA6no0AlIRcdOIFRm0eoemBCrG5CK7w6k4j6BVHbZQL7sWoB8WV5Bo0sHoXLeOhMsQREduCBfOHkmB8/k3Jl7qnYPpDIV0YFUpnw5cLoUoNrVQRxQ1ekoDqjqdNRMTprJQTM5Z860G182vji@KKK9tboHRLSIKDK9G8UruqjyFY3PwyGxZb@eHOKMZRbRW2Un0Zu7JC371WTo9WJRQOKAEaS4YCy56NmvJNHT@1HEP70fRfzzNpP4530npUdxiwYVb6e@g/hXHf@q4191/DuXq51Eb@2SRG@NmmzZryeld47dmVyQeA8dKh9By341Kb1Wak@iV9pMolfKTnr2K0mtH8Uvav0of3Hw@ZrJBamXsaiXMamXQ/Sm1SR6g3o5RG9QL4fSm4V8TN1vgspH0GCryZb9ehI93W9E/NP9RsQ/HTCiZb@alB6bQxyQeO/@OOW@k579SlJ6e7I/DtGbxHuI3sS/Q/Qm/h2yP6yWJPVsxHtIPRv5OKSezWYSPa87iX9OvIf45@RjO/nYOoLEeO/Hi2YmF4x4RYc6iIKW/WqyiSPyIaI3xkyiN@pOevYrSfR0/xelZ7r/i@hxMAXR42gKoqeXsIieXsMi/un@L2a8nvHq1PWmg0F0SLxtE29b@NcW/rWNf23jX5s6foPoTeI9RG/iX5v41yb@tYl/Xfd/cUDi7YV4eyEfvZCPrv0hoqf3s5j@7fSPeNsmH22PjHdmvLohnDJUPoIGdUkINqgrS3BA1Utwifr6KqKnL7Eier3VZMt@PYkel6AgelyDgujpYBMt@9UkelyGguhxHQqip/u/6NmvJKXnS/kINki8h9LjfBMXn@Mf59uhvgmL6A3i9UG8PvDvEL2Bf4fo6f4voufE6068nG9iy349iZ7ez2L6t9M/4vVFPnzNjHdlvFEvsQ0jXnHAyK@4YMQrevYrSRP1/VhET9@PRfR0vono6XwT0dP9QERP9wMRvTl7Er25ZjL92@nfRm@UkkSvr5rMeHfGu6V3XuszKb09iPfQ@Rz/Di371aT0tr4fi@g14t2NeM@NcSc9@5UkerofiOgt4t2LePciH3uRj633s4jemCWJ3iDeQ/QG@diDfGy9n0XpWSMf1siH6dcZ0aDVZMt@PSk9M/wzwz8z/DPDPzPqxYx6MaNezKgXG@TDBvmwQT5skI9zHdxJz34lmf55@kc@zvWwJ9Fr1MthxrszXvLRO/k4NEi8h9LrDf8OB8S/Q@n1Sr30Sr30Sry9Em83/Dts2a8n0Zvko0/y0Sfx9km8fZKPPslHn9RLn9RL79RL79RL78TbO/H2Tj567xnvzHh1fxlTPzWKDer@EhxQ95fggrq/BF3Ul2YRPX1tFtHT@Saip/NNRE/3AxE93Q9E9IbVZMt@PYleazOJXus7iZ5@3xIt@9Wk9Fy/WIoDEq834vWGf97wzxv@ecM/15dqET0jXjfidcM/N/xzwz83/HPuz0H0uD8H0eP@HESP@3MQPb2fRfQ68XonXm/kwxv5cO0PUXrntTyTC@p@H3So@27Qsl9NSs8c/8zxzxz/zPHPnHoxp17MqRdz6qV28lE7@aidfNROPmq3mcS/Tj4O8a@Sj0P0Kvk4RK9SL7VSL7WSj1rJx6jkY1TyMSrxjkq8nG9iy349Kb1RqJdRqJdRiHcU4h0F/0bBv1HwbxT8G4N8jEE@xiDeMYiX80307FeS6DXqZTTqZTTiHY14z7aaSfQa9XIYv8Wf9wgZTsuuxb8HyGrX0m/7WONa@o0fa2GR8bT8Wrs8ll1r1Mdqz4j@WHcOVUBa61p1P9aNQ2/ytOwZUR/rxqGKSOvOoapI686hN3ta/owoj5VzUCFptWvdtaJOsG4c3IWwbhzch2SpYtK6c5S7VtQN1o1jlBvHKDeOUW4cVFBad45x14o64unNOXelHNEf64nDnzj8ztHuWv27rka9OR91P2vlz1o5c5zzPHMe1rjWmo@1rtX3Y/kzojwWc4y1M46w2rUyjrDGtbJ2w1rXytoN687Ranksu1bmPKwbh26Cad04ms3HunFY3Y9157BeHuvOYVYfqz0j@mNlPriBpXX3oPX9WHcP2q1d7mI5oj5W5rz4rd3it3aL331e/O7z4rd2i9/aLX5rt/itXW5oad193kt/rBtHW/Oxbhzt1i73NVn11q7VW7tW7z63eve52a3dYz1r5c9aZe0av5Cl5dfKtTJ@JwuresYRVntG9Mca@XRnzsNa18q1CsuvlXGEZc@I@lh3jjr7Y41r5VrZ/XfdsPp@LH9GlMey62nuD7v/3hvWfuLYd44y5mM9azWftcr9YdwA07Jr3bXiHoh145h3n9u8@9zm3efnYp85DyvnGH7Xavhdq3H3eVjtGdEf687R2nysda27VtwTsW7O593nNu8@t3n3@Tkje3@sO8c9B8O6c9x9HpY/I8pjMUfhF7q02rVynxd@p5O1s3bDWvdp1m5YntbKOMK6c6xWH@vM8c3//6uIFztnyvN3Ed@/f3kdfwzx8pu3b1/@468avv7lm3j833848ds/ffr08dNv33z5678A "JavaScript (Node.js) – Try It Online") This is another implementation of the \$n\rightarrow \lfloor{n/4}\rfloor\$ recurrence given in the OEIS. (I saved a byte by changing `-(n>>2)` to `3-n>>2`, as suggested by @AnttiP and others.) [Answer] # [Python 3](https://docs.python.org/3/), ~~65~~ ~~45~~ 40 bytes ``` f=lambda n:n and(n&2)*6+n%2+16*f(3-n>>2) ``` [Try it online!](https://tio.run/##PdBRT4MwEMDxdz7FvSjtxpJyLYUtYV9EfUBWtsXZEaiJuuyz491FJfALpPw50vErna7RLsvQXrr310MHcRehiwcVH1Gv/Do@4Lr0q0HZTdzvUS/hcwx9CgdoQZkCSjqRLluA846piNozNeEaZssLhqH3sUaGCmwcQwVWnqECfcNQYbExYsluUbQsDyIrlkeRVFrTNCK3pTEit4YHklZWnchtZb3IbcU/SnJboRFLWUWRW@ucyK2tvM5SmNNMGzF18RjUJUT1tztaZ/0p9G9h4n3Knz@wdn1egNyVNtfZcJ0gFQHOEb7Po5JPFfDf7zKggz8@qKTlYZzOMakhv6U7bPZwm@9w@x3yFNp2frnnevkB "Python 3 – Try It Online") *Saved a whopping ~~20~~ 25 bytes thanks to [AnttiP](https://codegolf.stackexchange.com/users/84290/anttip)!!!* [Answer] # [Husk](https://github.com/barbuz/Husk), ~~16~~ 14 bytes ``` B16mo?I+10εB_4 ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8b@ToVluvr2ntqHBua1O8Sb///@PNtAx1DHSMdYx0THVMdMx17HQsdQxMjAw17G0MDaMBQA "Husk – Try It Online") Converts to base `-4`, replaces digits `0`, `1`, `2`, `3` with `0`, `1`, `12` & `13`, and converts back from base `16`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` NθWθ«F1220⊞υ&θIκ≔±÷θ⁴θ»I↨⮌υ² ``` [Try it online!](https://tio.run/##HYy7DoJAEEVr@YoJ1WyCCW5MLKxAGxpC/IMVRpiIi@wDCuO3r4vVvcU5px2UaSc1hlDpt3e1f93J4CzOyTrwSBAvfJLdYzKA6UHKPBXQeDugz6Bkt7KlQnc4Z3BR1uFTiKjuCmu511hTrxxhpd2VF@5ow45CZLD1v0ljWDv8e6WyhDdayMT1kZBbKASZ56ewX8Yf "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` Wθ« ``` Repeat until `n` is zero. ``` F1220⊞υ&θIκ ``` Create four more "bits" in the "base 2" representation of `n` using the digits `0221` bitwise anded with the current value. This results in `0000`, `0001`, `0220` (i.e. `1100`) and `0221` (i.e. `1101`) (although the bits are actually pushed in reverse order so that they accumulate correctly). ``` ≔±÷θ⁴θ ``` Integer divide `q` by `4` and negate it. (Sadly this is not the same as integer dividing `q` by `-4`, otherwise I could use negative base conversion.) ``` »I↨⮌υ² ``` Convert the "bits" from "base 2" and output the result. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 33 bytes ``` f(n)=if(n,16*f(n\-4)+n%4*6-n%2*5) ``` [Try it online!](https://tio.run/##FYtBCoMwFESvMgiCP52A0Zjqwl6k7cJNS6B8grjp6eN3M/PewJRtz/5bav10Kmu2ZEjO6uWj3LSNLnltBzdJ3Ur5/TuFf6DsWQ/D5pIG11eIZyAGYiQiMRGJuBMzsdje98bLPIa31BM "Pari/GP – Try It Online") A port of [@pajonk's R answer](https://codegolf.stackexchange.com/a/243145/9288). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 4(вεD2@ì}16β ``` Port of [*@DominicVanEssen*'s Husk answer](https://codegolf.stackexchange.com/a/243146/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##yy9OTMpM/f/fROPCpnNbXYwcDq@pNTQ7t@n/f0NTAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/E40Lm85tdTFyOLym1tDs3Kb/Ov@jDXQMdYx0jHVMdEx1zHTMdSx0LHUMTXWMDAzMdSwtjA1jAQ). **Explanation:** ``` 4(в # Convert the (implicit) base-10 input-integer to base-(-4) as list ε # Map over each integer in the list D # Duplicate it 2@ # Check if it's >= 2 ì # Prepend that 0/1 to the integer }16β # After the map: convert the list from base-16 to a base-10 integer # (which is output implicitly as result) ``` Two equal-bytes alternatives for `εD2@ì}` could be `D2@T*+` or `D2@søJ`, but I haven't been able to find anything shorter for this. [Answer] ## Python, 48 bytes ``` f=lambda n:16*f(-(n//4))+6*(n&2)+n%2 if n else 0 ``` This is a recursive function that takes advantage of the fact that because (i-1)^4 = -4, then every 4 bits of the output corresponds to a base -4 number. `f(-(n//4))` makes the recursive call for the base -4 representation of `n` *except* the last digit. Unfortunately, the inner parentheses are necessary. Multiplying by 16 shifts left 4 binary digits to make room for the last digit. `6*(n&2)+n%2` is a golfed way to encode the last base -4 digit: * 00 → 0000 * 01 → 0001 * 10 → 1100 * 11 → 1101 The last bit of the input (`n%2` or `n&1`) corresponds directly to the last digit of the output, while the first bit of the input (`n&2`), corresponds to either 000 (decimal 0) or 110 (decimal 6). Unfortunately, the parentheses in `n&2` are necessary because of operator precedence. `if n else 0` handles the base case of the recursion. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` λb°‹β?=;ṅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOu2LCsOKAuc6yPz074bmFIiwiIiwiMyJd) Port of Jelly. ]
[Question] [ ## Input A string of printable ASCII characters, for example: ``` This is an example string. ``` ## Output For every consonant (`BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz`) that is not followed by a vowel (`AEIOUaeiou`) add the last vowel before it, in lowercase. **Consonants before the first vowel are left as-is**: ``` Thisi isi ana examapale seterinigi. ``` ## Test cases ``` AN EXAMPLE WITH A LOT UPPERCASE (plus some lowercase) => ANa EXAMaPaLE WITiHi A LOTo UPuPEReCASE (pelusu some lowerecase) And here comes a **TEST** case with 10% symbols/numbers(#)! => Anada here comese a **TESeTe** case witihi 10% siyimiboloso/numuberese(#)! This is an example string. => Thisi isi ana examapale seterinigi. abcdefghijklmnopqrstuvwxyz => abacadefegehijikiliminopoqorosotuvuwuxuyuzu A pnm bnn => A panama banana Tell me if you need more test cases! => Telele me ifi you neede more tesete casese! ``` ## Scoring As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the answer with the lowest byte-count **in each language** wins (no answer will be accepted). [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 48 bytes ``` i`(?<=([aeiou]).*?[^\W\d_aeiou])(?![aeiou]) $l$1 ``` [Try it online!](https://tio.run/##NY5dS8NAFETf8yumWCHJQ7XvSggSUKga7EoLrR@b5LZZ3ezGvRvT@OdrFIV5msMwx5FXRs6PR/UaJheX4UaSst1TNIuTzfN2ta1e/oowmfyzYKqn4yK9Q7ZOb/NFhtWNuEaKxb3AY55nD1fpMkPY6o7BtiFo25MrJVMUpKZCTY5QjoAhEcciW4o4xg9Hr3yN@fkpeGgKq/nMdE1BjsOTaBKIWjHGSAM6yKbVBPZOmf0skEVZ0W5fq7d33Rjbfjj23Wd/GL4CQVpjlFA7DLaDIarQ2NHAE/vfV558Aw "Retina – Try It Online") Explanation: The lookahead searches for a point not followed by a vowel, while the lookbehind searches for an immediately preceding consonant and a previous vowel, which is then inserted in lower case. [Answer] # JavaScript (ES6), ~~108~~ 105 bytes *(Saved 3 bytes thanks to @Shaggy.)* ``` f=s=>(t=(s+=' ').replace(/[aeiou]|[a-z][^aeiou]/ig,r=>r[1]?r[0]+v.toLowerCase()+r[1]:v=r,v=''))!=s?f(t):s ``` Searches for vowels *or* for consonants with no following vowel: ``` /[aeiou]|[a-z][^aeiou]/ig ``` (We don't need to search for consonants explicitly, because vowels are excluded based on the `/[aeiou]|...`.) Vowels are stored in `v`, and consonants with no following vowel have `v` inserted: ``` r[1]?r[0]+v.toLowerCase()+r[1]:v=r ``` (If `r[1]` exists, we've matched on a consonant plus non-vowel.) If nothing has been changed, we return the input. Otherwise, we recurse on the replaced string. ``` f=s=>(t=(s+=' ').replace(/[aeiou]|[a-z][^aeiou]/ig,r=>r[1]?r[0]+v.toLowerCase()+r[1]:v=r,v=''))!=s?f(t):s console.log(f('A pnm bnn')); console.log(f('abc')); console.log(f('AN EXAMPLE WITH A LOT UPPERCASE (plus some lowercase)')); console.log(f('And here comes a **TEST** case with 10% symbols/numbers(#)!')); console.log(f('This is an example string.')); console.log(f('abcdefghijklmnopqrstuvwxyz')); console.log(f('Tell me if you need more test cases!')); ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~134~~ 119 bytes ``` def f(s,v=''):u=s[:1];return s and u+v*(u.isalpha()-g(u)-g((s+u)[1]))+f(s[1:],[v,u.lower()][g(u)]) g='aeiouAEIOU'.count ``` [Try it online!](https://tio.run/##HZBNT4NAEIbP9ldMY8zuUkTxiMGEGBKbVG0sjSaEA6ULrC67uB@0@Odx6WUu78c8M/1oWikepulIa6ix9ocYIRLZWOdRWDwqaqwSoKEUR7CrwcM2YLrkfVticttgOw@sV5bkYUHIyjXkYVT4@eDbgMsTVZgU@ewryKKJUUmZtEm6ft@joJJWmKmWytUzATlK3iD9Sl63mxQ@19kLJLB5z2C/3aYfz8kuBdxzq0HLjsKluio1JcgHlDi4lioKldMcK3helu4yz4PZAidmWgjvb0CP3UFyfSdsd6BK42uynONZyxzBfCPQc9n1nII2iokmmNXyULnfNC37/uGdkP2v0sYOp/P4d8lSzsEBsRpGaUFQeoROOhRDtbms10tURIur3hUa0D6Kn5Dv3kQW0z8 "Python 2 – Try It Online") EDIT: 15 bytes thx to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn) [Answer] # [sed 4.2.2](https://www.gnu.org/software/sed/), 64 bytes ``` : s/(([aeiou])[^a-z]*[b-df-hj-np-tv-z])([^aeiou]|$)/\1\l\2\3/I t ``` [Try it online!](https://tio.run/##HY7dSsNAGETv9ymmqJAEYqzeeRckYKFqsRGFpsKm@dps3Z@Yb9M/fHZjLMzVnIE5TFXf3wtOgmAhSbluGS4@ZXxaRosyrtZxvY1tE/vd0ITBQM6Tn8swKcaFLm6Lu2QifN@nz8g@0qfZNMP7JH9EiulLjrfZLHt9SOcZgkZ3DHaGoN2e2pVkCkVqK9TUElYDYEhEUZ7N8yjCP8de@Rrjmyvw0ZROc2I7U1LLwUU4EnmtGEOkBR2kaTSBfavs5lrIclXRelOr7Zc21jXfLftutz8cTyJFYw1Ka0VOWmPQUWscXQdLVMG4wcUT@/M/j35d45Wz3MftHw "sed 4.2.2 – Try It Online") [Answer] # [Standard ML](http://www.mlton.org/), ~~225~~ 223 bytes ``` str o Char.toLower;fun?c=String.isSubstring(it c)"aeiou"fun g(x,l)$d=(fn l=>if Char.isAlpha$andalso not(?d)then if? $then(it$,l)else(x,l^x)else(x,l))(l^str$)fun f$(c::d::r)=f(g$c d)(d::r)|f$[c]= #2(g$c c);f("","")o explode; ``` [Try it online!](https://tio.run/##bdFtb9owEAfw93yKa5pJNurYw0tQilCF1EmsQ4Vpk7YhXZIL8erYaWwXqPbd2SXZEC9QguKg8/98v7hKv620t@Z4dL4BC3clNiNvF3ZHzaQIZpolK98osx0ptwqp69ZCechkhKRsiLgItmJ/o2WcJ6IwoJNbVfRBys10XWKMJkftLBjrxTSXviQDqphC3K44LebdpB21MZv9aSml0BtuGcu2SRGLbDzOx@NGJoXYxhnkUnSvf4r4R/YrgeuP3d@ZnBQiim6iSFqgfa1tTpPjC2ooIAHlJ4Oap/CigGj2APPvs8/LxRy@fVrfwwwWX9bwdbmcP97NVnMQtQ4OnK0IdEuSoSMZwQainyaS50Emh5IagoxrHSAMh@v5aj0cQrsFdsqX8OH9G3CHKrXavTOhSqlx4lpeXYpbl8oB32h4AKxqTdDTjy5VY5rlVGxL9ftJV8bWz43z4WW3P7xePCrUpoLUmIuNSWvgafkLHmwAQ5RDZXkuT853s7jzAw/EcJDcwuwBO0dcYi@p7lVvaRkzsCb94yT2DGeg1Il2GQZzPDOk/4i0pjNGVaoeUh1UpdjSOttqBubkTS1om9YCKmh/aLAzxBpbRfLEs6qtGrVlmGKGbEdbYj31pDSHsqB9tg0Hs2LYhX04hNfQnRFqjqsQUn4Y7BqR5qsnUyczOqFxv56NrgZDefwL "Standard ML (MLton) – Try It Online") **Less golfed:** ``` val lower = str o Char.toLower fun isVowel c = String.isSubstring (lower c) "aeiou" (* c is the current char, d is the next char, x is the last vowel and l the accumulator for the resulting string *) fun g (x,l) c d = if Char.isAlpha c andalso not (isVowel d) then if isVowel c then (lower c, l^str c) else (x, l^str c^x) else (x, l^str c) fun f t (c::d::r) = f (g t c d) (d::r) | f t [c] = #2(g t c #"d") val h = f ("","") o explode; ``` [Try it online!](https://tio.run/##bZFta9swEMff@1NcFQaWybKHlykZhBLooOvC4j3AtoBsX2KtsuRaVpOUfffsJDUPjNgY23f/@9/dT7ZRrxvVG73fPwkFymywgwnYvgMDN7XoRr2588EkWTkN0n6jHwUlaRZ9J/V6JO3CFTZ8QxrrSw5MoDSOxSpKbIeKU1UFkwTokqtoLu1UtbWgjNCVUNaANj2khzYVD@q@Ru1LTt1DGI65Q98hqKUfveQnASqLvv8htdzG5P9xHmddAfUvx@NqPO44bbmCdE0hGp1DGoJU/TfIfpa/STB4/yIYsIqRicdYx0LGhoxxAonbVpkKr/ctYerTGtj0HmY/pp/mdzP4/jG/hSncfc7h63w@@3IzXcwgbZWzYE2D8UxKYZEzWAL7pRm/Tk5GuoIaO4SStBYEZFk@W@RZBr4ENrKv4d3bV2B3TWGUfaNdU2Bn0wG/umSX19ISZzoOGlo0rUKIZzu6pBZFWeFqXcs/D6rRpn3sbO@eNtvd88VRodUNFFpfbIxKAW1Lx7wzDjRiBY2hvXq0fdjFng@cpFky@QDTexE4irmIJOWtjCwNwXREE19wIvF0Z0AxEA0eWlTijCEeIGKOZxhlLSNIuZONJJbGGk/TEU4q8kC9mwcowT9Ci8BQtMJTxB5pV7mWIy8ThSgFscM1Ej35IBWZEkHzaDoyJopu47Zu555dmBFasmsEFPTSIjRCRXdEJo/M8AiN@kVseJVkfP8P "Standard ML (MLton) – Try It Online") [Answer] # Perl 5, ~~68~~ ~~67~~ 59 bytes ``` perl -pe '$v="[aeiou])";1while s/($v[^a-z]*[b-z]\K(?<!$v(?!$v/\L$1/i' ``` Here's a great example of the usefulness of `\K`, and I can't believe I didn't know about this feature before Dom Hastings pointed it out. I haven't been able to get the right behavior with just using `s///g`, so an actual loop seems necessary. (It's possible that the right use of a look-behind assertion could work without an explicit `while` -- but I haven't found it.) [Answer] # JavaScript ES6, 115 bytes *Saves 8 bytes thanks to @ETHProductions* ``` s=>[x="",...s].map((i,j)=>(r=/[aeiou]/i).test(i)?x=i:/[a-z]/i.test(i)&&!r.test(s[j]||1)?i+x.toLowerCase():i).join`` ``` I have managed to inflate this more in the process of golfing it O\_o but it also fixes a bug ``` s=>[x="",...s].map( // Create a new array with x storing last vowel // This also offsets indexes by one so rel to original str refers to next char (i,j)=> // Going through each char... (r=/[aeiou]/i).test(i)? // If it's vowel, store it in x x=i: /[a-z]/i.test(i) // If a letter (thats not a vowel excluded by above) &&!r.test(s[j]||1)? // Test if next char is *not* vowel i+x.toLowerCase():i // If it isn't, then add the most recent vowel after ).join`` // Combine back to string ``` [Answer] # JavaScript, ~~88~~ 82 Bytes Done with a single regular expression: Original Version (88 Bytes): ``` s=>s.replace(/(?<=([aeiou]).*?(?![aeiou])[a-z])(?=[^aeiou]|$)/gi,(_,c)=>c.toLowerCase()) ``` Updated Version (82 Bytes) after looking at [Neil's regular expression](https://codegolf.stackexchange.com/a/166373/15968): ``` s=>s.replace(/(?<=([aeiou]).*?[^\W\d_aeiou])(?![aeiou])/gi,(_,c)=>c.toLowerCase()) ``` ``` var tests = { "AN EXAMPLE WITH A LOT UPPERCASE (plus some lowercase)": "ANa EXAMaPaLE WITiHi A LOTo UPuPEReCASE (pelusu some lowerecase)", "And here comes a **TEST** case with 10% symbols/numbers(#)!": "Anada here comese a **TESeTe** case witihi 10% siyimiboloso/numuberese(#)!", "This is an example string.": "Thisi isi ana examapale seterinigi.", "abcdefghijklmnopqrstuvwxyz": "abacadefegehijikiliminopoqorosotuvuwuxuyuzu", "A pnm bnn": "A panama banana", "Tell me if you need more test cases!": "Telele me ifi you neede more tesete casese!" }; for ( test in tests ) { var result = (s=>s.replace(/(?<=([aeiou]).*?[^\W\d_aeiou])(?![aeiou])/gi,(_,c)=>c.toLowerCase()))(test); console.log( result === tests[test], result ); } ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) `-P`, 28 bytes ``` ó@\ctX ©\VtYÃËè\v ?P=D:D¬qPv ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=80BcY3RYIKlcVnRZw6NcdnRYID9QPVg6WKxxUHY=&input=LVAKIkFuZCBoZXJlIGNvbWVzIGEgKipURVNUKiogY2FzZSB3aXRoIDEwJSBzeW1ib2xzL251bWJlcnMoIykhIg==) ### Unpacked & How it works ``` UóXY{\ctX &&\VtY} mD{Dè\v ?P=D:Dq qPv UóXY{ } Split the string between any two chars that don't satisfy... \ctX &&\VtY The first char is a consonant and the second is a non-vowel mD{ And map... Dè\v If this item is a vowel... ?P=D Assign it to P and return as-is :Dq qPv Otherwise, split the item into chars and join with P lowercased (P starts with "", so beginning consonants are not affected) -P Join with "" ``` The `ó` function wins over any kind of regexes. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~146~~ ~~143~~ ~~132~~ ~~127~~ 125 bytes ``` (a,v="")=>[...a].map((b,i)=>(w=/[aeiou]/i).test(b)&&(v=b)?b:w.test(a[i+1]||b)||!b.match(/[a-z]/i)?b:b+v.toLowerCase()).join`` ``` [Try it online!](https://tio.run/##bY5RS8MwGEXf/RXfKo6k21L3KlQpo6BQdbiKQiks6bI1I01Kk7Yq/e81xTcZ3KfLuYd7ph01RSNqu1L6wMdjOCK67ELPw@F9RgihOalojRBbCtegPgwyyoVu80BgYrmxiOH5HHUhww/srv@raCYW63wYGB6GGXMCW5TIDVc/08xxbNERqxPd82ZDDUcYk7MWar8fC62MlpxIfUJH5KWlMOBCFfAvWtWSg7GNUCfiYXz1D6asuNBGLxB/Rs/bJIaPp/QRIkheU3jfbuO3TbSLAdWyNWB0xUFOhwp3CF/yqAOUvOFQONQ9At9P413q@zAtoBe2hPXtDZjvimlpAtVWjDcGXeOZs42/ "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 6](https://perl6.org), ~~75 73 71~~ 69 bytes ``` {({S:i/.*(<[aeiou]>).*<-[\W\d_aeiou]><()><![aeiou]>/$0.lc()/}...*eq*).tail} ``` [Try it](https://tio.run/##rZLtatswFIb/6ypOWDZsL1XaDfqj@WBmBFroutB6dNCGIduniVZZci2rSRpy7dmRnZRcwPAnet/z6JwXlVip852zCK/nPBswVqzhU2ZyhNFuE2zuLmSfR8HwQaA0bjYOeTQ8eXi8f8z/7FeGQTgedg56v3vKVRaE/S3nPMKXKOS1kGq7I@y3Gm0NI@hGVzdcSY2WV6Y2VfBlND4LeSHKC9gAfzid9eh9NuPWpbaugq8hbBnzLSYEGLBSCQ2fG9qAPZlqDz4ZQ9CVunR1r4urErMa8xA2DEBa8BPt1bAH7/rRLy8pCbbd3WKBRYoV1AvKxCxR2Q4bjaFZRxIQajxIaLHDWLKgHeimtnAlilIhUN9Sz7kv9KoE/wgtGoMohbdgjWSSc8kZi29g8jv@Mb2ewP1VcgkxXP9M4Nd0Orn9Ht9NICiVs2BNgaBo4yoTFkNPj29EUymmoq2Vl7KtNlTuqB73ACSCO0Jgy2CxzmHhx8pIoiEgipLJXRJF4A2wlPUCzk4/gl0XqVG2r52PxwYfwiaXWItcHAHwQMAEjxhyIVuKXMtCEshY41HOJ2qxof2PIEWa5fg0X8i/z6rQpnypbO1el6v1m0eIVGSCdJwjOeSzVNQMucyLqaghcrqlW7m1e3MUDJS6gFTrZkwoaddCQEofLahXVAooS/kEa@NAI@ZQmOZ00GH0Y7fnhnx0tU75bsV3LzXfurHzDw "Perl 6 – Try It Online") ``` {({S:i{.*(<[aeiou]>).*<-[\W\d_aeiou]><()><![aeiou]>}=$0.lc}...*eq*).tail} ``` [Try it](https://tio.run/##rZLvbtowFMW/@ykuGpuSjHqwSf3QAlo0IbVSy1CbqZNaNDnJLXh17DSOCxTx7Ow6oRUPMOWvfM79@d4jl1ip072zCC@nPDtnrNjAp8zkCKP9Ntjensktj4LhvUBp3Hwc8mh4cv9w95D/OawMg3A87Lzpu1G3z1W245xH@ByFvBZS7fYE/V6jrWEE3ehyypXUaHllalMFX0fjQcgLUZ7BFvh9f96j92DOrUttXQXfQtgx5htMCHDOSiU0fG5o5@zRVAfwyRiCrtSlq3tdXJeY1ZiHsGUA0oKf56CGPXjXj355STmw3f4GCyxSrKBeUiJmhcp22GgMzTqSgFDjm4QWO4wlS9qBbmoL16IoFQL1LfWC@0KvSvCP0KIxiFJ4C9ZIJrmQnLF4CpPf8fXsagJ3l8kFxHD1M4Ffs9nk5kd8O4GgVM6CNQWCoo2rTFgMPT2eiqZSzERbKy9kW22o3FE9HgBIBHeEwJbBYp3D0o@VkURDQBQlk9skisAbYCXrJQz6H8FuitQo@0U7H48NPoRNLrEWuTgC4BsBEzxiyKVsKXIjC0kgY41HOZ@oxYb2P4IUaZbj42Ip/z6pQpvyubK1e1mtN68eIVKRCdJxgeSQT1JRM@Qyz6aihsjpVm7tNu7VUTBQ6gJSrZsxoaRdCwEpfbSgXlEpoCzlI2yMA42YQ2Ga00GH0Y/dnhvy0dU65bsV373UfOvGzj8 "Perl 6 – Try It Online") ``` {({S:i{.*(<[aeiou]>).*<:L-[_aeiou]><()><![aeiou]>}=$0.lc}...*eq*).tail} ``` [Try it](https://tio.run/##rZLvatswFMW/6yluWDZsr9WaDfohTcLMCLSQdaHx2KCUIdu3iVZZci2riRvy7NmVnZQ8wPB/n3N/uvegEit1uXcW4eWSZ1eMFQ18yEyOMN5vg@1iKLc8Ckb3AqVxD5OQR6Ph7Pz@z@F7FISTUe@o7sb9C66yHec8wuco5LWQarcn5NcabQ1j6Ec3t1xJjZZXpjZV8Hk8GYS8EOUQtsDvLx7O6D544Naltq6CLyHsGPPtJQS4YqUSGj62tCv2aKoD@HwCQV/q0tVnfdyUmNWYh7BlANKCn@aghmfwpp@88pJSYLv9HRZYpFhBvaI8zBqV7bHxBNr/SAJCjUcJLfYYS1a0Ap3UFm5EUSoE6lvqJfeFXpXgL6FFaxCl8BaskUxyKTlj8S1Mf8ff57Mp/LpJriGG2Y8Efs7n07tv8WIKQamcBWsKBEULV5mwGHp6fCvaSjEXXa28ll21oXJH9XgAIBHcCQI7Bot1Dis/VkYSDQFRlEwXSRSBN8Ba1isYXLwH2xSpUfaTdj4eG7wL21xiLXJxAsAjARM8YciV7CiykYUkkLHGo5xP1GJL@x9BijTL8XG5kn@fVKFN@VzZ2r2sN82rR4hUZIJ0XCI55JNU1Ay5zLOpqCFyurXbuMa9OgoGSl1AqnU7JpS0aiEgpYcW1CsqBZSlfITGONCIORSm3R20Gf3Y3b4hHx2dU75Z8c1LzXdu7P0D "Perl 6 – Try It Online") ``` {({S:i{.*(<[aeiou]>).*<:L-[_aeiou]><(<![aeiou]>}=$0.lc}...*eq*).tail} ``` [Try it](https://tio.run/##rZLvbtowFMW/@ykuGpuSjHqwSf1AAS2akFqJMVQybVJVTU64Ba@OHeK4QBHPzq4TqHiAKf9zzv353iMXWKrro7MIL9c8u2Es38GHzCwQhsd9sJ/35Z5HweBBoDTucRTyaNCfXD38OX0PgkHrrB2G7S5X2YFzHuE6CnklpDocCfi1QlvBENrR3ZQrqdHy0lSmDD4PR72Q56Lowx74Q/exQ/feI7cutVUZfAnhwJhvLiHADSuU0PCxpt2wJ1OewFcjCNpSF67qtHFbYFbhIoQ9A5AW/CwnNezAm37xygvKgB2O95hjnmIJ1YrSMBtUtsWGI6j/IwkIFZ4ltNhiLFnRCnRSW7gVeaEQqG@pl9wXelWCv4QWtUEUwluwQjLJpeSMxVMY/46/zyZj@HWX3EIMkx8J/JzNxvff4vkYgkI5C9bkCIoWLjNhMfT0eCrqSjETTa28lU21oXJH9XgCIBHcBQIbBov1AlZ@rIwkGgKiKBnPkygCb4CNrFbQ674Hu8tTo@wn7Xw8NngX1rnEWizEBQDPBEzwgiFXsqHIncwlgYw1HuV8ohZr2v8IUqTZAp@WK/n3WeXaFOvSVu5ls929eoRIRSZIxyWSQz5LRc2Qy6xNSQ2R023c1u3cq6NgoNA5pFrXY0JBq@YCUnpoQb2iUkBZyifYGQcacQG5qXcHbUY/drNvyEdH45RvVnzzUvONG1v/AA "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter $_ ( # generate a sequence { # code block used to generate the values S # substitute (not in-place) :i # :ignorecase { .* # start at end of string ( <[aeiou]> ) # store the previous vowel in $0 .* <:L - [_aeiou]> # letter other than a vowel <( # ignore everything before this # this is where `$0.lc` gets inserted # )> # ignore everything after this <![aeiou]> # not a vowel (zero width lookahead) } = $0.lc # replace with lowercase of the earlier vowel } ... # keep generating until: * eq * # there are two equal strings (no changes) ).tail # get the last value } ``` [Answer] # [Python 3](https://docs.python.org/3/), 125 bytes ``` lambda s,v='[^aeiouAEIOU':sub(f'(?<={v}\W\d])(?={v}]|$)',lambda m:sub(f'{v}]','',s[:m.end()])[-1:].lower(),s) from re import* ``` [Try it online!](https://tio.run/##bdJtb5swEADg7/kVR7cJiFjWat@ioQpNSK3ULVFK1UlJJplwBK/Yphjndf3t2QFZlpWSIJLj7Ds/drGtMiU/H1J/dsiZiBMG2lv59vQnQ65MEN6OHuyhNrGT2s71F3@/epk9zpK561zXv@e/37u2dxwojnl13PZs29PToRigTBx37k4/Xg3ng1ytsXRcT7u9tFQCSgQuClVW/YMq@ZJLlmvwwbGD7xD@CL6N70J4vI1uIIC7UQQP43E4@Rrch@AUudGglUBo5lwwjdRJD84vO5AJZEhFFpSogUG/H4X3Ub8PdT6seZXB1eUH0FsRq1x/kkbEWGrnnWt15ooyroG@TAJumChyBF2VXC4HnVQWLxJMlxn/9ZQLqYrnUldmtd5sd90OoZACYim79TDPgZbHU9gqAxIxAaFoLRXqqulfW7bbw02Bi4retWqsYWNj1sLxG97SKbIzhIdHPSQ@c@aHbwGSH6N9/SeIfwkxwjNEnvGWkW@54CSptKotDWHSoDc4G00O9c0ka0BZwWpSrJBQ6Si8ZiVVtmDkikskWf7EcypGuupZlVSQhM3abMzW7ExnHVBQGcEgpodknWYwp0@LzU/aeOKmnlpwrMVTVUJ9WD1quwAuYccL53R6m2izI@6wqUL7V@f5PqRN1jFMV0ELrZz0Yl@HrfIFyEBDpWBPA@r/TJ8mu3CbUZhr7Iy3LCucTEYTer6eajiT@2NZis4kl7pCloBK6UVbZSb/K3P4Aw "Python 3 – Try It Online") Python 3.6 allows us to (ab)use [f-strings](https://www.python.org/dev/peps/pep-0498/) to reuse our set of vowels (and for four more characters saved, the beginning of an inverted regex character class) cheaply (a `f` prefix on each string, then `{v}` as needed, instead of the `'+v+'` you'd need with concatenation, or the `[^aeiouAEIOU` you'd insert literally. The regex that matches no characters, just a position, avoids issues with the non-overlapping matches normal regexes require, and removes the need to backreference any part of the match; all we use the match object for is to get the slice index we use to find the prior vowel. Partially de-golfed, it would be something like: ``` import re def get_last_vowel(string): ''' Returns the lowercase version of the last vowel in a string if the string contains any vowels, otherwise, return the empty string ''' try: *restvowels, lastvowel = re.sub(r'[^aeiouAEIOU]', '', string) except ValueError: lastvowel = '' # No vowels in string return lastvowel.lower() def rememebere_tehe_vowelese(string): '''Inserts the lowercased last vowel seen after any consonant not followed by a vowel''' return re.sub(r'(?<=[^aeiouAEIOU\W\d])(?=[^aeiouAEIOU]|$)', lambda match: get_last_vowel(string[:match.end()]), string) ``` [Answer] # TSQL, 500 bytes ``` CREATE TABLE i (i CHAR(999)); INSERT i VALUES ('The rain in Spain stays mainly in the plain') DECLARE @w CHAR(999)=(SELECT i FROM i),@r VARCHAR(999)='';WITH d(n,c,i,q)AS(SELECT n,SUBSTRING(@w,n,1),CHARINDEX(SUBSTRING(@w,n,1),'AEIOUaeiou'),CHARINDEX(SUBSTRING(@w,n,1),'BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz')FROM(SELECT DISTINCT number n FROM master..[spt_values]WHERE number BETWEEN 1 AND LEN(@w))D)SELECT @r=@r+f.c+LOWER(COALESCE(CASE WHEN f.q<>0 AND COALESCE(d2.i,0)=0 THEN SUBSTRING(@w,(SELECT MAX(n)FROM d WHERE i<>0 AND n<f.n),1)END,''))FROM d f LEFT JOIN d d2 ON f.n=d2.n-1 SELECT @r ``` Table `i` is used for [input](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341) [Answer] # SWI-Prolog, 593 bytes ``` a(S,D):-atom_chars(S,D). g(_,[],_,-1). g(E,[E|_],R,R). g(E,[_|T],I,R):-N is I+1,g(E,T,N,R). c(A,E):-g(E,A,0,R),R > -1. v(X):-a('AEIOUaeiou',X). c(X):-a('BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz',X). d([_],_,R,R). d([H|T],_,I,R):-v(V),c(V,H),!,d(T,H,I,[H|R]). d([H,N|T],V,I,R):-c(C),c(C,H),v(W),c(W,N),!,d([N|T],V,I,[H|R]). d([H,N|T],V,I,R):-c(C),c(C,H),v(W),\+c(W,N),string_lower(V,LV),!,d([N|T],V,I,[LV,H|R]). d([H|T],V,I,R):-!,d(T,V,I,[H|R]). r([],Z,Z). r([H|T],Z,A):-r(T,Z,[H|A]). r(S,D):-r(S,D,[]). m(X,R):-a(X,O),r(O,P),r([''|P],Q),d(Q,'',I,[]),r(I,J,[]),atomic_list_concat(J,R). ``` Used only built-in predicates (without regex or list manipulating library). Usage: ``` ?- m('A pnm bnn'). 'A panama banana' true . ``` [Answer] # [Haskell](https://www.haskell.org/), ~~142~~ 130 bytes ``` ""& import Data.Char v=(`elem`"aeiouAEIOU") s&(x:y:z)|v y=x:s&(y:z) s&(x:y)|v x=x:[toLower x]&y|isAlpha x=x:s++s&y|1>0=x:s&y _&x=x ``` [Try it online!](https://tio.run/##LZBfS@NQEMXf76c4VrckFbv6WqgQakChrkEjCruL3qaT5ur9k83ctIn42Y23ZWEe5vwOwxxOJfmdtB6O11QqSyjxZxiNxkKZ2jUeV9LL6aKSjdjOo1fSZF5HkpRrk/Tm7nEUCx5H3ayffcSfW/Tzbhb0Xv3ne9oF@tu7pdtRg@7vuP9UnOi6kgeHT085oIvL88NxL17GPOfBSGUxh7KeGll4nKC1OuRjTGFkjaiMw3YgQ/IL6XNymy1TPN3k10iwvMvxmGXp/SJ5SBHVumWwMwS9D1FIplgkdo2KGkIRDIbEZJKnD/lkgr2PnfIVLs5/gHuzcpp/2tasqOHoOD4SeaUYYaQFddLUmsC@UXYzFXJVhCY3lXp718a6@l/Dvt3uuv5DJKitwcpakYfGEeKoEr1rYYnWMC5k8cT@8J@PvopSyw0PZ8@LLPsG "Haskell – Try It Online") The initial `""&` is a partial application of the `(&)` function defined later on, and is placed so oddly to make TIO count the bytes in `""&`, but not count the bytes that, in a full program, would be needed to assign that to any named value. --- Less golfed: ``` import Data.Char (isAlpha, toLower) vowel :: Char -> Bool vowel = (`elem`"aeiouAEIOU") replace :: String -> String replace = go "" -- start by carrying no extra vowel where go _ "" = "" -- special case for "anything followed by vowel" so later cases can ignore next character go s (x:y:more) | vowel y = x : go s (y:more) go s (x:xs) | vowel x = x : go [toLower x] xs -- update the vowel we're carrying | isAlpha x = x : s ++ go s xs -- non-vowel letter not followed by a vowel | otherwise = x : go s xs -- some non-letter junk, just include it and carry on ``` There really ought to be a way to do this more concisely with a fold instead of recursion, but I couldn't figure it out. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 34 bytes ``` vyžMylåil©1V}žPylåžM¹N>èå_Y&&i®«}J ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/rPLoPt/KnMNLM3MOrTQMqz26LwDEAwoe2ulnd3jF4aXxkWpqmYfWHVpd6/X/f0hqTo5CbqpCZppCZX6pQl5qaopCbn5RqkJJanGJQnJicWqxIgA "05AB1E – Try It Online") --- I take that back I can only shave 3 bytes off this monstrosity... I think I could shave the boolean down, but there MUST be 3 cases. 1 for vowels. 1 for consonants. 1 for the case that a digit/symbol exists. --- ``` v # For each... y # Push current element. žM # Push lower-case vowels (aeiou). ylå # Lower-case current element is vowel? i©1V} # If so, put it in register, set Y to 1. žP # Push lower-case consonants (b...z) ylå # Is current char a consonant? žM¹N>èå_ # Push vowels again, is input[N+1] NOT a vowel? Y # Did we ever set Y as 1? && # All 3 previous conditions true? i®«} # Concat the current vowel to the current char. J # Join the whole stack. # '}' isn't needed here, b/c it's implied. # Implicit return. ``` [Answer] # Powershell, 104 bytes based on [Neil's regular expression](https://codegolf.stackexchange.com/a/166373/15968). ``` [regex]::Replace($args,'(?i)(?<=([aeiou]).*?[^\W\d_aeiou])(?![aeiou])',{"$($args.Groups[1])".ToLower()}) ``` save it as `get-rememebere.ps1`. Script for testing: ``` $test = @" AN EXAMPLE WITH A LOT UPPERCASE (plus some lowercase) And here comes a **TEST** case with 10% symbols/numbers(#)! This is an example string. abcdefghijklmnopqrstuvwxyz A pnm bnn Tell me if you need more test cases! "@ $expected = @" ANa EXAMaPaLE WITiHi A LOTo UPuPEReCASE (pelusu some lowerecase) Anada here comese a **TESeTe** case witihi 10% siyimiboloso/numuberese(#)! Thisi isi ana examapale seterinigi. abacadefegehijikiliminopoqorosotuvuwuxuyuzu A panama banana Telele me ifi you neede more tesete casese! "@ $result = .\get-rememebere.ps1 $test $result -eq $expected $result ``` [Answer] # [Red](http://www.red-lang.org), 276 bytes ``` func[s][v: charset t:"AEIOUaeiou"c: charset u:"BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"b: parse s[collect[any keep[thru c opt v]keep thru end]]p:""foreach c b[either find t e: last c: to-string c[p: e][parse c[any[copy p v | skip]]if find u e[append c lowercase p]]prin c]] ``` [Try it online!](https://tio.run/##TVHLbtswELz7KyYqCiQG@rrqpqRqk9ZJXFtp0hI8UNQqUi2RrEjZUdt8u7NSgMYAD8Q@ZmZnOir2KyqEnJXxvuyNFl6KbQxdqc5TQIijJL24vlFU2z7SL40@jk7PPn76fP7l6@Lyavlttc6@3979@Jnroryvfm2a1rjfnQ/b3cPwJ8rjmRv34IW2TUM6CGUGbIicCFXXQ8O6gK0cK5gqZAopXRxFpe1I6Qp6lguqQ0UdytoUCKAYjfIBLCvYNz50tbmHFi4GSfHMp0ce5nQDHLb4B7@pnZR1@YzBNEI5x1wM39gddVrxFk84BoOWcj9@Akr8Ta6Q3iWXy0WK24vsHAkW1xlulst0dZasUxy7pvfwtiX8Rzp5nL3sMwmLZ0084qEwn2fpOpvPMXHu@DR8eP8afmhz2/h3pm9z6vzxq5OjA5Ssqj34KQN6UK1r2NPp8LcHQ4pTII6hnnKwUxD9lMShHjjTIjfmEJ2aBnwA@zPYHoaoQMv@I9DoM@v0R4/7Jw "Red – Try It Online") Readable: ``` f: func [ s ] [ v: charset t: "AEIOUaeiou" c: charset u: "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz" b: parse s [ collect [ any keep [ thru c opt v ] keep thru end ] ] p: "" foreach c b [ e: last c: to-string c either find t e [ p: e ][ parse c [ any [ copy p v | skip ] ] if find u e [ append c lowercase p ] ] prin c ] ] ``` [Answer] # [Yabasic](http://www.yabasic.de), 180 bytes A full program which takes input from STDIN and outputs to STDOUT ``` Line Input""s$ x$="AEIOUaeiou" For i=1To Len(s$) c$=Mid$(s$,i,1) ?c$; If InStr(x$,c$)Then v$=c$ Else a=Asc(Upper$(c$)) If a>64And a<91And!InStr(x$,Mid$(s$,i+1,1))Then?v$;Fi Fi Next ``` [Try it online!](https://tio.run/##PY3RCoIwGIXv/6dY47@Y5I0QQdgSLxQEq4v0AdZcNKg5nIo9/VpdCAfOgcP5zkfchdPS@1obRSpjp5FSh7Agp3lRXVuhdD9RKPuBaJ40PamVYQ4jkMjPusOQYx0nEWQSU6gegXEbB7ZgLDFqnsrAjFwiFC@nQPDcSdZaqwZkoY9@A3Ha73LTEXE8JME3K2DFb5Nw8IdlM6alhqCLWkbvBbHmTe7GfAE "Yabasic – Try It Online") ]
[Question] [ You are to write a very small program within 100 characters. Your program must distinguish between masculine and feminine french nouns. The output should be `un` if it is masculine and `une` if it is feminine. Often, there are certain statistical rules you can follow (e.g. if it ends in an "e" it is more likely feminine than masculine). **Input**: A french word; it may consist of any lowercase letters and dashes, including lowercase letters with accents. Example input: `ami` **Output**: `un` if the word is masculine and `une` if the word is feminine. Example output: `un` You do not have to get every word right; your goal is to be as accurate as possible. **Scoring**: Your answer **must** be within 100 characters. Statements such as `print` or `console.log` or `alert` do *not* count as part of your total bytes. You may also write a function or method that performs this task, in which case the first few bytes (e.g. `f=x=>`) which are part of the function declaration do not count to your total. Your total score is the number of incorrect answers. Ties are broken by code size. Nouns to test with: ``` un ami un café un chapeau un concert un crayon un garage un garçon un lit un livre un mari un musée un oncle un ordinateur un pantalon un piano un pique-nique un portable un père un sandwich un saxophone un stade un stylo un théâtre un téléphone un voisin une botte une boum une chaise une chaussette une chemise une clarinette une copine une femme une fille une glace une heure une lampe une maison une montagne une personne une piscine une pizza une radio une raquette une salade une souris une sœur une table une télé une voiture ``` [Answer] # CJam, 0 incorrect, ~~32~~ 29 bytes This code uses a few odd characters (some of them unprintable), but they are all well within extended ASCII range. So again, I'm counting each character as a single byte. ``` "un"'el2b"zPB: ":i+:%2/* ``` Due to the unprintable characters, I'm sure Stack Exchange swallows some, so you might want to copy the code [from the character counter](https://mothereff.in/byte-counter#%22un%22%27el2b%22%C2%85zPB%3A%1A%14%0E%09%04%22%3Ai%2B%3A%252%2F%2a) (it shows bytes with UTF-8 encoding, which is suboptimal for this challenge; also, the link doesn't seem to work in Firefox, but does in Chrome). *A hexdump is provided for reference:* ``` 00000000: 2275 6e22 2765 6c32 6222 7a50 423a 1a14 "un"'el2b"zPB: 00000010: 0e09 0422 3a69 2b3a 2532 2f2a 0a ":i+:%2/*. ``` [Test it here.](http://cjam.aditsu.net/) After some more discussion in chat, we figured that the regex golfing wouldn't bring us much further. So following an earlier (joking) suggestion of mine we started looking into manipulating the character codes of the words with certain functions, such that all words from one group would yield a number with some property that is easy to check. And we got luckier than we expected! Here is what the code does to the words: * Implicitly convert the characters in the word to their code points. * Interpret those as digits in base 2 (yes, the digits will be much larger than 0 or 1, but CJam can handle that). * Repeatedly take the result modulo... the following numbers: `[133, 122, 80, 66, 58, 26, 20, 14, 9, 4]`. This sequence of numbers is itself encoded as the code points of a string (this is where the weird and unprintable characters come in). * As if by magic, all 25 masculine nouns yield `0` or `1`, and all 25 feminine nouns yield `2` or `3` with this procedure. So if we divide this by `2` (integer division) we get zeroes for masculine nouns and ones for feminine nouns. To round it off, we push `"un"` on the stack, the we push a single `e`. Then we read the input word from STDIN and perform the above computation, and finally multiply the `e` by the result. I have never folded modulo onto any list before, and I feel like I never will again... Many thanks for xnor and Sp3000 for throwing ideas around and helping with the search for divisor chain. [Answer] # Ruby, 0 incorrect, ~~63~~ ~~56~~ ~~53~~ ~~52~~ ~~51~~ 50 bytes All characters are in [extended ASCII](http://en.wikipedia.org/wiki/Extended_ASCII), specifically [ISO 8859-1](http://en.wikipedia.org/wiki/ISO/IEC_8859-1), so I'm counting each character as a single byte. ``` f=->s{s[/la|tt|i.e|[égdzœu]..$|^b|^f|so|^ta/]?'une':'un'} ``` It looks like your test set was a bit too short. I've generated the regex with [Peter Norvig's meta regex golfer](http://nbviewer.ipython.org/url/norvig.com/ipython/xkcd1313.ipynb). You can call the above function like `f["ami"]`. You can use this test harness to check all test cases: ``` puts "ami café chapeau concert crayon garage garçon lit livre mari musée oncle ordinateur pantalon piano pique-nique portable père sandwich saxophone stade stylo théâtre téléphone voisin botte boum chaise chaussette chemise clarinette copine femme fille glace heure lampe maison montagne personne piscine pizza radio raquette salade souris sœur table télé voiture".split.map{|s|f[s]+" "+s} ``` [Test it on Coding Ground.](http://www.tutorialspoint.com/execute_ruby_online.php) **Edit:** Using [Peter Norvig's second script](http://nbviewer.ipython.org/url/norvig.com/ipython/xkcd1313-part2.ipynb) I found a different regex, that was actually *one* byte longer, but which I could shorten by *two* bytes by hand. **Edit:** [Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000) set the regex golfer he wrote for my recent regex challenge on it, and found a ~~36~~ ~~35~~ 34 byte regex for me to use. Thanks for that! [Answer] # CJam, 0 errors (~~36~~ ~~32~~ ~~29~~ 28 bytes) ``` {"un"oEb72^"+ÕåWïº"583b2b='e*o}:F; ``` This is a named function, so I'm only counting the inner code. Also, `o` is a print statement, so it doesn't contribute to the byte count. Try the test cases in the [CJam interpreter](http://cjam.aditsu.net/#code=%7B%22un%22oEb72%5E%22%2B%C3%95%C3%A5%C2%8EW%C3%AF%C2%BA%22583b2b%3D'e*o%7D%3AF%3B%0A%0AqN%25%7BS%25%7BFSo%7D%2FNo%7D%2F&input=ami%20caf%C3%A9%20chapeau%20concert%20crayon%20garage%20gar%C3%A7on%20lit%20livre%20mari%20mus%C3%A9e%20oncle%20ordinateur%20pantalon%20piano%20pique-nique%20portable%20p%C3%A8re%20sandwich%20saxophone%20stade%20stylo%20th%C3%A9%C3%A2tre%20t%C3%A9l%C3%A9phone%20voisin%0Abotte%20boum%20chaise%20chaussette%20chemise%20clarinette%20copine%20femme%20fille%20glace%20heure%20lampe%20maison%20montagne%20personne%20piscine%20pizza%20radio%20raquette%20salade%20souris%20s%C5%93ur%20table%20t%C3%A9l%C3%A9%20voiture). ## How it works ``` "un"o " Print 'un'. "; Eb " Consider the input a base 14 number. "; 72^ " XOR the result with 72. "; "+ÕåWïº" " Push that string. "; 583b2b " Convert from base 583 to base 2. "; = " Retrieve the corresponding element (0 or 1) from the array. "; 'e*o " Print 'e' that many times. "; ``` Just a hash function and a table lookup. [Answer] # [Lexurgy](https://www.lexurgy.com/sc), 18 incorrect, 65 bytes A quick check for whether the word ends with `e`. ``` a: *=>|une/e _ $ else: *=>|un/ _ $ b propagate: []=>*/_ | c: |=>* ``` ]
[Question] [ *Inspired by a [question](https://stackoverflow.com/q/69682156/2586922) (now closed) at Stack Overflow.* Given a square matrix, let its *double trace* be defined as the sum of the entries from its main diagonal and its anti-diagonal. These are marked with `X` in the following examples: ``` X · · X · X X · · X X · X · · X ``` ``` X · · · X · X · X · · · X · · · X · X · X · · · X ``` Note that for odd `n` the central entry, which belongs to both diagonals, is counted only once. ### Rules * The matrix size can be any positive integer. * The matrix will only contain non-negative integers. * Any reasonable input format can be used. If the matrix is taken as an array (even a flat one) its size cannot be taken as a separate input. * Input and output means are [flexible](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) as usual. [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Shortest wins. ### Test cases ``` 5 -> 5 ``` ``` 3 5 4 0 -> 12 ``` ``` 7 6 10 20 13 44 5 0 1 -> 36 ``` ``` 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 -> 32 ``` ``` 23 4 21 5 24 7 0 7 14 22 24 16 4 7 9 12 -> 97 ``` ``` 22 12 10 11 1 8 9 0 5 17 5 7 15 4 3 5 3 7 0 25 9 15 19 3 21 -> 85 ``` Inputs in other formats: ``` [[5]] [[3,5],[4,0]] [[7,6,10],[20,13,44],[5,0,1]] [[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]] [[23,4,21,5],[24,7,0,7],[14,22,24,16],[4,7,9,12]] [[22,12,10,11,1],[8,9,0,5,17],[5,7,15,4,3],[5,3,7,0,25],[9,15,19,3,21]] ``` ``` [5] [3 5; 4 0] [7 6 10; 20 13 44; 5 0 1] [4 4 4 4; 4 4 4 4; 4 4 4 4; 4 4 4 4] [23 4 21 5; 24 7 0 7; 14 22 24 16; 4 7 9 12] [22 12 10 11 1; 8 9 0 5 17; 5 7 15 4 3; 5 3 7 0 25; 9 15 19 3 21] ``` ``` [5] [3,5,4,0] [7,6,10,20,13,44,5,0,1] [4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4] [23,4,21,5,24,7,0,7,14,22,24,16,4,7,9,12] [22,12,10,11,1,8,9,0,5,17,5,7,15,4,3,5,3,7,0,25,9,15,19,3,21] ``` [Answer] # [APL (Dyalog 18.0)](https://dyalog.com), ~~17~~ 16 [bytes](https://github.com/abrudz/SBCS) −1 thanks to Vadim Tukaev. Anonymous lambda. ``` {≢⍸⍵×∨∘⌽⍨∘.=⍨⍳≢⍵} ``` [Try it online!](https://tio.run/##bY4hTwNBFIQ9v6KuZhruvb3tcgKFAQRNerjLiSZ3rWkAgYCQqiZNId0GBAGNOkGCABJMTftP3h853i2OnNnMfjM7s6Oraa@4HU0vJ73y5rq8KMqiru/k/k38j/jv3YssK1m@ymojvjrc31biP8V/qTWrx7J4FL@Wh7n4d4XbDyOLJ1k/p8MjPc@PT9J63PlDp@ngrJtlNs@7e/@Ygc2RxYhaPIc@KFKbI5BBHKu0UN2SZfXBFNo4htOYU0kKGQqoH2YcEhC3vWflugYi7Ud2oMEIFuTCqANZHTDhYkI9N1NJwylRxM2vfgE "APL (Dyalog Extended) – Try It Online") `{`…`}` [dfn](https://wikipedia.org/wiki/Direct_function); argument is `⍵`  `⍴⍵` shape (number of rows and columns) in the argument  `⍳` **i**ndices of an array of that size  `=/¨` equality-reduction of each row-column pair (gives identity matrix)  `∨∘⌽⍨` OR with mirrored self (indicates both diagonals)  `⍵×` multiply with argument  `≢⍸` sum (lit. length of list of indices where each index is repeated as many times as its corresponding number in that) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` TżU$Ṭḋ⁸S ``` [Try it online!](https://tio.run/##LY2xEcIwDEX7zEH5C0u2IzwHUPlc0nBZgBIaClbJAOGOjmOQZBHz41Dp6/3T0@U8DNdaj9/3aTe/xnl6LrfpUD@P5T7WmrucYyng8IgFOcBtq6GHOBJ1EI8QGCOYt1qJoNJuNMDYGKMQKgikbzJDguj/RBnphAgtyHt2DhFiTW2QSKdvi29GXe1p5ZKIlL@78gM "Jelly – Try It Online") ``` T -- truthy indices of the argument, since every row is non-empty, this is [1 .. len(z)] żU$ -- zip with its reverse Ṭ -- for each pair of integers, create a list with 1's at those two indices ḋ⁸ -- for each resulting list, take the dot product with the corresponding row vector of the input matrix S -- sum the results ``` [Answer] # [R](https://www.r-project.org/), 47 bytes ``` function(m)sum(m[(z=diag(y<-nrow(m)))|z[y:1,]]) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNXs7g0VyM3WqPKNiUzMV2j0kY3ryi/HCiuqVlTFV1pZagTG6v5P00jN7GkKLNCw9DK0EzHRFOTC0nEyFTHVFPzPwA "R – Try It Online") [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 15 bytes ``` {+//x*|/|:\=#x} ``` [Try it online!](https://ngn.bitbucket.io/k#eJwdjkEOwyAMBO+8YqVeQnsAGwwhVn/Sc94QqWne3iXCBzxe73rfvq+UjueZzu3zfhy/EOzaYUH02pcC84ocQyFcFIKC6gKFofnA/dgbeaGqUdXRINk1QyiubuAvhtGnAwmUeteKzkF3IVCwleaTDYjGsN55DGRxXSC+cpSZJJ2WHWK0Kj6Tp5EazyGTQaAS/3qrKyU=) Useful to have an identity matrix primitive. Explanation: ``` {+//x*|/|:\=#x} =#x / identity matrix with size of x |:\ / append reverse |/ / OR both matrices x* / multiply by original matrix +// / sum all elements ``` [Answer] # [Python 3.10](https://docs.python.org/3.10/), 58 bytes ``` lambda m,i=0:sum(r[i:=i-1]+r[~i]*(~i!=len(m)+i)for r in m) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY69boMwEMd3nsLdTHOJOANxQGLvO7gMVAH1JGyQcSplyYtkyZIufaK8TQ8nnv4fd7_z9Xc-h-_J3e6DaMTn_RSG7eFRj539OnbCAjVZvZys9IbqhrbYbry5UPsuL_TWjL2TNt1QOkxeeEFO2PRF-CA7Tz6I5bwkazuS69cB9rslHMnVieBnu8Bn-59ulOtEGsPZkwtykFymL97t8WdM2baJMTmULZgCsug07AEzDlQGmENRsCyBdWwVJ6AwbqgCNBeaJXKogAPcR5SGClA9NxQrJgIiM8AcuMqgBNQRrAFLRubR5BGoVni15lhxpPjy88__) --- # [Python 3](https://docs.python.org/3/), 62 bytes ``` lambda m:sum(r[i]+r[~i]*(i!=len(m)+~i)for i,r in enumerate(m)) ``` [Try it online!](https://tio.run/##JY1NbsMgEIX3PgXd4WZUebAd6kg5CfXCVbCKZLCFSaRscnXnQZGQ3s/MN9sz/a2hPWZxFT/HMvnf2yT8Zb97GY0bT9G83Pgp3cd1sUH6@vRy9bxG4Qg/CBvu3sYpWVT14fy2xiT2517lmcUFm4fgv/Z0c@FSCTw/JRyzj2mReaIu4RZdSHKWKAEyph/HypiW@pFMR01xms7EDQLVELfUdZA9QZdWISHFZUN1pFFoSEaoCAGfC0rTQKz@NxQUiMQMBplvVA31xLqANXEPZFtMW4Aqw4ec84BI4fIb "Python 3 – Try It Online") ## Explanation ``` lambda m: for i,r in enumerate(m) # iterate m with i = row index and r = row +r[~i]*(i!=len(m)+~i) # add r[len(m) - i - 1] if the index does not equal i r[i] # add r[i] sum( ) # sum numbers generated by the loop ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~36~~ 34 bytes This uses logical indexing. As an index we use an identity matrix of the size of the input and `or` it with it's flipped version. Thanks @LuisMendo for -2 bytes! ``` @(x)sum(x(flip(e=eye(size(x)))|e)) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzuDRXo0IjLSezQCPVNrUyVaM4syoVKK6pWZOqqfk/JbO4QCNNIz8vtVjDFCho/R8A "Octave – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~13~~ 11 bytes This uses logical indexing. As an index we use an identity matrix of the size of the input and or it with it's flipped version, just like in my Octave answer. Thanks @LuisMendo for -2 bytes:) ``` tZyXytPY|)s ``` **Explanation** ``` t push input twice to stack Zy get size of matrix Xy get an identity matrix of that size t duplicate the identity matrix P flip one of the identty matrices Y| logical OR the two identity matrices ) perform (logical) indexing to the original matrix s compute the sum ``` [Try it online!](https://tio.run/##y00syfn/vySqMqKyJCCyRrP4//9oQx0jHWMdE2tTHTMdcx0La0sdQwMdQ0MdQyNrQ2MdQxMdQ1MdQ7NYAA "MATL – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` LÞ□Ḃ⋎*∑∑ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyIiLCIiLCJMw57ilqHhuILii44q4oiR4oiRIiwiIiwiW1sxLDIsM10sWzQsNSw2XSxbNyw4LDldXSJd) ``` Þ□ # Identity matrix of size... L # len(input) ⋎ # OR with... Ḃ # itself reversed * # Multiply by input ∑∑ # Sum ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 42 bytes ``` m->sum(i=1,#m,m[i,i]+m[i,j=#m+1-i]*(i!=j)) ``` [Try it online!](https://tio.run/##HYxBDoIwEEWvUnXTyidhBkolDdzAE5Au2GhqrGlQEz09Tl3N@29@fl7WWF/zdlHjlurp@U46joRDQpojYqjKuY2HVFEdw1HH3XgzZltyvn/1R9WTymt8vAT3JezVRX@MgZrPy0vbAi2s79AEQYce1HhuQC26zlsIlQdLBJM0uYMT6zyJYEik3hc3gPhfZQFZARHIn8Q3sCAnYw5kZacVbP8rbP1QHA0imEIw2w8 "Pari/GP – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` āDδQÂ~*˜O ``` [Try it online!](https://tio.run/##yy9OTMpM/f//SKPLuS2Bh5vqtE7P8f//PzrayFjHRMfIUMc0VifayETHXMdAxxzINAQKGukABQzNgDyQuKWOoVFsLAA "05AB1E – Try It Online") -1 thanks to @KevinCruijssen Wish to have the identity matrix builtin ``` g Length L Range D Dup δ Outer product with Q Equals? Â Bifurcate ~ Bitwise OR * Multiply with input ˜ Flatten O Sum ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 64 bytes ``` ->m{(r=0...l=m.size).sum{|y|r.sum{|x|x==y||x-~y==l ?m[y][x]:0}}} ``` [Try it online!](https://tio.run/##NY7NasMwEITvegpBLy1shHZlWXFB6YMIHdKQ0IIFwSFgxXJf3V3/wR722xlmtnt@5@nmp8MpDe@d10qp1if1@H1dP9TjmYaSS7cufem9z6X0h7/sfSu/Usgx9PFTj@M4BSHfrJAh2BhBMCDNZMAyShkq0Jtg6llwUAPqVSMNaKCqVrLAuHkbN3uJRSDco6gCxx63ErJEwDes9yYHDSBtEcflK7YgDycjhy@@I7s0WEC39zpAy01mZ7P00FbbzCo2fCV@T0R1PV9@hpLKXd7U5dy2Mo1i@gc "Ruby – Try It Online") ``` ->m{ # lambda taking a 2d array and returning diagonal sum (r=0...l=m.size) # range 0..length .sum{|y|r.sum{|x| # sum the result of passing each coordinates x==y||x-~y==l ? # if on diagonals m[y][x]:0 # take value else 0 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~81~~ \$\cdots\$ ~~71~~ 59 bytes ``` i;f(m,l)int*m;{for(i=l*l;--i;)*m+=i%~l&&i%~-l?0:m[i];l=*m;} ``` [Try it online!](https://tio.run/##bVPBbqMwEL3nK0ZIVECMCgaapi7tYbVfkeQQEdNaNaSCSI0a0U9fduwhFHZrgT1@8@bNeAxF@FIUfa9E6VVM@6o@BZW4lMfGU7kOtAhDJfygWubK/dI3NziH@jl6qDZqJ3SO3K7HGKj2qvZ8uCwAhwFOsj3Fmx3kcMk6MUKcoIRBxiBlEE18CflWDO4YxBEDjm@M1DS1dLOb0FOi88QK8dhyOJorS8U5NjgnML6zNETXuOETnWzQ4QanxDGK4XNvyZEVjld2MapUOR0huabjGSkb6trifCg2sFlaymLbwqgVtCS0pLRMe6UpBOncCpouDG55fpfFSR6GBlPlCR5xjdXcG1bxum8CnGXxJhuiOdvzb749r3/hmzkMpvvE6YS9O7x58EwKVR/kGcMiMZiP0KpPeSy9a3L/dgCCERGwXFq2b8Xocxg@iQAqlKNeWM5OTN2gB6/@zzvW1Bw/qCJjPII26dD0R@Z3wllccdQUZ4whDk1/xp7HmvHeYHDpOW7r8gM2DEOeTd8eHJyrDWYONCwNvPPFLLpb/KSzrZ0Jr5udvsUCzS8I2p@3RaJjvO5/O3NVhvAJ3AO4LaZg0LLx4ts8l9PirgHhD2NbfxfYLbr@T1Hq/Uvbhx9/AQ "C (gcc) – Try It Online") *Saved a bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!!* *Saved 12 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!!* Inputs a pointer to a flattened square array and the number of rows (because pointers in C carry no length info). Returns its double trace. [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), ~~132~~ 109 bytes ``` (load library (d L length (d f(q((M)(s(a(trace M)(trace(reverse M)))(*(odd?(L M))(nth(nth M(/(L M)2))(/(L M)2 ``` [Try it online!](https://tio.run/##dY9LjsIwEET3nKKW1Wwm7cSErLgAOYRnEoZIIYBjjcTpM@0oYodkS1Wvqv1Jw/Qah/mxLBzvocM4fMcQXzt2OGPsp990zfrCJ9kKZwamGH56mFkFY//XxzkDEe5577oTz9lxSte80fJrJc7YphauJyqcsES1e1uUwgoeB2GNI5otqXGAFkJXQK1fCT1MbqmXTTgHtWWJQoU2by0PrXO/hnpU@QKP0lwB54VNptoYcSr5q@3HlyTewgMJ7fIP "tinylisp – Try It Online") -23 bytes thanks to DLosc. [Answer] # [Pip](https://github.com/dloscutoff/pip) `-x`, ~~24~~ ~~21~~ 20 bytes ``` YEY#a$+$+a*HV:y+1+Ry ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboVS7IKlpSVpuhZbIl0jlRNVtFW0E7U8wqwqtQ21gyohUlAVNxWjlaKjza3NrA0NYq2jjQysDY2tTUyATFNrIDs2Fm4WAA) The matrix should be given as a command-line argument in the following form: ``` [[7;6;10];[20;13;44];[5;0;1]] ``` Or, [verify all test cases](https://ato.pxeger.com/run?1=dU8xDsIwDNx5xQk6UVWKnaRp2ZFYWBiQqihDFyQkhg4wVIiXsBQheAGfYeYjuAkryuDzXe5sX-_dvnv6aXGYhtv5cTruiurVLJtZm-VZ3s5X20WfU77pk_T-XLCGn8B7G8JYNGyAN1CpdShBShhWIA1jBFoITrJBfNHxH8WvLG4wxXg2cBLiBJKQDCGojA6HGsQ_CwuU8SCSgfCVaAoW5OIWDmQlU8dGx0Qe0-uRp1ooHtcM6dRhSPUL). ### Explanation ``` YEY#a$+$+a*HV:y+1+Ry #a Size of the matrix EY Identity matrix of that size Y Yank into the y variable Ry y reversed (backward identity matrix) 1+ Add 1 to each value y+ Add to y (identity matrix) HV: Each value halved (rounded down) This creates a matrix where both diagonals are 1's and everything else is 0's a* Multiply the input matrix itemwise by the 1/0 matrix $+ Fold on addition (sum each column) $+ Fold on addition (sum that list of sums) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-mx`](https://codegolf.meta.stackexchange.com/a/14339/), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` gV +J´gUhVT ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW14&code=Z1YgK0q0Z1VoVlQ&input=WwpbMjIsMTIsMTAsMTEsIDFdClsgOCwgOSwgMCwgNSwxN10KWyA1LCA3LDE1LCA0LCAzXQpbIDUsIDMsIDcsIDAsMjVdClsgOSwxNSwxOSwgMywyMV0KXQ) ``` gV +J´gUhVT :Implicit map of each row U at 0-based index V in implicit input array gV :Index V into U + :Add J : Initially -1 ´ : Postfix decrement g : Index into UhV : U with the character at index V replaced with T : 0 :Implicit output of sum of resulting array ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` IΣEθΣΦι∨⁼κμ⁼⁺κμ⊖Lθ ``` [Try it online!](https://tio.run/##PcjLCsIwEIXhV8lyhCM0qaEWl15WigWXIYtQgy2m1aaprx9TkQ5nMd9fN8bXL@NirHzbB9qbMdBt6uhi3jSAze@pdcF6asGuno7DZNxIT7BuBfZX5aYlHWztbWf7YO90tv0jNDSsltvFqJQSAjwtA@fgGmqLEhkkeJEgUYBLbJD/kCdmEDKhnDsvUxJcax3XH/cF "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Filters out elements not on either main diagonal, then takes the sum. ``` θ Input matrix E Map over rows ι Current row Φ Filtered where κ Row index ⁼ Equals μ Column index ∨ Logical Or κ Row index ⁺ Plus μ Column index ⁼ Equals θ Input matrix L Length ⊖ Decremented Σ Take the sum Σ Take the sum I Cast to string Implicitly print ``` [Answer] # [Raku](http://raku.org/), 43 bytes ``` {sum .kv.flatmap:{@^v[unique $^k,@v-$k-1]}} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/urg0V0Evu0wvLSexJDexwKraIa4sujQvs7A0VUElLlvHoUxXJVvXMLa29n9xYqVCmka0jbmCmYKhgZ2OjZGBgqGxgokJkGmqAGTbxWr@BwA "Perl 6 – Try It Online") A function which takes its input in `$_` as a list-of-lists. * `.kv` returns an interleaved sequence of each row's index and the row, ie: `0`, the first row, `1`, the second row, etc. * `.flatmap: { ... }` passes the key and value to the brace-delimited anonymous function and flattens the return values. That function takes the index of each row in `$k` and the row itself in `@v`, each argument declared with a "twigil" `$^`/`@^` on its first lexical appearance. * `$k` and `@v - $k - 1` are the indices of the elements of each row that go into the double trace. `@v`, the row, evaluates to its number of elements in a numerical context (the subtraction operator). * `unique` selects only the unique indices. This eliminates the double index at the center of the matrix, if it has an odd dimension. * `@v[...]` is a slice that returns the row elements at the unique indices. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 18 bytes ``` s.e+@bk&-hyklb@_bk ``` [Try it online!](https://tio.run/##JY3BCsIwEETv/obgxalkN0ljD0IvfoDnUISiUKnYQnvpzxsn8bLMvmHfzts6pP3ldk3L6Xls@/FQDdv47tt7P6YUu12MvsvTwneIDqZsATXEEKiBWDjH6MFcWiWBSrlQh8AiMAqhgkDqogpoIPq/UCYaIUIH4pmVgYeEIg4QT6Utiy1CzfImc2mIlJ@/07y@ps@SqscP "Pyth – Try It Online") ## Explanation ``` s.e+@bk&-hyklb@_bk .e # Iterate through implicit input with (b = row, k = index) @bk # b[k] &-hyklb # if ((2 * k) + 1) - len(b) != 0 + @_bk # plus b[::-1][k] s # sum results from the iteration ``` The `((2 * k) + 1) - len(b)` is derived from rearranging `k - (len(b) - (k + 1))` [Answer] # JavaScript (ES6), 51 bytes ``` m=>m.reduce((t,r,i)=>t+r[i]+r.reverse(r[i]=0)[i],0) ``` [Try it online!](https://tio.run/##bY7BDoIwEETvfkkbRtJdqJUD/kjDgUA1GBRTkN/HpUfDZTM7M9m3z3Zt5y4On@X8nvqw3evtVd9eeQz9twtKLYgYdH1bsuiHJosSrCHOQe1rbbRMGL1103uexpCP00Pdlfe2abQ@/bsFbANfwhymDheQkQIbUIGyFGkh@rDN0gBTusglnBSdSBKTIQZdEsqhAvHxBZZEiCASBvxVqgYW5BLYgawgirQUCcA7rNp9qsTi9Nn2Aw "JavaScript (Node.js) – Try It Online") ### Commented ``` m => // m[] = matrix m.reduce( // reduce(): ( t, // t = sum r, // r[] = current row i // i = row index, used as a column index ) => // t + r[i] + // add r[i] to t r.reverse( // reverse r[] ... r[i] = 0 // ... but only once r[i] has been cleared // so that it's not counted twice )[i], // add r[i] again 0 // start with t = 0 ) // end of reduce() ``` --- # JavaScript ES2022, 46 bytes Suggested by [@tsh](https://codegolf.stackexchange.com/users/44718/tsh): ``` m=>m.reduce((t,r,i)=>t+r[i]+r.at(~i,r[i]=0),0) ``` (Doesn't work on TIO.) ]
[Question] [ *Disclaimer: This is heavily inspired by ["Polyglot the OEIS!"](https://codegolf.stackexchange.com/questions/137846/polyglot-the-oeis) but fixes the problem that lead to closure (see the output section) and was re-posted as to not invalidate answers.* ## Introduction We all know and love the *on-line encyclopedia of integer sequences* ([OEIS](https://oeis.org/)). So what if we made an *off-line* version of the interesting sequences? Well, that would be kinda too easy, wouldn't it and how would you select a sequence with our standard interface!? No. We need an easier solution to this. A polyglot! ## Input Your input will be a non-negative integer `n`. ## Output Your output will either be * The `n`-th entry of an OEIS sequence OR * The first `n` entries of an OEIS sequence. You may take the index to be 1-based or 0-based as you prefer. To not make this question a duplicate of *[The versatile integer printer](https://codegolf.stackexchange.com/q/65641/55329)* **constant sequences are banned.** This should also increase the difficulty level of submissions and avoid "boring" solutions ;) A sequence is non-constant if there exist two sequence members that are unequal. ## Uhm, so where is the Challenge? You have to polyglot the above functionality. That is if you support languages A, B and C all must implement different OEIS sequences. The choice of sequence is not limited except that you need different ones for all languages. That is, if you run the provided program in language A, then sequence X shall be generated, if you run the provided program in language B, then sequence Y shall be generated (with X!=Y) and if you run the provided program in language C, then sequence Z shall be generated (with X!=Z && Y!=Z). ## Who wins? The answer with the most sequence/language pairs wins. First tie-breaker is code-size (in bytes) with lower being better. Second tie-breaker is submission time with earlier being better. ## Any final Words / Rules? * You must declare which language will generate which sequence. * [Standard I/O rules apply.](https://codegolf.meta.stackexchange.com/q/2447/55329) * If different encodings are used between languages, both programs must use the same byte-sequence. * Language (Python 2/3) revisions *do* count as different languages. Different implementations of a language (such as Browser JS vs Node.js) also count as different languages. * [Standard loopholes apply.](https://codegolf.meta.stackexchange.com/q/1061/55329) [Answer] # 3 languages (1 byte) - [Pyth](https://pyth.readthedocs.io) ([A001477](https://oeis.org/A001477)), [MATL](https://github.com/lmendo/MATL) ([A000027](https://oeis.org/A000027)), [Braingolf](https://github.com/gunnerwolf/braingolf) ([A000217](https://oeis.org/A000217)) ``` Q ``` * **[Try Pyth online!](https://tio.run/##K6gsyfj/P/D/fxMA)**, 0-indexed (non-negative integers) * **[Try MATL online!](https://tio.run/##y00syfn/P/D/fxMA)**, 0-indexes (positive integers) * **[Try Braingolf online!](https://tio.run/##SypKzMxLz89J@/8/8P///yYA)**, 1-indexed (triangular numbers) --- # How? `Q` does the following: * In MATL, it means `+ 1`, so it basically evaluates to `input + 1`. * In Pyth, it means input, so it just outputs the input. * In Braingolf, it is the built-in for triangular numbers. ## Mini-polyglot **[Pyth](https://tio.run/##K6gsyfj/P/D/fxMA)** can be replaced by any of the following languages: **[GolfScript](https://tio.run/##S8/PSStOLsosKPn/P/D/f0MA)**, **[Pyke](https://tio.run/##K6jMTv3/P/D/fxMA)**, **[Brachylog](https://tio.run/##SypKTM6ozMlPN/r/P/D/f@P//gA)** or **[Brain-Flak](https://tio.run/##SypKzMzTTctJzP7/P/D/f0MA)**. [Answer] # 10 languages, 122 bytes ``` #|A=1:0;~@}{\,[.,];oi #coding:utf-8 print (0 and gets.to_i-1 or int(input())**(2+(1/2>0)));quit()#⎚I±N» # x #x%:+. ``` I definitely can add a bunch more. 1-indexed unless otherwise specified. Note that I may not be up-to-date on TIO links when I'm sure newer changes didn't affect older programs - you can test them if you want to, but copying 10+ new TIO links every time I make a change gets tiring after a bit. I'll copy new ones every 5 updates or so. # cQuents v0, [A000007](https://oeis.org/A000007) Relevant code: `#|A=1:0;` `#|A` catches the input and is there for Python comments. `=1` means the first item is `1`, `:0` mean the rest are `0`, outputs the `n`th term given input `n`. cQuents v0 has a weird bug/feature that when an unexpected but valid token, such as `;`, is read, it causes parsing to end. [Try it online!](https://tio.run/##Sy4sTc0rKf7/X7nG0dbQysC6zqG2OkYnWk8n1jo/k0s5OT8lMy/dqrQkTdeCq6AoM69EA4ILSks0NDW1tDSMtDUM9Y3sDDQ1Na0LSzOBosqP@ma937Py0Mb3e9Yd2v3/v6EBAA "cQuents – Try It Online") # PingPong, [A001478](http://oeis.org/A001478) Relevant code: `#|A=1:0;~@` ***Outputs via exit code.*** 0-indexed. `#` skips the next char. `=` does nothing here. `1` pushes `1`, and `:` prints `1` to STDOUT. `0` pushes `0`. `)` does nothing. `;` pushes input, `~` pops and pushes `-n-1`. `@` terminates. The exit code is the top of the stack. [Try it online!](https://tio.run/##K8jMSy/Iz0v//1@5xtHW0MrAus6htjpGJ1pPJ9Y6P5NLOTk/BajEqrQkTdeCq6AoM69EA4ILSks0NDW1tDSMtDUM9Y3sDDQ1Na0LSzOBosqP@ma937Py0Mb3e9Yd2v3/v6EBAA "PingPong – Try It Online") # axo, [A001477](http://oeis.org/A001477) Relevant code: `}{\` 0-indexed. `}` reads and pushes an integer from STDIN (requires trailing newline for some reason), `{` prints an the top of stack, and `\` ends the program. I'm not sure what the preceding characters do, but nothing that matters in this case. [Try it online!](https://tio.run/##S6zI//9fucbR1tDKwLrOobY6RidaTyfWOj@TSzk5PyUzL92qtCRN14KroCgzr0QDggtKSzQ0NbW0NIy0NQz1jewMNDU1rQtLM4Giyo/6Zr3fs/LQxvd71h3a/f@/oQEXAA "axo – Try It Online") # brainfuck, [A000027](https://oeis.org/A000027) Relevant code: `,[.,]` Simple cat program from esolangs.org. Outputs the input. [Try it online!](https://tio.run/##SypKzMxLK03O/v9fucbR1tDKwLrOobY6RidaTyfWOj@TSzk5PyUzL92qtCRN14KroCgzr0QDggtKSzQ0NbW0NIy0NQz1jewMNDU1rQtLM4Giyo/6Zr3fs/LQxvd71h3a/f@/oQEA "brainfuck – Try It Online") # ><>, [A000030](https://oeis.org/A000030) Relevant code: `#` ... `;oi` `#` mirrors and wraps to the right, which direct it to read `io;`, which outputs the first character of the input. 0-indexed. [Try it online!](https://tio.run/##S8sszvj/X7nG0dbQysC6zqG2OkYnWk8n1jo/k0s5OT8lMy/dqrQkTdeCq6AoM69EA4ILSks0NDW1tDSMtDUM9Y3sDDQ1Na0LSzOBosqP@ma937Py0Mb3e9Yd2v3/v6EBAA "><> – Try It Online") # Ruby, [A023443](https://oeis.org/A023443) Relevant code: `print (0 and gets.to_i-1` ... `)` 0-indexed. Prints the input minus 1. `0` is truthy in Ruby, but falsey in Python. [Try it online!](https://tio.run/##KypNqvz/X7nG0dbQysC6zqG2OkYnWk8n1jo/k0s5OT8lMy/dqrQkTdeCq6AoM69EQcNAITEvRSE9taRYryQ/PlPXUCG/SAEoo5GZV1BaoqGpqaWlYaStYahvZGegqalpXViaCRRVftQ36/2elYc2vt@z7tDu//@NDAA "Ruby – Try It Online") # Python 3, [A000578](http://oeis.org/A000578) Relevant code: `print (0 and gets.to_i-1 or int(input())**(2+(1/2>0)));quit()` Ripped off of HyperNeutrino's original post, but it's a pretty well-known polyglot. `quit()` ends the program. [Try it online!](https://tio.run/##K6gsycjPM/7/X7nG0dbQysC6zqG2OkYnWk8n1jo/k0s5OT8lMy/dqrQkTdeCq6AoM69EQcNAITEvRSE9taRYryQ/PlPXUCG/SAEoo5GZV1BaoqGpqaWlYaStYahvZGegqalpXViaCRRVftQ36/2elYc2vt@z7tDu//@NDAA "Python 3 – Try It Online") # Python 2, [A000290](https://oeis.org/A000290) Relevant code: ``` #coding:utf-8 print (0 and gets.to_i-1 or int(input())**(2+(1/2>0)));quit() ``` `#coding:utf-8` is required for the Charcoal stuff to work. Also ripped off of HyperNeutrino's original post. `quit()` ends the program. [Try it online!](https://tio.run/##K6gsycjPM/r/X7nG0dbQysC6zqG2OkYnWk8n1jo/k0s5OT8lMy/dqrQkTdeCq6AoM69EQcNAITEvRSE9taRYryQ/PlPXUCG/SAEoo5GZV1BaoqGpqaWlYaStYahvZGegqalpXViaCRRVftQ36/2elYc2vt@z7tDu//@NDAA "Python 2 – Try It Online") # Charcoal, [A001489](https://oeis.org/A001489) Relevant code: `⎚I±N»` 0-indexed. `⎚` clears the console (Charcoal prints ASCII as-is) and `I±N` prints the negative of the input. `»` is a parse error and terminates the program. Thanks to ASCII-only for help in chat. [Try it online!](https://tio.run/##S85ILErOT8z5/1@5xtHW0MrAus6htjpGJ1pPJ9Y6P5NLOTk/JTMv3aq0JE3XgqugKDOvREHDQCExL0UhPbWkWK8kPz5T11Ahv0gBKKORmVdQWqKhqamlpWGkrWGob2RnoKmpaV1YmgkUVX7UN@v9npWHNr7fs@7Qbi5lhQou5QpVK229//8NAQ "Charcoal – Try It Online") # Cardinal, [A020725](https://oeis.org/A020725) Relevant code: ``` x x%:+. ``` Adds 1 to the input, and squashes all other pointers. [Try it online!](https://tio.run/##S04sSsnMS8z5/1@5xtHW0MrAus6htjpGJ1pPJ9Y6P5NLOTkfKJ9uVVqSpmvBVVCUmVeioGGgkJiXopCeWlKsV5Ifn6lrqJBfpACU0cjMKygt0dDU1NLSMNLWMNQ3sjPQ1NS0LizNBIoqP@qb9X7PykMb3@9Zd2g3l7JCBZdyhaqVtt7//4YA "Cardinal – Try It Online") [Answer] # 5 languages ([05AB1E](https://github.com/Adriandmen/05AB1E), [Actually](https://github.com/Mego/Seriously), [CJam](https://sourceforge.net/p/cjam), [Jelly](https://github.com/DennisMitchell/jelly), [MATL](https://github.com/lmendo/MATL)), 7 bytes ``` UD>li)+ ``` Try it online!: * [**05AB1E**](https://tio.run/##MzBNTDJM/f8/1MUuJ1NT@/9/QwsA): sequence [A000027](https://oeis.org/A000027) (positive integers: *a*(*n*) = *n*; 1-based) * [**Actually**](https://tio.run/##S0wuKU3Myan8/z/UxS4nU1P7/39TEwA): sequence [A023443](https://oeis.org/A023443) (non-negative integers including 1: *a*(*n*) = *n*−1; 0-based) * [**Cjam**](https://tio.run/##S85KzP3/P9TFLidTU/v/f1MA): sequence [A020725](https://oeis.org/A020725) (positive integers excluding 1: *a*(*n*) = *n*+1; 1-based) * [**Jelly**](https://tio.run/##y0rNyan8/z/UxS4nU1P7////pgA): sequence [A005843](https://oeis.org/A005843) (non-negative even numbers: *a*(*n*) = 2\**n*; 0-based) * [**MATL**](https://tio.run/##y00syfn/P9TFLidTU/v/fxMA): sequence [A000290](https://oeis.org/A000290) (squares: *a*(*n*) = *n*2; 1-based). Exits with an error after producing the output. [Answer] # 3 languages: Proton, [A000583](http://oeis.org/A000583); Python 3, [A000578](http://oeis.org/A000578); Python 2, [A000290](https://oeis.org/A000290) ## [Proton](https://github.com/alexander-liao/proton), 49 bytes ``` print(int(input())**(2+(1/2>0)+((''',''')!=','))) ``` [Try it online!](https://tio.run/##KyjKL8nP@/@/oCgzr0QDggtKSzQ0NbW0NIy0NQz1jewMNLU1NNTV1XWAWFPRFkhramr@/28KAA "Proton – Try It Online") ## [Python 3](https://docs.python.org/3/), 49 bytes ``` print(int(input())**(2+(1/2>0)+((''',''')!=','))) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EA4ILSks0NDW1tDSMtDUM9Y3sDDS1NTTU1dV1gFhT0RZIa2pq/v9vCgA "Python 3 – Try It Online") ## [Python 2](https://docs.python.org/2/), 49 bytes ``` print(int(input())**(2+(1/2>0)+((''',''')!=','))) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EA4ILSks0NDW1tDSMtDUM9Y3sDDS1NTTU1dV1gFhT0RZIa2pq/v9vCgA "Python 2 – Try It Online") # Explanation Proton doesn't have `'''...'''` strings, so `(''',''')` becomes `('' ',' '')`, which somehow doesn't cause issues. It evaluates to `''`, making `(''',''')!=','` evaluate to `True`. Python does have these strings, so `(''',''')` is just `','` so `(''',''')!=','` evaluates to `False`. Python 2 uses floor division for integers, so `1/2>0` is false in Python 2 and true in Python 3. [Answer] ## 5 Languages, 107 bytes ``` s=1/2;1//2;q=int(input())*([2,3][s>0]);"""/.__id__;' alert(+prompt()+1);`"""#=;#';q=gets print(q)#)|<>%2)#` ``` ### Perl: [A000035](http://oeis.org/A000035) Using `=` as a delimiter for `s///` means we can easily exclude code we don't want, and using `)` as the delimiter for `q{}` means after `print`ing `q` in all other languages, we can just work on `<>` directly, without worrying. ``` s/1...q/i...#/; print(<>%2) ``` [Try it online!](https://tio.run/##FcxBDoMgEEDRvceAGJlqpNC4GvEixmCTkobE2hHorndH3PzVyycXtiHnaJTUqGTJYfyehN/plwTATcy6eyxznO4LIGNM9tb6l7XYVM/NhSRaCt8PFdsqwLUIbpA3ZfN2KVYUrtsBHP7jVGvga87DCQ "Perl 5 – Try It Online") ### Ruby: [A001477](http://oeis.org/A001477) In Ruby, `//` is actually `/` (divide by) `/.../` (regex match), so as long as the regex is terminated, and converted to a number, we can divide by it safely. `__id__` is shorter than `.to_s.ord`, then we just contain the rest of the code we don't want in `'`s, set `q` to `gets` and `print` it with all the others. ``` s=1/2;1//2..."/.__id__;'...';q=gets print(q) ``` [Try it online!](https://tio.run/##KypNqvz/v9jWUN/I2lAfSBTaZuaVaGTmFZSWaGhqamlEG@kYx0YX2xnEalorKSnp68XHZ6bEx1urcyXmpBaVaGgXFOXnFgDVahtqWicAVSjbWiurA41JTy0p5iooAplWqKmsWWNjp2qkqZzw/78pAA "Ruby – Try It Online") ### Python 2: [A005843](http://oeis.org/A005843) Using the standard trick to differentiate 2 from 3 and enclosing stuff we don't want in `"""` and comments. ``` s=1/2;1//2;q=int(input())*([2,3][s>0]);"""/...`""" print(q) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9jWUN/I2lAfSBTaZuaVaGTmFZSWaGhqamlEG@kYx0YX2xnEalorKSnp68XHZ6bEx1urcyXmpBaVaGgXFOXnFgDVahtqWicAVSjbWiurA41JTy0p5iooAplWqKmsWWNjp2qkqZzw/78pAA "Python 2 – Try It Online") ### Python 3: [A008585](http://oeis.org/A008585) [Try it online!](https://tio.run/##K6gsycjPM/7/v9jWUN/I2lAfSBTaZuaVaGTmFZSWaGhqamlEG@kYx0YX2xnEalorKSnp68XHZ6bEx1urcyXmpBaVaGgXFOXnFgDVahtqWicAVSjbWiurA41JTy0p5iooAplWqKmsWWNjp2qkqZzw/78pAA "Python 3 – Try It Online") ### JavaScript (ES6 browser): [A000027](http://oeis.org/A000027) Pretty straightforward for JS, it ended up being easier not to re-use the existing `print` and go for SpiderMonkey, but that might also be possible too. ``` s=1/2;1//2;q=int(input())*([2,3][s>0]);"""/.__id__;' alert(+prompt()+1);`"""#=;#';q=gets print(q)#)|<>%2)#` ``` [Answer] # 6 languages: Cubically 5/6/7/8/9/10, ~~44~~ ~~40~~ 32 bytes [Crossed out 44 is still regular 44 ;(](https://codegolf.stackexchange.com/a/153011/61563) ``` DDR'DDR$:_0?{R'DDRDDB'%0}!{+00%} ``` This prints: * [A010710](http://oeis.org/A010710) in Cubically 5x5x5 * [A010711](http://oeis.org/A010711) in Cubically 6x6x6 * [A010712](http://oeis.org/A010712) in Cubically 7x7x7 * [A010713](http://oeis.org/A010713) in Cubically 8x8x8 * [A010714](http://oeis.org/A010714) in Cubically 9x9x9 * [A010715](http://oeis.org/A010715) in Cubically 10x10x10 Explanation: ``` DDR'DDR$:_0?{R'DDRDDB'%0}!{+00%} DDR'DDR get top face sum to 2 (all versions) $: read input and set notepad to it _0 set notepad to input modulo 2 ?{...........} if truthy R'DDRDD reset cube B' set top face to Cubically version number %0 print top face !{....} if falsy +00 add 2 to notepad twice % print ``` [Try it online!](https://tio.run/##Sy5NykxOzMmp/P8/SN0lyEUdRKpYmccb2JtVA9nqQS5g0kld1aBW0azaykDbQNWs9v9/s/9mAA) (Cubically 6x6x6) ]
[Question] [ Inspired by [this example](http://bl.ocks.org/mbostock/3231298) of using [d3js](http://d3js.org/), I challenge you to create a canvas (or your language-of-choice equivalent) in which the [mouse pointer trails](http://en.wikipedia.org/wiki/Pointer_(graphical_user_interfaces)#Pointer_trails_and_animation) will be displayed, with the following twist: # The Twist You should not display the trails of where the mouse pointer **was**, but the "trails" of where it **will** (might) be in future. You can do it by using either: 1. A time machine, or 2. Probabilistic estimations based on previous mouse movements # Assumptions In case you didn't choose the time machine implementation, when the mouse does not move for more than *threshold* milliseconds, you can display none of the trails. (The *threshold* value is up to you to choose). The cursor image is up to you and does not have to be the same of the OS's cursor (you can even draw a plain small circles or dots). No evil input will be tested: You can assume the movements are smooth. 'Smooth' definition for this case is: if the mouse movements were a function over the x and y axis of the canvas - it would be a continuous function. # Winning The valid answer with the least characters in code will win. In case of a tie - the one that was posted first will win. **EDIT:** The valid answer with the **most upvotes** will win. In case of a tie - the one that was posted first will win. You can be creational on the implementation, or be precise with the prediction. I'm not the judge anymore, we all are :) * A valid answer must include a way for me to play with (test! I meant test), either on an online tool or on a freely-downloadable compiler/interpreter/runtime/etc. [Answer] # Javascript My program predicts the direction of the pointer by using the average of the angular change in direction of the last 20 mouse moves. It also uses the variance of the angular change to create a "cloud" of possible locations and directions of the pointer. The color of each pointer in the "cloud" is supposed to represent the likelihood of it being the new position of the mouse pointer, where darker colors represents a greater likelihood. The distance of the pointer cloud ahead of the mouse is calculated using the speed of mouse movement. It doesn't make the best predictions but it looks neat. Here's a fiddle: <http://jsfiddle.net/5hs64t7w/4/> Increasing the size of the pointer cloud is interesting to see. It can be set by changing the `cloudSize` variable on the first line of the program. Here is a fiddle with a cloud size of 10: <http://jsfiddle.net/5hs64t7w/5/> I used these sources to get formulas for circular mean and variance: Circular Mean: <http://en.wikipedia.org/wiki/Circular_mean> Circular Variance: <http://www.ebi.ac.uk/thornton-srv/software/PROCHECK/nmr_manual/man_cv.html> Here is the code if anyone is interested: ``` var cloudSize = 3; var canvas = document.getElementById('canvas_element'); var c = canvas.getContext('2d'); var prevX = -1; var prevY = -1; var curX = -1; var curY = -1; var distance = 0; var direction = 0; function drawMouse(x, y, angle, gray){ var grayVal = Math.round(gray*255); var grayString = "rgb(" + grayVal + "," + grayVal +"," + grayVal + ")"; c.fillStyle = grayString; c.strokeStyle = grayString; c.lineWidth = 1; c.beginPath(); c.moveTo(x, y); c.lineTo(x + 16*Math.cos(angle + Math.PI/2.0 + Math.PI/8.0), y + 16*Math.sin(angle + Math.PI/2.0 + Math.PI/8.0)); c.moveTo(x, y); c.lineTo(x + 16*Math.cos(angle + Math.PI/2.0 - Math.PI/8.0), y + 16*Math.sin(angle + Math.PI/2.0 - Math.PI/8.0)); c.lineTo(x + 16*Math.cos(angle + Math.PI/2.0 + Math.PI/8.0), y + 16*Math.sin(angle + Math.PI/2.0 + Math.PI/8.0)); c.stroke(); c.fill(); c.beginPath(); c.moveTo(x, y); c.lineTo(x + 24*Math.cos(angle + Math.PI/2), y + 24*Math.sin(angle + Math.PI/2)); c.stroke(); } function sum(array){ var s = 0.0; for(var i=0; i<array.length; i++){ s += array[i]; } return s; } var sins = []; var coss = []; var lengths = []; var times = []; var index = 0; var limit = 20; var variance = 0; var prevTime = new Date().getTime(); function updateDistanceAndDirection(x, y){ var angle = Math.atan2(prevY - curY, prevX - curX); sins[index] = Math.sin(angle); coss[index] = Math.cos(angle); lengths[index] = Math.sqrt((curX-prevX)*(curX-prevX) + (curY-prevY)*(curY-prevY)); var time = new Date().getTime(); times[index] = time - prevTime; variance = 1.0 - Math.sqrt(sum(coss)*sum(coss)+sum(sins)*sum(sins))/sins.length; direction = Math.atan2(1/sins.length*sum(sins),1/coss.length*sum(coss)); var speed = sum(lengths)/(sum(times)/200); distance = Math.min(Math.max(40, speed), 100); prevTime = time; index = (index+1)%limit; } function drawMice(count){ c.clearRect(0, 0, canvas.width, canvas.height); for(var i=count; i>=0; i--){ var dir = direction + i*variance; drawMouse(curX - distance*Math.cos(dir), curY - distance*Math.sin(dir), dir - Math.PI/2, i/count); dir = direction - i*variance; drawMouse(curX - distance*Math.cos(dir), curY - distance*Math.sin(dir), dir - Math.PI/2, i/count); } } canvas.onmousemove = function (event) { curX = event.clientX; curY = event.clientY; updateDistanceAndDirection(curX, curY); drawMice(cloudSize); prevX = curX; prevY = curY; }; ``` [Answer] # Java I decided to take the time machine approach. It turns out the key ingredient of a time machine is java.awt.Robot. My program lets you move your mouse around for 10 seconds. After the 10 seconds it goes back in time and recreates your mouse movement, while predicting it perfectly. ![enter image description here](https://i.stack.imgur.com/harlg.png) Here's the code: ``` import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Robot; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.util.ArrayList; import java.util.TimerTask; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class TimeMachine extends JPanel implements MouseMotionListener { Timer timer; int time = 10; java.util.Timer taskTimer; ArrayList<Point> mousePoints; ArrayList<Long> times; Robot robot; int width, height; ArrayList<Point> drawMousePoints; public TimeMachine(){ width = 500; height = 500; drawMousePoints = new ArrayList<Point>(); robot = null; try{ robot = new Robot(); } catch(Exception e){ System.out.println("The time machine malfunctioned... Reverting to 512 BC"); } mousePoints = new ArrayList<Point>(); times = new ArrayList<Long>(); taskTimer = new java.util.Timer(); ActionListener al = new ActionListener(){ public void actionPerformed(ActionEvent e){ time--; if(time == 0) rewind(); repaint(); } }; timer = new Timer(1000, al); start(); } public void paint(Graphics g){ g.clearRect(0, 0, width, height); g.drawString("Time Machine activiates in: " + time, 15, 50); for(int i=0; i<drawMousePoints.size(); i++){ Point drawMousePoint = drawMousePoints.get(i); drawMouse(drawMousePoint.x-getLocationOnScreen().x, drawMousePoint.y-getLocationOnScreen().y, g, Color.BLACK, Color.LIGHT_GRAY, (double)i/drawMousePoints.size()); } } public void drawMouse(int x, int y, Graphics g, Color line, Color fill, double alpha){ Graphics2D g2d = (Graphics2D)g; g2d.setColor(new Color(fill.getRed(), fill.getGreen(), fill.getBlue(), (int)Math.max(Math.min(alpha*255, 255), 0))); g2d.fillPolygon(new int[]{x, x, x+4, x+8, x+10, x+7, x+12}, new int[]{y, y+16, y+13, y+20, y+19, y+12, y+12}, 7); g2d.setColor(new Color(line.getRed(), line.getGreen(), line.getBlue(), (int)Math.max(Math.min(alpha*255, 255), 0))); g2d.drawLine(x, y, x, y + 16); g2d.drawLine(x, y+16, x+4, y+13); g2d.drawLine(x+4, y+13, x+8, y+20); g2d.drawLine(x+8, y+20, x+10, y+19); g2d.drawLine(x+10, y+19, x+7, y+12); g2d.drawLine(x+7, y+12, x+12, y+12); g2d.drawLine(x+12, y+12, x, y); } public void start(){ timer.start(); prevTime = System.currentTimeMillis(); mousePoints.clear(); } public void rewind(){ timer.stop(); long timeSum = 0; for(int i=0; i<times.size(); i++){ timeSum += times.get(0); final boolean done = i == times.size()-1; taskTimer.schedule(new TimerTask(){ public void run(){ Point point = mousePoints.remove(0); drawMousePoints.clear(); drawMousePoints.addAll(mousePoints.subList(0, Math.min(mousePoints.size(), 30))); robot.mouseMove(point.x, point.y); repaint(); if(done) System.exit(0); } }, timeSum); } } long prevTime = 0; public void record(MouseEvent m){ if(timer.isRunning()){ long time = System.currentTimeMillis(); mousePoints.add(new Point(m.getXOnScreen(), m.getYOnScreen())); times.add((time-prevTime)/10); prevTime = time; } } public static void main(String[] args){ TimeMachine timeMachine = new TimeMachine(); JFrame frame = new JFrame("Time Machine"); frame.setSize(timeMachine.width, timeMachine.height); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.addMouseMotionListener(timeMachine); frame.add(timeMachine); } public void mouseDragged(MouseEvent m) { record(m); } public void mouseMoved(MouseEvent m) { record(m); } } ``` [Answer] # Vanilla Javascript Just to get things started, here is a simple prediction based on two values. The last `n` mouse postions are memorized and kept in a queue, the prediction is a simple linear extrapolation of the first and last element in the queue. This is just the prediction code, the full code including the demo can be seen in `[this fiddle](http://jsfiddle.net/pfyruc14/5/)`: ``` function predict(trail) { var b = trail.pop(), a = trail[0], d = { x: b.x - a.x, y: b.y - a.y }, m = Math.sqrt( d.x * d.x + d.y * d.y ); d.x = 5 * d.x / m; d.y = 5 * d.y / m; var predictions = []; for(var i = 1; i <= 10; i++) { predictions.push({ x: b.x + i * d.x, y: b.y + i * d.y }); } return predictions; } ``` The demo contains a comment in the prediction that allows you to instead use the last two elements in the queue for the prediction. Makes the result more "real-time", but also less "smooth". If anyone wants to use the `[boilerplate work](http://jsfiddle.net/pfyruc14/2/)` to implement a different prediction algorithm, feel free. It's not a lot of work anyway. [Answer] **Javascript** *The past is the best prediction for the future* - me, and propably someone else too My solution is very simple. First, here is the [>>> Fiddle! <<<](http://jsfiddle.net/k2zzz024/8/ "Fiddle!") All it does is shifting the past trail, so it looks like the future trail. Basically no Math is involved (I Know, pretty boring). You can easily see the errors, especially when moving the cursor in circles. That's why I made the trail so short ;) The code: ``` <!DOCTYPE html> <html> <head> <style type="text/css"> .cursor { width: 12px; height: 19px; position: absolute; background-image: url(https://i.imgur.com/h8imKBP.png); } </style> <script type="text/javascript"> var x, y; window.onmousemove = function(e) {x=e.clientX; y=e.clientY;} var p = [0,0,0,0,0,0,0,0,0,0]; window.setInterval(function() { p.shift(); p.push([x, y]); var diff = [x-p[0][0], y-p[0][1]]; for (var i = 0; i < 10; i++) { var e = document.getElementById(i); e.style.left = (p[9-i][0]+diff[0])+"px"; e.style.top = (p[9-i][1]+diff[1])+"px"; } }, 10); </script> </head> <body> <div id="0" class="cursor"></div> <div id="1" class="cursor"></div> <div id="2" class="cursor"></div> <div id="3" class="cursor"></div> <div id="4" class="cursor"></div> <div id="5" class="cursor"></div> <div id="6" class="cursor"></div> <div id="7" class="cursor"></div> <div id="8" class="cursor"></div> <div id="9" class="cursor"></div> </body> </html> ``` ]
[Question] [ Let's play some code golf! Given a tic-tac-toe board state (Example:) ``` |x|x|o| |x|o|x| |o|o|x| ``` Determine whether a game is a `win` a `lose` or `cat`. Your code should output any of these options given a state. The above game should output `lose` Just to be clear: a win is defined as any 3 `x`s in a row (diagonal, horizontal, vertical). a lose is 3 `o`s in a row, while a `cat` game in none in a row. To make things interesting, you get to determine your input structure for the state- which you must then explain. For instance `xxoxoxoox` is a valid state as seen above where each of the characters is read from left to right, top to bottom. `[['x','x','o'],['x','o','x'],['o','o','x']]` is the game in multidimensional array read in a similar way. While `0x1a9` which is hex for `110101001` might work as a suitable compression where `1` can be manipulated for `x`s and `0` can be manipulated for `o`. But those are just some ideas, I'm sure you might have many of your own. Ground rules: 1. Your program must be able to accept any viable state. 2. The form of input must be able to represent any state. 3. The input cannot be redundant, meaning each cell must only appear in one location. 4. "The win state must be determined from the board" 5. Assume a complete board 6. `Win` before `lose` for instance in the case 'xxxoooxxx' Lowest character count wins [Answer] ## Ruby 2.0, 85 characters Here's a simple bitmask-based solution in Ruby: ``` d=gets.hex $><<[292,146,73,448,56,7,273,84].map{|m|d&m<1?:lose:d&m<m ?:cat: :win}.max ``` The board is represented as a hex number, made up of nine bits corresponding to the nine squares. 1 is an `X`, 0 is an `O`. This is just like the `0x1a9` example in the question, though the `0x` is optional! There's probably a better way to do the bitmasks then just hardcoding a big list. I'll happily take suggestions. See it running [on Ideone here](http://ideone.com/91YLmq). [Answer] # Mathematica, 84 chars ``` a=Input[];Which[Max@#>2,win,Min@#<1,lose,1>0,cat]&@{Tr@a,Tr@Reverse@a,Tr/@a,Total@a} ``` Input format: `{{1, 1, 0}, {1, 0, 1}, {0, 0, 1}}` [Answer] # Bash: ~~283~~ ~~262~~ 258 Featuring a relatively friendly interface. ``` t(){ sed 's/X/true/g;s/O/false/g'<<<$@;} y(){ t $(sed 's/X/Q/g;s/O/X/g;s/Q/O/g'<<<$@);} f(){($1&&$2&&$3)||($1&&$5&&$9)||($1&&$4&&$7)||($2&&$5&&$8)||($3&&$5&&$7)||($3&&$6&&$9)||($4&&$5&&$6)||($7&&$8&&$9)} f $(t $@)&&echo win||(f $(y $@)&&echo lose)||echo cat ``` To execute `bash tictactoe.sh O X O X O X X O X` Note: the list of 9 positions is a standard matrix representation. It doesn't matter if the board is represented as column major or row major, read from left to right or top to bottom - games of noughts and crosses (or tic tac toe if you insist) are symmetrical, so input order should be irrelevant to the result in every correct implementation, as long as input is linear. Edit: Thanks to h.j.k for shorter function syntax suggestion. [Answer] # Befunge 93 - 375 Takes a binary string as input. ``` 99>~\1-:!!|>v >0v>v>v >^$>v ^+ + + 0<:p: >#+#+#+ ^246 ^+ + + 0<265 >#+#+#+ ^pp6 ^+ + + 0<2++ #+#+#+ 55p 0 0 552 >^>^>0v +46 v+ + + < ppp >0 + + + v 444 v!!-3:<< 246 v_"ni"v ppp 0v" w"< :+: \>,,,,@ 266 ->,,,@ 555 !^"cat"_^ 645 !>:9-! ^ +:+ >| p:p >"eso"v 6p6 @,,,,"l"< 246 p2p >^ v <^ < ``` Reads the string. Bruteforce writes it (the right most vertical strip) as a matrix in between the ``` ^+ + + >#+#+#+ ^+ + + >#+#+#+ ^+ + + #+#+#+ ``` adding lattice (idk). Determins the sum of the columns, rows, and two diagnals. Compares those values to 3 ("win") or 0 ("lose"), else if all the values equal 1 or 2 then draw ("cat"). [Answer] # Python 2 - 214 bytes ``` b=eval(raw_input()) s=map(sum,b) w,l='win','lose' e="if min(s)<1:print l;a\nif max(s)>2:print w;a" exec e+'\ns=map(sum,zip(*b))\n'+e m=b[1][1] for i in 0,2: if m==b[0][i]==b[2][abs(i-2)]:print[l,w][m];a print'cat' ``` I'm sure there are improvements to be made. To run: ``` python2 tictactoe.py <<< '[[1,1,1],[1,0,1],[0,1,0]]' ``` which represents this board: ``` X|X|X ----- X|O|X ----- 0|X|0 ``` Exits with a `NameError` exception in every case except `cat`. [Answer] ## Haskell, 146 chars > > To make things interesting, you get to determine your input structure for the state- which you must then explain. > > > OK :). My representation of a board is one of those 126 characters > > ĻŃŇʼnŊœŗřŚşšŢťŦŨųŷŹźſƁƂƅƆƈƏƑƒƕƖƘƝƞƠƤƳƷƹƺƿǁǂDždžLjǏǑǒǕǖǘǝǞǠǤǯDZDzǵǶǸǽǾȀȄȍȎȐȔȜȳȷȹȺȿɁɂɅɆɈɏɑɒɕɖɘɝɞɠɤɯɱɲɵɶɸɽɾʀʄʍʎʐʔʜʯʱʲʵʶʸʽʾˀ˄ˍˎː˔˜˭ˮ˰˴˼̌ > > > Here's the solution in 146 chars : ``` main=interact$(\x->case(head x)of h|elem h "ĻŃœťŦŨųŷŹƁƂƅƈƕƠƤƳƿǂdžǞǤǵǾȀȳȿɁɅɑɒɘɝɠɤɵɽʀʐʽʾː˭ˮ˰˴˼̌"->"lose";h|elem h "ƏƝƞƹǁLjǑǝȍȺɆɈɶɾʎʸ"->"cat";h->"win") ``` And here's how it works, as an haskell script : ``` import Data.List (subsequences, (\\)) import Data.Char (chr) -- A set of indexes [0-8] describing where on the board pieces of a single color have been played -- For example the board "OxO;Oxx;xxO" is indexes [0,2,3,8] type Play = [Int] -- There are 126 filled tic tac toe boards when X plays first. -- (This is a combination of 4 OHs among 9 places : binomial(9 4) = 126) -- perms returns a list of all such possible boards (represented by the index of their OHs). perms = filter (\x -> 4 == length x) $ subsequences [0..8] -- We now create an encoding for plays that brings them down to a single char. -- The index list can be seen as an 9 bit binary word [0,2,3,8] -> '100001101' -- This, in turn is the integer 269. The possible boards give integers between 15 and 480. -- Let's call those PlayInts type PlayInt = Int permToInt [] = 0 permToInt (x:xs) = (2 ^ x) + permToInt xs -- Since the characters in the range 15-480 are not all printable. We offset the chars by 300, this gives the range -- ĻŃŇʼnŊœŗřŚşšŢťŦŨųŷŹźſƁƂƅƆƈƏƑƒƕƖƘƝƞƠƤƳƷƹƺƿǁǂDždžLjǏǑǒǕǖǘǝǞǠǤǯDZDzǵǶǸǽǾȀȄȍȎȐȔȜȳȷȹȺȿɁɂɅɆɈɏɑɒɕɖɘɝɞɠɤɯɱɲɵɶɸɽɾʀʄʍʎʐʔʜʯʱʲʵʶʸʽʾˀ˄ˍˎː˔˜˭ˮ˰˴˼̌ -- Of all distinct, printable characters uOffset = 300 -- Transform a PlayInt to its Char representation pIntToUnicode i = chr $ i + uOffset -- Helper function to convert a board in a more user friendly representation to its Char -- This accepts a representation in the form "xooxxxoxo" convertBoard s = let play = map snd $ filter (\(c, i) -> c == 'o') $ (zip s [0..]) :: Play in pIntToUnicode $ permToInt play -- -- Now let's cook some data for our final result -- -- All boards as chars allUnicode = let allInts = map permToInt perms in map pIntToUnicode allInts -- Now let's determine which boards give which outcome. -- These are all lines, columns, and diags that give a win when filled wins = [ [0,1,2],[3,4,5],[6,7,8], -- lines [0,3,6],[1,4,7],[2,5,8], -- columns [0,4,8],[2,4,6] -- diagonals ] isWin :: Play -> Bool isWin ps = let triplets = filter (\x -> 3 == length x) $ subsequences ps -- extract all triplets in the 4 or 5 moves played in any (\t -> t `elem` wins) triplets -- And check if any is a win line -- These are OH wins oWins = filter isWin perms -- EX wins when the complement board wins xWins = filter (isWin . complement) perms where complement ps = [0..9] \\ ps -- And it's stalemate otherwise cWins = (perms \\ oWins) \\ xWins -- Write the cooked data to files cookData = let toString = map (pIntToUnicode . permToInt) in do writeFile "all.txt" allUnicode writeFile "cWins.txt" $ toString cWins writeFile "oWins.txt" $ toString oWins writeFile "xWins.txt" $ toString xWins -- Now we know that there are 48 OH-wins, 16 stalemates, and 62 EX wins (they have more because they play 5 times instead of 4). -- Finding the solution is just checking to which set an input board belongs to (ungolfed :) main = interact $ \x -> case (head x) of -- Only consider the first input char h | elem h "ĻŃœťŦŨųŷŹƁƂƅƈƕƠƤƳƿǂdžǞǤǵǾȀȳȿɁɅɑɒɘɝɠɤɵɽʀʐʽʾː˭ˮ˰˴˼̌" -> "lose" -- This string is == oWins h | elem h "ƏƝƞƹǁLjǑǝȍȺɆɈɶɾʎʸ" -> "cat" -- And this one == cWins h -> "win" ``` [Answer] ## Ruby, 84 characters ``` $><<(gets.tr("01","10")[r=/0..(0|.0.)..0|000(...)*$|^..0.0.0/]?:win:~r ?:lose: :cat) ``` Simple, RegExp based solution. The input format is a 9-digit binary string, e.g. `110101001` for the example board given in the question. ## Ruby, 78 characters ``` $><<(gets.tr("ox","xo")[r=/o...(o|.o.)...o|ooo|o_.o._o/]?:win:~r ?:lose: :cat) ``` Input format: `xxo_xox_oox` [Answer] # Python3 - 188 w. different approaches to evaluation Found the subject yesterday on Reddit and was fascinated. It was a simple code just to determine victory. Same night I made up my own version. Today i found this codegolf thread. [EDIT: 'blabla'] I am amazed about the different answers and possibilities within the other languages! Nice! ### 188 Python3 Code EDIT: Now Meeting Requirements 1-5 Input-Style: Player p=0/1 and board b=(1,1,1,0,1,0,1,0,1) ``` def t(b,p): s,c,l,w=0,"cat","loose","win" for i in 1,2,3,4: u=2*i-1 a=i*i-5*i+3 if b[4]==b[4+i]==b[4-i]: if p==b[4]:s+=1 else:s-=1 if b[u]==b[u+a]==b[u-a]: if p==b[u]:s+=1 else:s-=1 if s>0:c=w if s<0:c=l return c ``` ## Victory Check Codes ### 103 Python3 - 'Square-Function' EDIT1: nicer with "a==b==c==p" instead of "a+b+c==3\*p" ``` def t(b,p): for i in 1,2,3,4: u=2*i-1 a=i*i-5*i+3 if b[4]==b[4+i]==b[4-i]==p or b[u]==b[u+a]==b[u-a]==p:return True ``` Explanation: Term for a based on f(u=1)=f(u=7)=1 f(u=3)=f(u=5)=3 ### 113 Python3 - 'Magic Square' Input just with board: Player is „1“, Oponent „0“ ``` def t(b): n=[x*y for x,y in zip(b,(2,9,4,7,5,3,6,1,8))] if 15 in [x+y+z for x in n for y in n if x!=y for z in n if z!=x and z!=y]:return True ``` Explanation: Sum has to be 15 in Magic Square ### 119 Python3 - 'Oneliner' inspired by Reddit Solution from user 'Xelf' ``` def t(b,p): if 3*p in [b[x]+b[y]+b[z] for x,y,z in [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]]:return True ``` --- @Ad Hoc Garf Hunter Thank You for the Feedback! Though i am a bit embarassed and sorry i don´t even know what 'stdin' is about. Just want to contribute some ideas and learn. Thank you for the comment on assignment and whitespaces! I just corrected it. EDIT: Hope to meet the rules now. I understand i could make spaces instead of tabs, but that just looks nasty. [Answer] ## GolfScript, 63 + 27 = 90 bytes I originally submitted the following 27-byte entry that exploited a loophole in the rules (as written at the time of submission) allowing a redundant input encoding: ``` 70&.{~"win""lose"if}"cat"if ``` The input format for this entry is a string consisting of eight octal digits, each (redundantly) encoding three consecutive board squares: * The first three digits each encode a single row of the board, from top down and left to right. * The following three digits each encode a single column of the board, from left to right and top down. * The final two digits each encode one of the diagonals (first from top left to bottom right, then from bottom left to top right). To encode a sequence (row / column / diagonal) of three squares as an octal digit, replace every `x` in the sequence with a 1 and every `o` with a 0, and interpret the resulting sequence of ones and zeros as a binary number between 0 and 7 inclusive. This input format is quite redundant (all board positions are encoded at least twice, with the center position encoded four times), but it *does* unambiguously represent any possible state of a completely filled tic-tac-toe board, and does not *directly* encode the winner into the input. The input may, optionally, contain spaces or other delimiters between digits. In fact, all the program *really* cares about is whether or not the input string contains the digits `7` or `0`. For example, the example board: ``` |x|x|o| |x|o|x| |o|o|x| ``` may be represented by the input: ``` 651 643 50 ``` To make testing the program above easier, I also provided a 63-byte GolfScript program to convert an ASCII art board layout, as shown above, into an input string suitable for this program: ``` ."XOxo"--[{1&!}/]:a[3/.zip"048642"{15&a=}%3/]{{2base""+}%}%" "* ``` This converter ignores any characters other than `x` and `o`, in either case, in its input. It produces a single digit string (complete with space delimiters as shown above) suitable for feeding into the win-determining program above, so **the concatenation of these two programs can be used to determine the winner directly from the ASCII art board**, and thus still qualifies as a valid entry under the current challenge rules: ``` ."XOxo"--[{1&!}/]:a[3/.zip"048642"{15&a=}%3/]{{2base""+}%}%" "*70&.{~"win""lose"if}"cat"if ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/X08pwr8iX0lXN7raUE2xVj/WKjHaWF@vKrNAycDEwszESKna0FQt0bZW1Vg/trraKCmxOFVJSbtWtVZVSUFJy9xATa@6Tqk8M09JKScfKJWZVquUnFgCpP//r6kAwvwaLjBZAaTzwTQA "GolfScript – Try It Online") Of course, the input format converted is not particularly well optimized and the combined program could easily be golfed further. However, rather than attempting to re-golf a six-year-old solution, I prefer to just keep it as close to its originally submitted form as current rules permit. Ps. Here's a reverse converter, just to demonstrate that the redundant input format for the 27-byte version indeed does unambiguously represent the board: ``` .56,48>-- 3<{2base-3>{"ox"=}%n}%"|".@@*+); ``` [Answer] # CJam, ~~39 38~~ 36 characters ``` "ᔔꉚ굌궽渒䗠脯뗠㰍㔚귇籾〳㎪䬔⹴쪳儏⃒ꈯ琉"2G#b129b:c~ ``` This is a base converted code for ``` q3/_z__Wf%s4%\s4%]`:Q3'o*#"win"{Q'x3*#"lose""cat"?}? ``` which is 52 characters long. The input is simply the string representation of the board starting from top left, going row by row. For example: ``` oxooxooox ``` which results in a `win` output. Or ``` oxooxoxox ``` which results in a `cat` output, etc. The code simply does the following three things: * `q3/_` - Split the string into parts of 3, i.e. per row * `_z` - Copy the per row array and transpose into per column array. * `__Wf%s4%` - Reverse each row and get the left to right diagonal. This is the secondary diagonal of the board. * `\s4%` - Get the main diagonal of the board * `]`` - Wrap everything in array and stringify the array. Now we have all possible groups of 3 from the board. We simply check for existence of "ooo" and "xxx" to determine the result. [Try it online here](http://cjam.aditsu.net/) [Answer] # Haskell, 169 ``` main=interact$(\x->last$"cat":[b|(a,b)<-[("ooo","lose"),("xxx","win")],any(==a)x]).(\x->x++(foldr(zipWith(:))(repeat[])x)++map(zipWith(!!)x)[[0..],[2,1,0]]).take 3.lines ``` Input format: "X" is represented only by `x`, "O" only by `o`. Within each row, characters are simultaneous without spaces, etc. Rows are separated by new lines. Generates all possible rows/columns/diagonals, then filters `[("ooo","lose"),("xxx","win")]` by their existence on the board, then selects the second word in the tuple, so we know which players won. We prepend `"cat"` so that we can take the last element of the list as our winner. If both players won, `"win"` will be last (list comprehensions maintain order). Since `"cat"` is always first, if a winner exists, it will be chosen, but otherwise a last element still exists as prepending `"cat"` guarantees nonemptyness. EDIT: Shaved 3 characters by changing last list comprehension to `map`. [Answer] # Bash, ~~107~~ 103 Generates and runs a sed script. I/O format: `oxo-oox-xoo` outputs `lose` (use a `-` to separate rows). Input on stdin. Requires GNU sed for the `c` command. I've interpreted rule 5 as "if both win and lose are possible, choose win". ## Main Code This is the actual answer. Nothing interesting really. It defines `$b` as `/cwin` to save characters, then defines the win condition part of the script, then uses `sed y/x/o/\;s$b/close/` to convert `x` to `o` and `cwin` to `close` (thereby generating the lose conditions). It then sends the two things and `ccat` (which will output `cat` if no win/lose condition is matched) to sed. ``` b=/cwin v="/xxx$b /x...x...x$b /x..-.x.-..x$b /x-.x.-x$b" sed "$v `sed y/x/o/\;s$b/close/<<<"$v"` ccat" ``` ## Generated Code This is the sed script generated and run by the Bash script. In the regexes, `.` matches any character and after them `cTEXT` prints TEXT and exits if the regex is matched. This can run as a standalone sed script. It's 125 characters long, you can count it as another solution. ``` /xxx/cwin /x...x...x/cwin /x..-.x.-..x/cwin /x-.x.-x/cwin /ooo/close /o...o...o/close /o..-.o.-..o/close /o-.o.-o/close ccat ``` [Answer] ## Dart - 119 (See [dartlang.org](http://dartlang.org/)). Original version using RegExp: 151 chars. ``` main(b,{w:"cat",i,p,z}){ for(p in["olose","xwin"]) for(i in[0,2,3,4]) if(b[0].contains(new RegExp('${z=p[0]}(${'.'*i}$z){2}'))) w=p.substring(1); print(w); } ``` Input on the command line is 11 characters, e.g., "xxx|ooo|xxx". Any non-xo character can be used as delimiter. Leading whitespace and newlines should be omitted before counting characters, but I cut away the internal whitespace where possible. I wish there was a smaller way to make the substring. Recusive bit-base version: 119 chars. Input must be a 9-bit number with 1s representing 'x' and 0s representing 'o'. ``` main(n){ n=int.parse(n[0]); z(b,r)=>b>0?b&n==b&511?"win":z(b>>9,n&b==0?"lose":r):r; print(z(0x9224893c01c01e2254,"cat")); } ``` [Answer] # J - 56 (26?) char Input is given a 3x3 matrix of nine characters, because J can support that as a datatype, LOL. ``` (win`lose`cat{::~xxx`ooo<./@i.<"1,<"1@|:,2 7{</.,</.@|.) ``` Examples: ``` NB. 4 equivalent ways to input the example board (3 3 $ 'xxoxoxoox') ; (_3 ]\ 'xxoxoxoox') ; ('xxo','xox',:'oox') ; (];._1 '|xxo|xox|oox') +---+---+---+---+ |xxo|xxo|xxo|xxo| |xox|xox|xox|xox| |oox|oox|oox|oox| +---+---+---+---+ (win`lose`cat{::~xxx`ooo<./@i.<"1,<"1@|:,2 7{</.,</.@|.) 3 3 $ 'xxoxoxoox' lose wlc =: (win`lose`cat{::~xxx`ooo<./@i.<"1,<"1@|:,2 7{</.,</.@|.) wlc (3 3 $ 'xoxoxooxo') cat wlc (3 3 $ 'xxxoooxxx') win ``` If we are allowed the Golfscriptish encoding of octal digits redundantly representing the state of each row, column, and diagonal, then it's just 26 characters: ``` win`lose`cat{::~7 0<./@i.] 6 5 1 6 4 3 5 0 lose f=:win`lose`cat{::~7 0<./@i.] f 7 0 7 5 5 5 5 5 win ``` [Answer] # T-SQL (2012),110 `select max(iif(@&m=0,'lose',iif(@&m=m,'win','cat')))from(VALUES(292),(146),(73),(448),(56),(7),(273),(84))z(m)` Input is a hex number. This is pretty much a translation of the ruby solution into T-SQL pretty nice and neat. [Answer] # Java 7, 260 bytes ``` String c(int[]s){int a[]=new int[8],x=0,y;for(;x<3;x++){for(y=0;y<3;a[x]+=s[x*3+y++]);for(y=0;y<3;a[x+3]+=s[y++%3]);}for(x=0;x<9;y=s[x],a[6]+=x%4<1?y:0;a[7]+=x%2<1&x>0&x++<8?y:0);x=0;for(int i:a)if(i>2)return"win";for(int i:a)if(i<1)return"loose";return"cat";} ``` **Ungolfed & test cases:** [Try it here.](https://ideone.com/ARfs4J) ``` class M{ static String c(int[] s){ int a[] = new int[8], x = 0, y; for(; x < 3; x++){ for(y = 0; y < 3; a[x] += s[x * 3 + y++]); for (y = 0; y < 3; a[x + 3] += s[y++ % 3]); } for(x = 0; x < 9; y = s[x], a[6] += x % 4 < 1 ? y : 0, a[7] += x % 2 < 1 & x > 0 & x++ < 8 ? y : 0); x = 0; for(int i : a){ if(i > 2){ return "win"; } } for(int i : a){ if(i < 1){ return "loose"; } } return "cat"; } public static void main(String[] a){ /* xxo xox oox */ System.out.println(c(new int[]{ 1, 1, 0, 1, 0, 1, 0, 0, 1 })); /* xxx ooo xxx */ System.out.println(c(new int[]{ 1, 1, 1, 0, 0, 0, 1, 1, 1 })); /* xxo oox xox */ System.out.println(c(new int[]{ 1, 1, 0, 0, 0, 1, 1, 0, 1 })); } } ``` **Output:** ``` loose win cat ``` [Answer] # Bash: 208 chars ``` y(){ tr '01' '10'<<<$@;} f(){ x=$[($1&$2&$3)|($1&$5&$9)|($1&$4&$7)|($2&$5&$8)|($3&$5&$7)|($3&$6&$9)|($4&$5&$6)|($7&$8&$9)]; } f $@;w=$x f $(y $@) ([ $x -eq 1 ]&&echo lose)||([ $w -eq 1 ]&&echo win)||echo cat ``` To execute `bash tictactoe.sh 0 1 0 1 0 1 1 0 1` Inspired by [this answer](https://codegolf.stackexchange.com/a/32395/23764). [Answer] # Python 2, 99 bytes Similar to [the Ruby answer](https://codegolf.stackexchange.com/a/32401/4999): ``` def t(b):print['win'if w&b==w else'lose'if w&~b==w else'cat'for w in 448,56,7,292,146,73,273,84][0] ``` The input is the binary format described in the question: `1` for X, `0` for O, left-to-right, top-to-bottom. For example, `0b101001110` represents ``` XOX OOX XXO ``` which leads to output: `cat` [Answer] # C, 164 bytes It's midnight here and **I haven't done any testing**, but I'll post the concept anyway. I'll get back to it tomorrow. User inputs two octal numbers (I wanted to use binary but as far as I know C only supports octal): `a` represents the centre square, 1 for an X, 0 for an O `b` is a nine-digit number representing the perimeter squares, circling round the board starting in one corner and finishing in the same corner (with repeat of that corner only), 1 for an X, 0 for an O. **There are two possible ways to win:** 1. centre square is X (`a`=1) and two opposite squares are also X (`b&b*4096` is nonzero) 2. three adjacent perimeter squares are X (`b/8 & b & b*8` is nonzero.) This is only a valid win if the middle square is an edge square, not a corner square, therefore it is necessary to apply the mask `m` also, to avoid the corner square cases. **Losing is detected using the variable c, which is the inverse of b.** ``` int a,b,c,m=010101010; main(){ scanf("%o%o",a,b);c=b^0111111111; printf("%s",(a&&b&b*4096)|(b/8&b&b*8&m)?"win":((!a&&c&c*4096)|(c/8&c&c*8)?"lose":"cat")); } ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~120~~ ~~116~~ ~~118~~ ~~112~~ ~~106~~ 102 bytes The more compact pattern inspired by [Ventero](https://codegolf.stackexchange.com/a/32502/80745) Fixed to follow the rule 6. ``` @(switch -r($args){($x='^(...)*111|^..1.1.1|1..(1|.1.)..1'){'win'}($x-replace1,0){'lose'}.{'cat'}})[0] ``` [Try it online!](https://tio.run/##RZDRTsMgFIbveYqTiAKmJeVmd0safQCNu1w20zF0M2grtOmSlmevHFo3uCHf//OdQFP3xvmTsXaiH7CGYSq578@tPkHuOK3cpxcDp5c123MppXhUSo17KRXuUUnJ1RiPIhImBtaff1iI9dyZxlbaqKyI1NbesCAHpquWhSC2xW4KhJSckIyzolC4VcEySAKBVCUYM6RJkHBCmCFG3VKOGPlVAXfgOmtgRYiAEe5hIBAXPdSVO2ZAzaUxujXH@GT6PkfO@M62ETzEn5iLKdi@bp4739bfL4eveGdXzipcm05r49GxXM7N7819rb39m5faNXjCIchv0wIJ0x8 "PowerShell – Try It Online") [Answer] ## J - 97 bytes Well, the simplest approach available. The input is taken as `111222333`, where the numbers represent rows. Read left-to-right. Player is `x` and enemy is `o`. Empty squares can be anything except `x` or `o`. ``` f=:(cat`lose>@{~'ooo'&c)`('win'"_)@.('xxx'&c=:+./@(r,(r|:),((r=:-:"1)(0 4 8&{,:2 4 6&{)@,))3 3&$) ``` Examples: (NB. is a comment) ``` f 'xoxxoxxox' NB. Victory from first and last column. win f 'oxxxooxxx' NB. Victory from last row. win f 'ooxxoxxxo' NB. The example case, lost to a diagonal. lose f 'xxooxxxoo' NB. Nobody won. cat f 'xoo xx ox' NB. Victory from diagonal. win ``` ### Ungolfed code an explanation ``` row =: -:"1 Checks if victory can be achieved from any row. col =: -:"1 |: Checks if victory can be achieved from any column. diag =: -:"1 (0 4 8&{ ,: 2 4 6&{)@, Checks if victory can be achieved from diagonals. check =: +./@(row,col,diag) 3 3&$ Checks all of the above and OR's them. f =: (cat`lose >@{~ 'ooo'&check)`('win'"_)@.('xxx'&check) Check if you have won ........................@.('xxx'&check) If yes, return 'win' .............. ('win'"_) If not (cat`lose >@{~ 'ooo'&check) Check if enemy won ................... 'ooo'&check If yes, return 'lose' ---`lose >@{~ If not, return 'cat' cat`---- >@{~ ``` [Answer] ## J : 83 ``` (;:'lose cat win'){::~>:*(-&(+/@:(*./"1)@;@(;((<0 1)&|:&.>@(;|.)(,<)|:)))-.)3 3$'x'= ``` Usage: just append a string of x's and o's and watch the magic work. eg. 'xxxoooxxx'. The inner verb `(+/@:(*./"1)@;@(;((<0 1)&|:&.>@(;|.)(,<)|:)))` basically boxes together the original binary matrix, with the transpose boxed together with the 2 diagonals. These results are razed together ; row sums are taken to determine wins, and then summed. further I'll call this verb `Inner`. For finding the winner, the difference of the scores between the normal and inversed binary matrices is taken by the hook `(-&Inner -.)`. The rest of the code simply makes the outputs, and selects the right one. [Answer] ## JavaScript, ~~133~~, 114 characters ``` r = '/(1){3}|(1.{3}){2}1|(1.{4}){2}1|(1\|.1.\|1)/';alert(i.match(r)?'WIN':i.match(r.replace(/1/g,0))?'LOSS':'CAT') ``` The input `i` is a simple string with delimiters for the rows, i.e. `100|001|100` Edit: updated my method to replace the 1s in the regex with zeroes to check for the loss case. [Answer] # APL(NARS), 69 chars, 138 bytes ``` {w←3 3⍴⍵⋄x←(+/1 1⍉⊖w),(+/1 1⍉w),(+⌿w),+/w⋄3∊x:'win'⋄0∊x:'lose'⋄'cat'} ``` The input should be one 3x3 matrix or one linear array of 9 element that can be only 1 (for X) and 0 (for O), the result will be "cat" if nobody wins, "lose" if O wins, "win" if X wins. There is no check for one invalid board or input is one array has less than 9 element or more or check each element <2. As a comment: it would convert the input in a 3x3 matrix, and build one array named "x" where elements are the sum each row column and diagonal. Some test see example showed from others: ``` f←{w←3 3⍴⍵⋄x←(+/1 1⍉⊖w),(+/1 1⍉w),(+⌿w),+/w⋄3∊x:'win'⋄0∊x:'lose'⋄'cat'} f 1 2 3 win f 0 0 0 lose f 1 0 1 1 0 1 1 0 1 win f 0 1 1 1 0 0 1 1 1 win f 0 0 1 1 0 1 1 1 0 lose f 1 1 0 0 1 1 1 0 0 cat f 1 1 0 0 1 0 0 0 1 win f 1 1 0 1 0 1 0 0 1 lose ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes ``` ŒD,ŒdḢ€;;ZEƇFṀị“ẏż“¡ṇ⁽“Zƙċ» ``` [Try it online!](https://tio.run/##y0rNyan8///oJBedo5NSHu5Y9KhpjbV1lOuxdreHOxse7u5@1DDn4a7@o3uA9KGFD3e2P2rcC2RGHZt5pPvQ7v///0dHG@kY6RjG6gBpQx0jIG0IpmMB "Jelly – Try It Online") Input is a list of lists of ints: 0 = nothing, 1 = circle, 2 = cross. ## Explanation ``` ŒD,ŒdḢ€;;ZEƇFṀị“ẏż“¡ṇ⁽“Zƙċ» Main monadic link ŒD Diagonals , Pair with Œd Antidiagonals Ḣ€ Head (first item) of each [the main diagonal and antidiagonal] ; Join with the input ; Join with the input Z zipped (transposed) [the diagonals, rows and columns] Ƈ Filter by E All elements equal? F Flatten Ṁ Maximum ị Index into (1-indexed) “ẏż“¡ṇ⁽“Zƙċ» ["lose", "win", "cat"] ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 174 bytes ``` param($a,$b,$c,$d,$e,$f,$g,$h,$i)@("$a$b$c","$a$d$g","$a$e$i","$b$e$h","$c$e$g","$c$f$i","$d$e$f","$g$h$i")|%{if($_-eq'XXX'){'win';exit}elseif($_-eq'OOO'){'lose';exit}};'cat' ``` [Try it online!](https://tio.run/##RclbCoMwEIXhvcgpUZiuwJfuIK95KzFOLpBWq4IF69rTpJaWYeDj/OOw8jR7jjGlUU/6VkMTOoIh9AQmWIIjeEJoLnUFjQ6mooIe7gAjFHQZvsBkuAP2SH1ebIGDz0vzOm3B1rie@SGUUqLZxBruouVnWHaOM/@qlLLUOMz8zXsrjF5ESkl@Tv3/DQ "PowerShell – Try It Online") Trivial solution. Takes 9 parameters for each key in board. ]
[Question] [ Your task is to determine how much of a perfect palindrome a string is. Your typical palindrome (eg 12321) is a perfect palindrome; its perfectness is 1. To determine the perfectness of a string, you see how many sections you can split it into where each section is a palindrome. If there are ambiguities, such as with `aaaa`, as you can split it into `[aa, aa]` or `[aaaa]` or `[a, aaa]` or `[aaa, a]`, the shortest set will override, giving `aaaa` a score of 1, which is the length of the shortest set. Therefore, you must write a program or function that will take one non-empty input and output how perfect it is (which is the length of the shortest set you can split it into where each element in the set is a palindrome). ### Examples: ``` 1111 -> 1 [1111] abcb -> 2 [a, bcb] abcbd -> 3 [a, bcb, d] abcde -> 5 [a, b, c, d, e] 66a -> 2 [66, a] abcba-> 1 [abcba] x -> 1 [x] ababacab -> 2 [aba, bacab] bacababa -> 2 [bacab, aba] 26600 -> 3 [2, 66, 00] [my user id] [who has a more perfect user id?] ababacabBACABABA -> 4 [aba, bacab, BACAB, ABA] ``` Note that in the examples anything in square brackets shouldn't be part of the output. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes ``` ~cL↔ᵐLl ``` [Try it online!](https://tio.run/nexus/brachylog2#@1@X7POobcrDrRN8cv7/V0pMSk5KUfofBQA "Brachylog – TIO Nexus") ### Explanation ``` ~cL Deconcatenate the input into L L↔ᵐL Reversing all elements of L results in L Ll Output = length(L) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ ~~12~~ 11 bytes ``` ~~ŒṖLÞŒḂ€P$ÐfḢL~~ ~~ŒṖLÞṚ€⁼$ÐfḢL~~ ŒṖṚ€⁼$ÐfL€Ṃ ŒṖ obtain partitions Ðf filter for partitions which Ṛ€ after reversing each subpartition ⁼ is equal to the partition L€ length of each successful partition Ṃ minimum ``` [Try it online!](https://tio.run/nexus/jelly#@3900sOd0x7unPWoac2jxj0qhyek@QCZD3c2/f//XykxCQiTE5OUAA "Jelly – TIO Nexus") ### Specs * Input: `"ababacab"` (as argument) * Output: `2` [Answer] # Pyth, 9 bytes ``` lh_I#I#./ ``` [Test suite](https://pyth.herokuapp.com/?code=lh_I%23I%23.%2F&test_suite=1&test_suite_input=%221111%22%0A%22abcb%22%0A%22abcbd%22%0A%22abcde%22%0A%2266a%22%0A%22abcba%22%0A%22x%22%0A%22ababacab%22%0A%22bacababa%22%0A%2226600%22&debug=0) This forms all partitions of the input, from shortest to longest. Then, it filters those partitions on invariance under filtering the elements on invariance under reversal. Finally, we take the first element of the filtered list of partitions, and return its length. To explain that complicated step, let's start with invariance under reversal: `_I`. That checks whether its input is a palindrome, because it checks whether reversing changes the value. Next, filtering for palindromicity: `_I#`. This will keep only the palindromic elements of the list. Next, we check for invariance under filtering for palindromicity: `_I#I`. This is truthy if and only if all of the elements of the list are palindromes. Finally, we filter for lists where all of the elements of the list are palindromes: `_I#I#`. [Answer] # [Haskell](https://www.haskell.org/), 83 bytes ``` f s=minimum[length x|x<-words.concat<$>mapM(\c->[[c],c:" "])s,all((==)=<<reverse)x] ``` [Try it online!](https://tio.run/nexus/haskell#HY49DoMwDIX3nMJCDIn4Ee3AUBFu0BMAgwlpiZSEioSSoXenAT/p87PkZ/l4geNGWWU202lp336G8AtNsS/r5EqxWIG@SVuDnyftRdF2nRhy8UggGZjLUWtKOWe8aVb5lauTLAyHQWWBg7Jerig8pLBZrax0UEI8BLR3ULTgIMsgOV1yOjcvO9D4DwMWF6/AcYtFcBTjhenkJEld4zUjCbFHCRzJxShyr@uq@gM "Haskell – TIO Nexus") This uses Zgarb's great [tip for generating string partitions](https://codegolf.stackexchange.com/a/98446/56433). ``` f s = minimum[ -- take the minimum of the list length x | -- of the number of partitions in x x<-words.concat<$>mapM(\c->[[c],c:" "])s -- where x are all partitions of the input string s , all((==)=<<reverse)x -- where each partition is a palindrome. ] ``` [Answer] ## Clojure, 111 bytes ``` (defn f[s](if(=()s)0(+(apply min(for[i(range(count s))[a b][(split-at(inc i)s)]:when(=(reverse a)a)](f b)))1))) ``` Splits at all possible positions, and when the first part is a palindrome proceeds to find a partitioning for the remaining of the string. [Try it online](https://tio.run/nexus/clojure#Zc6xCgIxDAbg3acInRJE0FXwSUqHpNdq4S5X2nqHT392cqgJ//JBfnLgFKJCtNVhivhAqnTFM3LO8weWpBjXYhMW1mdAv761QSWyDOIs1jynduGGST2kfuru@ytorylhC6UGYGJyGEGI6NZzYC5J26wnAFw4bxDBGpa@nsV0/Y1hFvH/NIj4aQqjifBIIxjXv/kC). Ungolfed, uses [thread-last macro](https://clojuredocs.org/clojure.core/-%3E%3E) `->>`. ``` (defn f [s] (if (empty? s) 0 (let [results (for[i (range(count s))] (let [[a b] (split-at (inc i) s)] (when (= a (reverse a)) (f b))))] (->> results ; Take results (a list of integers and nils), (filter some?) ; remove null values (they occur when "a" is not a palindrome) (apply min) ; find the minium value, inc)))) ; and increment by one. ``` An obscure version, please do not write code like this :D ``` (defn f [s] (->> (f b) (when (= a (reverse a))) (let [[a b] (split-at (inc i) s)]) (for[i (range(count s))]) (filter some?) (apply min) inc (if (empty? s) 0))) ``` [Answer] ## JavaScript (ES6), ~~143~~ ~~126~~ 124 bytes *Saved 2 bytes thanks to Neil* Inspired by [NikoNyrh](https://codegolf.stackexchange.com/a/117469/58563) method. ``` s=>(r=1/0,F=(s,i=1,p=0)=>s[p++]?([...o=s.slice(0,p)].reverse().join``==o&&(s[p]?F(s.slice(p),i+1):r=r<i?r:i),F(s,i,p)):r)(s) ``` ### Formatted and commented ``` s => ( // given a string 's': r = 1 / 0, // 'r' = best score, initialized to +Infinity F = ( // 'F' is a recursive function that takes: s, // - the current string 's' i = 1, // - a substring counter 'i' p = 0 // - a character pointer 'p' ) => // s[p++] ? ( // if we haven't reached the end of the string: [...o = s.slice(0, p)] // compute 'o' = substring of length 'p' .reverse().join`` == o // if 'o' is a palindrome, && ( // then: s[p] ? // if there are still characters to process: F(s.slice(p), i + 1) // do a recursive call on the remaining part : // else: r = r < i ? r : i // update the score with r = min(r, i) ), // in all cases: F(s, i, p) // do a recursive call with a longer substring ) : // else: r // return the final score )(s) // initial call to F() ``` ### Test cases ``` let f = s=>(r=1/0,F=(s,i=1,p=0)=>s[p++]?([...o=s.slice(0,p)].reverse().join``==o&&(s[p]?F(s.slice(p),i+1):r=r<i?r:i),F(s,i,p)):r)(s) console.log(f('1111')) // -> 1 [1111] console.log(f('abcb')) // -> 2 [a, bcb] console.log(f('abcbd')) // -> 3 [a, bcb, d] console.log(f('abcde')) // -> 5 [a, b, c, d, e] console.log(f('66a')) // -> 2 [66, a] console.log(f('abcba')) // -> 1 [abcba] console.log(f('x')) // -> 1 [x] console.log(f('ababacab')) // -> 2 [aba, bacab] console.log(f('bacababa')) // -> 2 [bacab, aba] ``` --- ## Initial approach, ~~173~~ 168 bytes A pretty long recursive function that computes all possible partitions of the input string. ``` f=(s,b=1/(k=0))=>++k>>(L=s.length)?b:f(s,(k|1<<30).toString(2).slice(-L).match(/(.)\1*/g).some(m=>[...o=s.slice(i,i+=m.length)].reverse(n++).join``!=o,n=i=0)?b:b<n?b:n) ``` ### Formatted and commented ``` f = ( // given: s, // - a string 's' b = 1 / (k = 0) // - a best score 'b' (initialized to +Infinity) ) => // - a counter 'k' (initialized to 0) ++k >> (L = s.length) ? // if 'k' is greater or equal to 2^(s.length): b // stop recursion and return 'b' : // else: f( // do a recursive call: s, // using the same string 's' (k | 1 << 30) // compute an array containing the groups of identical .toString(2).slice(-L) // digits in the binary representation of 'k', padded .match(/(.)\1*/g) // with leading zeros and cut to the length of 's' .some(g => // for each group 'g' in this array: [... o = s.slice( // compute 'o' = corresponding substring of 's', i, i += g.length // starting at position 'i' with the same length )] // (e.g. s = 'abcd' / k = 0b1101 => 'ab','c','d') .reverse(n++) // increment the number of groups 'n' .join`` != o, // return true if this substring is NOT a palindrome n = i = 0 // initialize 'n' and 'i' ) ? // if some() returns true: b // invalid partition -> keep the previous score 'b' : // else: b < n ? b : n // valid partition -> use min(b, n) ) // end of recursive call ``` ### Test cases ``` f=(s,b=1/(k=0))=>++k>>(L=s.length)?b:f(s,(k|1<<30).toString(2).slice(-L).match(/(.)\1*/g).some(m=>[...o=s.slice(i,i+=m.length)].reverse(n++).join``!=o,n=i=0)?b:b<n?b:n) console.log(f('1111')) // -> 1 [1111] console.log(f('abcb')) // -> 2 [a, bcb] console.log(f('abcbd')) // -> 3 [a, bcb, d] console.log(f('abcde')) // -> 5 [a, b, c, d, e] console.log(f('66a')) // -> 2 [66, a] console.log(f('abcba')) // -> 1 [abcba] console.log(f('x')) // -> 1 [x] console.log(f('ababacab')) // -> 2 [aba, bacab] console.log(f('bacababa')) // -> 2 [bacab, aba] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒṖŒḂ€¬$ÞḢL ``` **[Try it online!](https://tio.run/nexus/jelly#@3900sOd04DEjqZHTWsOrVE5PO/hjkU@/4/uOdwOFPAG4sj//6PVDYFAXUc9MSk5CUqlQOiUVCBtZpYIFQXRFWA2ECYnghSD6USwjJGZmYGBeiwA "Jelly – TIO Nexus")** ### How? Uses the fact that `[0]<[0,0]<[0,0,0],...,<[0,...,0,1]<...` - thus if we sort the partitions by a key "is not palindromic for each part" the first entry will be all palindromic and of minimal length. *Note: any non-empty string of length **n** will always result in such a key with **n** zeros, since all length **1** strings are palindromic.* ``` ŒṖŒḂ€¬$ÞḢL - Main link: s e.g. 'abab' ŒṖ - partitions of s [['a','b','a','b'],['a','b','ab'],['a','ba','b'],['a','bab'],['ab','a','b'],['ab','ab'],['aba','b'],['abab']] Þ - sort by (create the following key and sort the partitions by it): $ - last two links as a monad: (key evaluations aligned with above:) ŒḂ€ - is palindromic? for €ach [ 1 , 1 , 1 , 1 ] [ 1 , 1 , 0 ] [ 1 , 0 , 1 ] [ 1 , 1 ] [ 0 , 1 , 1 ] [ 0 , 0 ] [ 1 , 1 ] [ 0 ] ¬ - not [ 0 , 0 , 0 , 0 ] [ 0 , 0 , 1 ] [ 0 , 1 , 0 ] [ 0 , 0 ] [ 1 , 0 , 0 ] [ 1 , 1 ] [ 0 , 0 ] [ 1 ] - ...i.e.: - making the sorted keys: [[ 0 , 0 ],[ 0 , 0 ],[ 0 , 0 , 0 , 0 ],[ 0 , 0 , 1 ],[ 0 , 1 , 0 ],[ 1 ],[ 1 , 0 , 0 ],[ 1 , 1 ]] - hence the sorted partitions: [['a','bab'],['aba','b'],['a','b','a','b'],['a','b','ab'],['a','ba','b'],['abab'],['ab','a','b'],['ab','ab']] Ḣ - head of the result ['a','bab'] L - length 2 ``` [Answer] ## [Haskell](https://www.haskell.org/), 69 bytes ``` x!(a:b)|p<-a:x=p!b++[1+f b|p==reverse p] x!y=[0|x==y] f=minimum.(""!) ``` Defines a function `f`. [Try it online!](https://tio.run/nexus/haskell#NYtBCoMwFET3nuIndJGgFu0iC@nvDXoCK@VHI2QRCaYtEby7tVpnFvOGYZbIBFVazv6aUxXRM52mdZn2oGePOJqPGYMB3ySRTVgXc0ScmqRHZwfr3u4sOGdycWQHQHDk708QjwD5DfxohxeIkEEPQUo4Qc3LVTwDTrrVR3Z/6MwPlKJj2CDubXVL22UD2seLUkXBm@UL "Haskell – TIO Nexus") ## Explanation The infix helper function `x ! y` computes a list of integers, which are the lengths of some splittings of `reverse x ++ y` into palindromes where `reverse x` is left intact. It is guaranteed to contain the length of the minimal splitting if `y` is nonempty. How it works is this. * If `y` is nonempty, a char is popped off it and pushed into `x`. If `x` becomes a palindrome, we call the main function `f` on the tail of `y` and add 1 to account for `x`. Also, we call `!` on the new `x` and `y` to not miss any potential splitting. * If `y` is empty, we return `[0]` (one splitting of length 0) if `x` is also empty, and `[]` (no splittings) otherwise. The main function `f` just calls `"" ! x` and takes the minimum of the results. ``` x!(a:b)| -- Function ! on inputs x and list with head a and tail b, p<-a:x= -- where p is the list a:x, is p!b++ -- the numbers in p!b, and [1+f b| -- 1 + f b, p==reverse p] -- but only if p is a palindrome. x!y= -- Function ! on inputs x and (empty) list y is [0| -- 0, x==y] -- but only if x is also empty. f= -- Function f is: minimum.(""!) -- evaluate ! on empty string and input, then take minimum. ``` [Answer] ## JavaScript (Firefox 30-57), 97 bytes ``` f=(s,t=``,i=0)=>s?Math.min(...(for(c of s)if([...t+=c].reverse(++i).join``==t)1+f(s.slice(i)))):0 ``` ES6 port: ``` f=(s,t=``)=>s?Math.min(...[...s].map((c,i)=>[...t+=c].reverse().join``==t?1+f(s.slice(i+1)):1/0)):0 ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` It seems such a simple solution that I keep thinking I've forgotten something but it does at least pass all the test cases. [Answer] # Haskell, ~~139~~ ~~116~~ 109 bytes ``` h[]=[[]] h x=words.concat<$>mapM(\c->[[c],c:" "])x r x=reverse x==x g x=minimum[length y|y<-h x,and$r<$>y] ``` Still green at Haskell golfing but here is my best attempt I can come up with quickly. * h is a function that creates a List of all possible contiguous subsequences of a List (like a string). It takes the input String and breaks it out for g. * r is a simple function that returns a Boolean for if a List is a palindrome * g is the main function that takes an input List, calls h to get the list of contiguous subsequence possibilities, filters on `(and.map r)` to remove sub lists that do not contain a palindrome, at which point length is applied to the list, and then the result is sorted so we can grab the head which is the answer. I was thinking a better answer might be able to leverage the non-deterministic nature of Lists in Haskell through the use of Applicatives. It might be possible to shave many bytes off of function h by using applicatives, even if we have to import Control.Applicative. Comments for improvement are welcome. **UPDATE1** Huge savings based on Laikoni's reminder about the minimum function. Removing sort actually allowed me to drop the Data.List import because minimum is defined in Prelude! **UPDATE2** Thanks to nimi's suggestion about using list comprehensions as a useful replacement for filter.map. That saved me a few bytes. Also I borrowed the neat String partition trick from Laikonis answer and saved a couple bytes there as well. [Answer] # PHP, 319 Bytes ``` for(;$i<$l=strlen($s=$argn);$i++)for($j=$l-$i;$j;$j--)strrev($r=substr($s,$i,$j))!=$r?:$e[+$i][]=$r;uasort($e,function($a,$b){return strlen($b[0])<=>strlen($a[0])?:count($a)<=>count($b);});foreach($e as$p=>$v)foreach($v as$w){$s=preg_replace("#^(.{{$p}})$w#","$1".str_pad("",strlen($w),"ö"),$s,1,$c);!$c?:++$d;}echo$d; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/94f45855398aa600106e2799dfa7fdc602638619) Expanded ``` for(;$i<$l=strlen($s=$argn);$i++) for($j=$l-$i;$j;$j--)strrev($r=substr($s,$i,$j))!=$r?:$e[+$i][]=$r; #Make all substrings that are palindromes for each position uasort($e,function($a,$b){return strlen($b[0])<=>strlen($a[0])?:count($a)<=>count($b);}); # sort palindrome list high strlen lowest count for each position foreach($e as$p=>$v) foreach($v as$w){ $s=preg_replace("#^(.{{$p}})$w#","$1".str_pad("",strlen($w),"ö"),$s,1,$c); !$c?:++$d; # raise count } echo$d; # Output ``` [Longer Version without E\_NOTICE and Output the resulting array](http://sandbox.onlinephpfunctions.com/code/b7cc8da273bf5a80e6c29a69f5b0e5828aef0436) ]
[Question] [ Draw the path of [Langton's ant](http://en.wikipedia.org/wiki/Langton%27s_ant). ### Description > > Squares on a plane are colored variously either black or white. We arbitrarily identify one square as the "ant". The ant can travel in any of the four cardinal directions at each step it takes. The ant moves according to the rules below: > > > * At a white square, turn 90° right, flip the color of the square, move forward one unit > * At a black square, turn 90° left, flip the color of the square, move forward one unit > > > ### Specifications * Input: an integer N between 0 and 725 (inclusive). * Output: a 17 by 17 grid representing the "path" of the ant as of step N. ### Rules * The ant starts facing right (3 o' clock). * The ant starts at the center of the grid. * Use `_#@` for white squares, black squares and the ant respectively. * The grid is initially completely white. * You may make either a complete program or a function on an interpreted language. * Input by stdin or argument. ### Examples **Update:** case's N = 450 output was wrong. N = 0 ``` _________________ _________________ _________________ _________________ _________________ _________________ _________________ _________________ ________@________ _________________ _________________ _________________ _________________ _________________ _________________ _________________ _________________ ``` N = 1 ``` _________________ _________________ _________________ _________________ _________________ _________________ _________________ _________________ ________#________ ________@________ _________________ _________________ _________________ _________________ _________________ _________________ _________________ ``` N = 450 ``` _________________ _________________ ___________##____ ____##______##___ ___#__##___##_#__ __###_#@#__#__#__ __#_#_#_#__#_#___ _____###___#_____ _____#___________ _____#__###______ ___#_#_#__#_#_#__ __#__#_#____###__ __#_##__##___#___ ___##______##____ ____##___________ _________________ _________________ ``` [Answer] ## GolfScript - 67 chars ``` ~17.'_'*n+*\153:|;{|/()[124^.2/6+:6.1&17*)\2&(*|+:|;]@++}*|/();'@'@ ``` hallvabo's Python solution is the most similar to this, so I'll only describe the main differences. The board is stored as a string instead of an array. This is so we can update a value on the board with less characters (as strings are always flat), and so getting it to the desired output format is easy. The ant position is incremented by the formula `((d&1)*17+1)*((d&2)-1)` (i.e. `.1&17*)\2&(*`), where d is the direction. We use the variable `6` so we can skip initialization. [Answer] ## Ruby 1.9, 104 characters ``` f=->z{l=[*[r=1]*17,2]*17;c=152;z.times{c+=r=(r*r>1?r/18:-r*18)*l[c]*=-1};l[c]=0;l.map{|a|putc"@_ #"[a]}} ``` Input via function argument. * (146 -> 142) Inlined `m` * (142 -> 140) Check for `r*r>1` instead of `r.abs>1` * (142 -> 128) Use `String#scan` to generate the output. Changed a `==` to `>` * (128 -> 125) Removed obsolete variable * (125 -> 122) Replace `String#tr` with a conditional * (122 -> 122) Now generates the same output as the updated examples * (122 -> 111) Use ints instead of chars when generating the ant's path. * (111 -> 109) Reorder some expressions to save parentheses * (109 -> 108) Code is now a function * (108 -> 104) Print every character individually [Answer] ## Python, 123 ``` n=input() d=x=152 g=(17*[95]+[10])*17 while n:d+=g[x]/2;g[x]^=124;x+=(1,-18,-1,18)[d%4];n-=1 g[x]=64 print"%c"*306%tuple(g) ``` Just a slight reworking of my Python solution from <http://golf.shinh.org/p.rb?Langtons+Ant>. [Answer] # GolfScript 96 94 89 My favourite hate language is back with another bunch of of semi-readable sorta-bytecode. 89 version, I finally managed to integrate @ into the output loop. ``` ~289[0:c]*145:b;{.b>\b<)!..c++(4%:c[1 17-1-17]=b+:b;@++}@*{{(b(:b!.++'_#@@'1/=\}17*n\}17* ``` 94 version: ``` ~306[0:c]*152:b;{.b<\b>(!..c++(4%:c[1 18-1-18]=b+:b;\++}@*{{('_#'1/=\}17*(;n\}17*].b<\b>(;'@'\ ``` Commented: ``` #Initialization. ~ #Parse input. 306[0:c]* #Make array of 306 0s, set c to 0 in the middle of that operation. 152:b; #Set b to 152, remove 152 from the stack. #b is a value for the ant's position, c for its rotation. #Run the algorithm. { #Start of block. .b<\b>( #Split the array at index b into before, after and value at b. !.. #Not the value and make 2 copies of it. c++ #Add the 2 copies to c. (4%:c #Subtract 1, modulus by 4 and save the result to c. [1 18-1-18]= #Define an array and take element number c. b+:b; #Add b to the value, save result to b, remove result from stack. \++ #Reform the array. }@* #Switch the input to the top of the stack and run the block input times. #Convert array of 1s and 0s to the correct characters. { #Start of block. { #Start of block. ('_#'1/= #Take the first array element, convert it to either '_' or '#'. \ #Switch the array to the top of the stack. }17* #Execute block 17 times. (;n\ #Discard the 18th element of the line, write a lineshift. }17* #Execute block 17 times. #Insert the @. ] #Put everything in an array. .b<\b>( #Split the array at index b into before, after and value at b. ;'@'\ #Ditch the value at b, write a @ and shift it into place. ``` Edit, I might as well make a big version, here goes 59\*59 and 10500 iterations: ``` ~59:a.*[0:c]*1741:b;{.b>\b<)!..c++(4%:c[1 a-1-59]=b+:b;@++}@*{{(b(:b!.++'_#@@'1/=\}a*n\}a* ``` . ``` ___________________________________________________________ ___________________________________________________________ _________________________##__##____________________________ ________________________#__@_###___________________________ _______________________###__#_#_#__________________________ _______________________#####_#__##_________________________ ________________________#___##_##_#________________________ _________________________###___#__##_______________________ __________________________#___##_##_#______________________ ___________________________###___#__##_____________________ ____________________________#___##_##_#__##________________ _____________________________###___#__##__##_______________ ______________________________#___##_##__##___#____________ ________________________####___###___#___#__###____________ _______________________#____#___#___##_####___#____________ ______________________###____#___#_#______#_##_#___________ ______________________###____#_##_____#_##__#_##___________ _______________________#____#___##_#_#_____##______________ _______________________#_#______#_#####__#___#_____________ ______________________#___#####__________##_######_________ ______________________###__##__#_##_#_#_#___##_#_##________ ____________________##__#_#######_#___#__###____##_#_______ ___________________#__#__######_##___#__#_##___#___#_______ __________________#____#_#_##_#__######_#######___#________ __________________#_####_##_#_####____##__##_#_##_#________ ___________________#____####___#__#_######_##____###_______ ______________________#___#_##_#_###_#__##__##___###_______ _________________________#######____#__##_##_#_____#_______ _________________####__##_##__####_##_##_##__#_____#_______ ________________#____#_#___###_##_###____#_####____#_______ _______________###_______###_#_#_#####____#_#______#_______ _______________#_#___###_####_##_#___##_###_##_____#_______ _____________________##_##__####____####_#_#_#_____#_______ ________________#____#__##___###__###_____###______#_______ ________________##___##_###_####__#______###___##__#_______ ________________##_#_####_____#___#__#_##_###_##___#_______ _______________####_##___##_####__#_#__#__#__###___#_______ _______________#_##_###__#_#_##_#_#_____#_#_____#_#________ ___________________#_#__#____##_##__#_#__###_##____________ ___________________##_#____#__#####_#____#____#__#_#_______ __________________#_##_#__#____##_##_#__###______###_______ ________________#_#___#__#__#__#__###___##__##____#________ _______________###_#_#####_######_###_#######_#_##_________ _______________#_#_#____#####___##__#####_#####____________ _________________#__##___#______#__#_##__###_###___________ ______________####___#####_#########___#_#_________________ _________##____#__#_____###_#_#___#_###__###_______________ ________#__#__####_##___###_##___###_##_____##_____________ _______###____#_##_#_#####___#____#__#__##_###_____________ _______#_#####_#_#___##__##_____#____#___#__#______________ ___________######_####__##_#___#__##__#_#_##_______________ _________##______#_###_##__####___#___###__________________ __________#__#_#####__#___#_##___#__#__#___________________ __________##_###_#######_____#_____#_##____________________ _________#_#__##_##______#___##____#_______________________ ________#__#_####________###__##__#________________________ ________#_##_###____________##__##_________________________ _________##________________________________________________ __________##_______________________________________________ ``` [Answer] ## Windows PowerShell, ~~119~~ 118 ``` for($p,$n,$g=144,+"$args"+,1*289;$n--){$d+=$g[$p]*=-1 $p+='B0@R'[$d%4]-65}$g[$p]=0 -join'@_#'[$g]-replace'.{17}',"$& " ``` [Answer] ## PHP, ~~350~~ ~~309~~ ~~307~~ ~~312~~ ~~174~~ ~~161~~ ~~166~~ ~~159~~ ~~151~~ ~~149~~ ~~147~~ ~~144~~ 143 ``` <?$p=144;while($i=$argv[1]--){$g[$p]=$a=2-$g[$p];$d+=--$a;$p+=(1-($d&2))*(1+16*($d&1));}while($i++<288)echo$i%17?$i!=$p?$g[$i]?"#": _:"@":"\n"; ``` **Ungolfed** ``` $p = 144; // Set initial pointer while($i = $argv[1]--){ // Ends at -1 $g[$p] = $a = 2 - $g[$p]; // Either returns true (2) or false(0) $d += --$a; // Adds 1 (2-1) or removes 1 (0-1) from the direction $p += (1 - ($d & 2)) * (1 + 16 * ($d & 1)); } while($i++ < 288) echo $i % 17? $i != $p? $g[$i]? "#" : @_ : "@" : "\n"; // Prints the correct character ``` **350 -> 309:** Various compression techniques with the for() loops, also updated to show correct output. **309 -> 307:** Converted main for() loop to a while() loop. **307 -> 312:** Forgot to change it to use argv. **312 -> 174:** Recoded based on another answer. **174 -> 161:** No longer defaults entire array. **161 -> 166:** Argv wins again. **166 -> 159:** No need to redefine argv[1]. **159 -> 151:** No longer defaults anything, PHP does it automatically. **151 -> 149:** Removed a set of parenthesis, order of operations removes the need. **149 -> 147:** Shortened the last for() loop, braces not needed. **147 -> 144:** Last for() loop is now a while() loop. **144 -> 143:** Used a temporary variable to save a character. [Answer] ## C, 166 162 Here a translation of my Delphi-approach to C, showing off how compact C can be. I borrowed the conditional newline trick from fR0DDY (thanks mate!) : ``` g[289]={0},a=144,d,i,N;main(){scanf("%d",&N);while(N--)g[a]=2-g[a],d+=g[a]-1,a+=(1-(d&2))*(1+d%2*16);for(g[a]=1;i<289;)printf("%s%c",i++%17?"":"\n","_@#"[g[i]]);} ``` The indented, commented version looks like this : ``` g[289]={0}, // g: The grid is initially completely white. (size=17*17=289) a=144, // a: Ant position starts at the center of the grid (=8*17+8=144) d, // Assume 0=d: Ant start 'd'irection faces right (=0, see below) i, N; main(){ scanf("%d",&N); while(N--) // Flip the color of the square: g[a]=2-g[a], // Turn 90° right if at an '_' space, 90° left otherwise : d+=g[a]-1, // Move one unit forward; // For this, determine the step size, using the two least significant bits of d. // This gives the following relation : // 00 = 0 = 90° = right = 1 // 01 = 1 = 180° = down = 17 // 10 = 2 = 270° = left = - 1 // 11 = 3 = 0° = up = -17 // (d and 2) gives 0 or 2, translate that to 1 or -1 // (d and 1) gives 0 or 1, translate that to 1 or 17 // Multiply the two to get an offset 1, 17, -1 or -17 : a+=(1-(d&2))*(1+d%2*16); // Place the ant and print the grid : for(g[a]=1;i<289;) printf("%s%c",i++%17?"":"\n","_@#"[g[i]]); // 0 > '_', 1='@', 2 > '#' } ``` [Answer] # Delphi, 217 ``` var g,a:PByte;i,d,Word;begin g:=AllocMem(306);a:=g+153;Read(i);for n:=1to i do begin a^:=2-a^;d:=d-1+a^;a:=a+(1-2and d)*(1+17*(1and d))end;a^:=1;for n:=1to 306do if n mod 18=0then WriteLn else Write('_@#'[1+g[n]])end. ``` The indented & commented code reads like this: ``` var g,a:PByte; i,d,n:Int32; begin g:=AllocMem(306); // g: The grid is initially completely white. (size=18*17=306) // Assume 0=d: Ant start 'd'irection faces right (=0, see below) a:=g+153; // a: Ant position starts at the center of the grid (=8*18+9=153) Read(i); for n:=1to i do begin // Flip the color of the square; a^:=2-a^; // Turn 90° right if at an '_' space, 90° left otherwise; d:=d-1+a^; // Move one unit forward; // For this, determine the step size, using the two least significant bits of d. // This gives the following relation : // 00 = 0 = 90° = right = 1 // 01 = 1 = 180° = down = 18 // 10 = 2 = 270° = left = - 1 // 11 = 3 = 0° = up = -18 // (d and 2) gives 0 or 2, translate that to 1 or -1 // (d and 1) gives 0 or 1, translate that to 1 or 18 // Multiply the two to get an offset 1, 18, -1 or -18 : a:=a+(1-2and d)*(1+17*(1and d)) end; // Place the ant and print the grid : a^:=1; // 0 > '_', 1='@', 2 > '#' for i:=1to 306do if i mod 18=0then // we insert & abuse column 0 for newlines only (saves a begin+end pair) WriteLn else Write('_@#'[1+g[i]]) end. ``` Input: ``` 450 ``` Output : ``` _________________ _________________ ___________##____ ____##______##___ ___#__##___##_#__ __###_#@#__#__#__ __#_#_#_#__#_#___ _____###___#_____ _____#___________ _____#__###______ ___#_#_#__#_#_#__ __#__#_#____###__ __#_##__##___#___ ___##______##____ ____##___________ _________________ _________________ ``` [Answer] **C 195 Characters** ``` x=144,T,p=1,i,N[289]={0},a[]={-17,1,17,-1};c(t){p=(p+t+4)%4;x+=a[p];}main(){scanf("%d",&T);while(T--)N[x]=(N[x]+1)%2,c(N[x]?1:-1);for(;i<289;i++)printf("%s%c",i%17?"":"\n",i-x?N[i]?'#':'_':'@');} ``` <http://www.ideone.com/Dw3xW> I get this for 725. ``` _________________ _________________ ___________##____ ____##______##___ ___#___##__##_#__ __###____#_#__#__ __#_#_#__#_#_#___ ______###____#__@ _______###__#__#_ _____#_#____#___# ___#_#_#_##____#_ __#__#_#_#_#_###_ __#_##_#_____#### ___##_#____#_#### ____###___####_#_ _______#__#__##__ ________####_____ ``` [Answer] ## sed, 481 chars ``` #n 1{s/.*/_________________/;h;H;H;H;G;G;G;G;s/^\(.\{152\}\)_/\1@/;s/$/;r/;ta;};x;:a;/;r/br;/;d/bd;/;l/bl;/;u/bu;:w;y/rdlu/dlur/;bz;:b;y/rdlu/urdl/;bz;:r;s/@\(.\{17\}\)_/#\1@/;tw;s/@\(.\{17\}\)#/#\1!/;tw;s/_\(.\{17\}\)!/@\1_/;tb;s/#\(.\{17\}\)!/!\1_/;tb;:d;s/_@/@#/;tw;s/#@/!#/;tw;s/!_/_@/;tb;s/!#/_!/;tb;:l;s/_\(.\{17\}\)@/@\1#/;tw;s/#\(.\{17\}\)@/!\1#/;tw;s/!\(.\{17\}\)_/_\1@/;tb;s/!\(.\{17\}\)#/_\1!/;tb;:u;s/@_/#@/;tw;s/@#/#!/;tw;s/_!/@_/;tb;s/#!/!_/;tb;:z;h;${s/!/@/;s/;.//p} ``` May be reduced to 478 chars by removing first line and running with `-n` Requires N lines for input, eg. when run as ``` seq 450 | sed -f ant.sed ``` outputs: ``` _________________ _________________ ___________##____ ____##______##___ ___#__##___##_#__ __###_#@#__#__#__ __#_#_#_#__#_#___ _____###___#_____ _____#___________ _____#__###______ ___#_#_#__#_#_#__ __#__#_#____###__ __#_##__##___#___ ___##______##____ ____##___________ _________________ _________________ ``` [Answer] # Perl, 110 characters ``` $p=144;$p+=(1,-17,-1,17)[($d+=($f[$p]^=2)+1)%4]for 1..<>;$f[$p]=1;print$_%17?'':$/,qw(_ @ #)[$f[$_]]for 0..288 ``` Number is read from the first line of STDIN. Rest of input is ignored. ### Slightly more readable: ``` $p=144; $p += (1,-17,-1,17)[($d+=($f[$p]^=2)+1) % 4] for 1..<>; $f[$p]=1; print $_%17 ? '' : $/, qw(_ @ #)[$f[$_]] for 0..288 ``` ### Edits * **(112 → 111)** No need to update `$d` with the modulo-4 value. * **(111 → 110)** Can now inline the `$d` increment ### Addendum (109 characters) We can have it one character shorter if you’re happy to have the special case of `N=0` fail (it doesn’t output the `@` character for the ant). All other inputs work correctly: ``` $p+=(1,-17,-1,17)[($d+=($f{$p+0}^=2)+1)%4]for 1..<>;$f{$p}=1;print$_%17-9?'':$/,qw(_ @ #)[$f{$_}]for-144..144 ``` The differences are that we now use `%f` instead of `@f` so we can use negative indices, and we iterate from `-144..144` instead of `0..288`. It saves having to initialise `$p`. [Answer] # ><>, 122 bytes At the risk of a little thread necromancy, I thought writing an answer in ><> would be an interesting challenge... ``` 1&f8r\ 1-:?!\r:@@:@$:@@:@g:2*1+&+4%:&}1$-@p{:3$-5gaa*-$@+@5gaa*-+r 2}p70\~ a7+=?\:@@:@g4+5go$1+: o053.>~1+:64*=?;a dedc_#@ ``` This program expects the number of steps to compute to be present on the stack before execution. [Answer] # Mathematica, 94 chars ``` a@_=d=1;a@Nest[#+(d*=(a@#*=-1)I)&,9-9I,Input[]]=0;Grid@Array["@"[_,"#"][[a[#2-# I]]]&,17{1,1}] ``` [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 108 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {'@'@(⊂9 11○⊃⍵)⊢3⊃⍵}{p s g←⍵⋄(p+s)(s←s×0j1ׯ1 1['#_'⍳g[x]])(('_#'~g[x])@(x←⊂9 11○p)⊢g)}⍣⎕⊢9J9 0J1(17 17⍴'_') ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q1Z3UHfQeNTVZKlgaPhoevejruZHvVs1H3UtMoYwa6sLFIoV0h@1TQByHnW3aBRoF2tqFAP5xYenG2QZHp5@aL2hgmG0unK8@qPezenRFbGxmhoa6vHK6nUgjqaDRgVIM9yGApDh6Zq1j3oXP@qbCmRbelkqGHgZahiaKxiaP@rdoh6vrgkA&f=AwA&i=S@MyMTUAAA&r=tio&l=apl-dyalog&m=tradfn&n=f), [Alternate version](https://razetime.github.io/APLgolf/?h=e9Q31dP/UdsEAwA&c=q9ZQd1DXUVdW13/Uu@JR5yKjR13Nj3q3ajpoWCoYGj7qmPFoevehFY86uoCC0QYKRrGaj7oWGZorGJo/6t2iHq9eW12gUKyQ/qhtAlDBo@4WjQLtYk2NYiC/@PB0gyzDw9MPrTdUMIwuABqRHqup8ai3z/BRz171gnSgrTp16jCJ2ke9ix/1TQUabuFloWDgZfiodw0A&f=AwA&i=S@MyMTUAAA&r=tio&l=apl-dyalog&m=tradfn&n=f) A tradfn submission which takes a single number as input. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~5040~~ ~~4562~~ 4390 bytes ``` ,>,>,>++++++[->++++++++<]>[<<-<-<->>>>-]>++++++++>++++++++<<<<[>+>+<<-]>[<+>-]<<[>>+>+<<<-]>>[<<+>>-]<<<[>>>+>+<<<<-]>>>[<<<+>>>-]>[<+>[-]]<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-]<[-<<<<<[>>>>>+>-<<<<<<-]>>>>>-[<<<<<+>>>>>-]+>[<->[-]]<[-<<<<<[-]+++++++++<[>>>>>>+>-<<<<<<<-]>>>>>>-[<<<<<<+>>>>>>-]+>[<->[-]]<[<<<<<<++++++++++<->>>>>>>-]]<<<<[>>>>+<<<<-]<[>+>>>>>-<<<<<<-]>[<+>-]<<[>>+>>>>>-<<<<<<<-]>>[<<+>>-]<<<[>>>+>>>>>-<<<<<<<<-]>>>[<<<+>>>-]>>>>[<<<<+>>>>-]+>[<->[-]]<[<<<<->>>>-]<[>+++++++++++++++++>+<<-]>>[<<+>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-]<[>>[-]+<[>+<-]<-[>+<-]>]<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>[<<+>>-]<[<[<+>-]>-[<+>-]<]+<[>-<<<<->>>-]>[<<<<+>[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<<[>>>+++++++++++++++++>+<<<<-]>>>>[<<<<+>>>>-]<[>>>[-]<[>+<-]<+[>+<-]<-[>+<-]>]<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>[-[<+>-]<]<<-]<+<<<[>>>>+<<<<-]>>>>>++++<[->-[>+>>]>[+[<+>-]>+>>]<<<<<]>>[<<+<<<<+>>>>>>-]<<[-[-[<<->->-]<[<<->>-]>]<[<+>-]>]<[<<+>>-]<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-]<]>+[[-]>+[[-]<<[>>+>-<<<-]>>[<<+>>-]<<<[>>>+>+<<<<-]>>>[<<<+>>>-]+>[<->[-]]<<[>>+>-<<<-]>>[<<+>>-]<<<<<[>>>>>+>+<<<<<<-]>>>>>[<<<<<+>>>>>-]+>[<->[-]]<<[->[>+<-]<]>>[<<+>>-]<[-]+<[->+++++++[->++++++++<]>.<<]>[-<<<[>>>+>+++++++++++++++++<<<<-]>>>[<<<+>>>-]<<[>>+>+<<<-]>>[<<+>>-]>[>+[>+<-]<-[>+<-]>]<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>[<<+>>-]<[<[<+>-]>-[<+>-]<]+<[---[>--<+++++++]>--.[-]<]>[--[>++<-----]>-------.[-]<]<<]<<[>+>+<<-]>>+[<<+>>-]<----------------]++++++++++.[-]<[-]<[>+>+<<-]>>+[<<+>>-]<----------------] ``` [Try it online!](https://tio.run/##7VjLTsQwDPwg4xUHuEX5kSgHQEJCSByQ@P7i8SNNQ6sWjihTabe1HSd149npPn8@vX28fr28L8tdxkGKwn5ClGouKTGOLODaPGuIoGS5ljhEk0TBYibYkIKymmF3h3rggi/70MK1akwEWZTFWaQmKpySZ0OoXUUsb4Mlq6zeMvswMbblW441SWSJNJ5nSOSuNQ3nCKttZX6bWh71tQk2Zepc@@XqA36ULYpD@4vkqFimEf7IhvnWx9bNAgeqhjS4I7bvXNPEJfgumzgHzd1yFUFVE@doLFeSsS8IXllYaY2DLJWdlfgu/A4FRe9Ra4zp2Vmji9ExeJQmn/4VNLf09b3ftrrqERoEitGuiiHOrGpFmoC8TXClFXepsNFEEFPILq3D1lxoIt3JPlxt1HfLSU/JjKWwf7ok4d8oyU4CHY5etSOl47VsMsmJNWufyURRE8xb6XxDzVRz@mJH7Cz@QDpj7skVU39NDTZ12H/XYsxCcczxdi1OvhXl3QIPXrYB2BXmTKn2f0QIXcYkPGB9@Scd6nrswsBleXi8/wY "brainfuck – Try It Online") Input is zero padded. So for 5 iterations you type `005`. ]
[Question] [ # Challenge Bar Dice is a simple game played in a Bar with Dice (hence the name). You roll 5 six-sided dice and attempt to make the best hand. > > Scoring is based on amassing the largest number of dice with the same digits. Each hand must include at least a single "Ace", or one, in order to be a valid hand; Aces act as "wilds", and can be paired with any other digit. The strength of a player's hand depends first on the number of digits and then value of those digits. As an example, a hand (counting wilds) with four 3's is better than a hand with three 5's, but not better than a hand with five 2's. > > Taken from [the Wikipedia article](https://en.wikipedia.org/wiki/Bar_dice) > > > This means the highest ranked hand is made entirely of 6's and 1's, and the lowest ranked is any hand without a 1. Your challenge is to take two hands and return which player won, or if they tied. # Input Two unsorted lists of 5 numbers, ranging from 1 to 6. Each list represents a player's hand. The input format is flexible. # Output Any three distinct but consistent, static values (ranges are not allowed) signifying whether player 1 or player 2 won, or if it was a tie. Please state in your answer what values you are using for what. For example, you can return `-1` if P1 wins, `0` if it's a tie, and `1` if P2 wins. # Rules * Input will always be valid * Only the best possible score of each hand is used to determine a winner. There are no tie-breakers. E.g., `[1,4,4,3,3]` will tie `[1,4,4,2,2]` instead of using the 3's and 2's as a tie-breaker. * Output must be one of the 3 chosen values every time. Simply mapping all negative numbers to `P1 Wins` is not allowed and must be normalized. * Invalid hands, i.e. those with no 1's, lose to all valid hands but tie with all other invalid hands. E.g., `[2,2,2,2,2]` ties `[3,3,3,3,3]`. * A hand of `[1,1,1,1,1]` counts as a valid set of 6's for ranking purposes. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest byte count wins. # Examples ``` #You guys are pretty good at finding edge-cases that break things. Good job! Input: [2,1,5,6,6], [6,2,6,6,6] Output: P1 Wins Input: [2,4,5,6,6], [6,2,6,6,6] Output: Tie Input: [1,2,3,4,5], [5,4,3,2,1] Output: Tie Input: [1,5,5,3,2], [5,4,1,6,6] Output: P2 Wins Input: [3,2,2,2,1], [4,1,3,6,6] Output: P1 Wins Input: [1,1,1,1,1], [6,1,1,6,6] Output: Tie Input: [1,3,3,4,4], [1,2,2,5,5] Output: P2 Wins Input: [1,3,3,5,5], [1,3,3,2,2] Output: P1 Wins Input: [1,3,3,3,4], [1,1,3,3,3] Output: P2 Wins Input: [2,2,2,6,1], [5,3,3,1,2] Output: P1 Wins Input: [5,5,5,1,5], [1,1,1,1,1] Output: P2 Wins Input: [1,1,1,1,1], [1,1,5,1,1] Output: P1 Wins ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 14 bytes ``` ċⱮ6Ḣ©+$®aĖUṀ)M ``` [Try it online!](https://tio.run/##TY89DsIwDIX3noKBBeHFSZNbMDJVGRhYUC/AhlgY2BgQMxsSqtSNrqUcJL1IsJNajbzY/t7zz2Ff18cQhuvYNtZ/nv1rveyb3XDf@u602oTvZTy/fzffPUKoiqpSgGDAgnWwoEJDyaVzEFk5MwuKU2EIk5iZoURTA4UZCmoIw9nHMhWlxJjofOYUaR/mPhbyvpIZxhG0JGcm3ZIK4jnT4ptK@U/FpzDdyQTFZ@IPKDPlMFe4Pw "Jelly – Try It Online") A monadic link that takes a list of the two lists as its argument and returns `[1]` for player 1 wins, `[2]` for player 2 wins and `[1, 2]` for a tie. TIO link tidies this up for display. Thanks to @JonathanAllan for saving 3 bytes! ### Explanation ``` ) | For each input list (e.g. of one list 1,1,3,3,4) ċⱮ6 | - Count each of 1..6 (e.g. 2,0,2,1,0,0) $ | - Following as a monad: Ḣ | - Head (number of 1s) ©︎ | - Copy to register + | - Add (e.g. 2,4,3,0,0) ®a | - Register logical and with this Ė | - Enumerate (e.g. [1,2],[2,4],[3,3],[4,0],[5,0]) U | - Reverse each (e.g. [2,1],[4,2],[3,3],[0,4],[0,5]) Ṁ | - Max (e.g. 4,2) M | Index/indices of maximal score ``` [Answer] # [R](https://www.r-project.org/), ~~115~~ 96 bytes -6 bytes thanks to Giuseppe. -6 bytes thanks to Aaron Hayman. -2 bytes thanks to Arnauld, following the output format in his [JavaScript answer](https://codegolf.stackexchange.com/a/186462/86301). ``` function(i,j)(f(i)-f(j))/0 f=function(x,s=tabulate(x,6),l=s[1]+s[-1]*!!s[1])max(l)*6+order(l)[5] ``` [Try it online!](https://tio.run/##dY7NDkRAEITvnoLbNC27jXGQ9STiYC1CLImfxNvbnjERDpu5dM3XVV3T3tgv397rdSiXdhxEix2IWrTg16IDeDytOj3hhnO6FO@1L5aKRQzYp3NGuTdnPuWu4ygB32ITPbixN06fauIxk/neiFIESCgxVj67FDEGamYF1kGjv5QSibZM6NhUKRJDDPSmZB9dcvhfP9JUsfBCCc0zV@jmVbsh50Waks7hWzcantTos3@gO5NppRgnGCp1Z25@eo8WsP8A "R – Try It Online") Returns `Inf` for P1, `NaN` for a tie, `-Inf` for P2. Uses the helper function `f` which computes a score for each hand. The score is defined as follows: let `d` be the digit which is repeated the most, and `n` the number of times it is repeated. Then the score is `6*n+d` if there is at least one ace, and `0` if there are no aces. We then just need to find the player with the highest score. Ungolfed: ``` f = function(x) { s = tabulate(x, 6) # number of occurrences of each integer l = s[1] + s[-1] * !!s[1] # add the number of wild aces to all values; set to 0 if s[1] == 0 max(l) * 6 + # highest number of repetitions (apart from aces) order(l)[5] # most repeated integer (take largest in case of tie) } function(i, j){ sign(f(i) - f(j)) } ``` [Answer] # JavaScript (ES6), ~~97~~ 90 bytes Takes input as `(a)(b)`. Returns `+Infinity` for P1, `-Infinity` for P2 or `NaN` for a tie. ``` a=>b=>((g=(x,m)=>x>6?m*/1/.test(a):g(-~x,a.map(k=>n+=k<2|k==x,n=x/6)|m>n?m:n))()-g(a=b))/0 ``` [Try it online!](https://tio.run/##hY/BTsMwEETvfEWOa3Bi7NQ@VKz7CxyQOEQc3JJGIY1TNVHlQ8WvBzsuEpSSai@71oxn3oc5mn5zqPdDarv3ctziaFCvUQNUCI62BLXTatXeM86yoewHMGRZQfrpqMlas4cGtX3A5kmcGkRHLTqmyKnVdtUuLSFA0goMrglhj@Oms323K7NdV8EWCkE5lVRR9UagUFSENRwkYSx55slrbfu7P57F/56XurzUcy/JgyfopV9y/8Dn9NKPF33r@c9O4mqn8KWI30IRHPltDk7PEzn4r5yrvfKJYxH0fIqTAWquV/TIyB4PEcDme@UxKXrO53xOpFeRRU4OfpkzfgE "JavaScript (Node.js) – Try It Online") ### Commented ``` a => b => ( // a[] = dice of P1; b[] = dice of P2 ( g = ( // g is a recursive function taking: x, // x = dice value to test; initially, it is either undefined // or set to a non-numeric value m // m = maximum score so far, initially undefined ) => // x > 6 ? // if x is greater than 6: m * /1/.test(a) // return m, or 0 if a[] does not contain any 1 : // else: g( // do a recursive call: -~x, // increment x (or set it to 1 if it's non-numeric) a.map(k => // for each dice value k in a[]: n += // add 1 to n if: k < 2 | // k is equal to 1 k == x, // or k is equal to x n = x / 6 // start with n = x / 6 ) | // end of map() m > n ? // if m is defined and greater than n: m // pass m unchanged : // else: n // update m to n ) // end of recursive call )() // first call to g, using a[] - g(a = b) // subtract the result of a 2nd call, using b[] ) / 0 // divide by 0 to force one of the 3 consistent output values ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 15 bytes *-1 byte thanks to JonathanAllan* ``` εWΘ*6L¢ć+°ƶà}ZQ ``` [Try it online!](https://tio.run/##yy9OTMpM/W/u9v/c1vBzM7TMfA4tOtKufWjDsW2HF9RGBf7X@R8dbaRjqGOqY6ZjFqujEG2mYwRiAjmxXCApE1xShkCeMUgaJGUKZBgDBQyhUqZACOTDpAzhukCKjMAKgVIgCWMkA6EQYpchki6QMpBdJiApQ7ABQBtiYwE "05AB1E – Try It Online") Returns [1, 0] for P1 wins, [1, 1] for ties, [0, 1] for P2 wins. Rather than using lexicographic order on a 2-tuple (dice count, dice value), this computes the score as 10\*\*dice count \* dice value. Hands without a 1 score 5. ``` ε } # map each hand to its computed score WΘ # minimum == 1 (1 if the hand contains a 1, 0 otherwise) * # multiply (sets hands without 1 to [0, 0, 0, 0, 0]) 6L # range [1..6] ¢ # count occurences of each in the hand ć # head extract (stack is now [2-count, ..., 6-count], 1-count) + # add the 1-count to all the other counts ° # 10**x ƶ # multiply each element by its 1-based index à # take the maximum Z # maximum Q # equality test (vectorizes) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~85~~ ~~81~~ 80 bytes ``` lambda p:cmp(*[max((h.count(i)+h.count(i>1),i)*(1in h)for i in[6]+h)for h in p]) ``` [Try it online!](https://tio.run/##bY3NDoMgEITvPsUeQUkTQG1iYl@Ekob@WEkqEoNJ@/R2Qeup2TnMzLcL/hP60Ymla8/LywzXuwHf3AZPcjWYNyH94TbOLhBLi92eOGWW5oRbBz3txgksWKdqXaypxwRe0yWGSwyTcc8HOdImA9Na5@dAaAZ@si5ARwxdlGCcVaxmtWagaiaixZAhKP8Djl5GGEGFRmLBE6hwMP0A3y7igkhLCGIt96e2Wf/g@wVnIJNKVIRYiKQKpb8 "Python 2 – Try It Online") Returns `1` for P1, `0` for tie, and `-1` for P2. -1 byte, thanks to squid [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~60~~ 49 bytes ``` &[cmp]o*.map:{.{1}&&max (.{2..6}X+.{1})Z ^5}o&bag ``` [Try it online!](https://tio.run/##hZJNa4NAEIbP8VcMIfiRyIbVrAdDDz30UCg0lNKWGlts0SL4RYzQIP52O7urJQa6ZWGd3X3emXcGq/iQeX1@Aj2Bq14PPvMqLJckjyq/JS3tdD2PvsEkrUOI172s@J31Cm@sK/WP6Kvfakl5ADNLi7i2oNVmdXQC4yGum@zog2GDaewceE6LGmPjMY35Z0fljRUk5mJNbp6u76wVDbXZLE1gfVtUDWr39RLrLq31ViadL973xRyAI/fNERl86fqBhoDawwptCDzbwxD3UJOsD1hb035pB5@ZAATt8PCcHixOFBulYpqfIuByBacZBi5e0L9phguRkb7wPozwTMHTOSIlKjjv/uf/Yj5UPR@ekPvfcJqKUmhR5UgqmOxYHlClduTKKlIxHFU1ZM@e7IEJnqprMDFZOroaR6Ds42xOVPwmU4Ws8QM "Perl 6 – Try It Online") Returns `More`, `Same`, `Less` for `P1 Wins`, `Tie`, `P2 Wins`. ### Explanation ``` *.map: # Map input lists &bag # Convert to Bag { }o # Pass to block .{1}&& # Return 0 if no 1s max # Maximum of .{2..6} # number of 2s,3s,4s,5s,6s X+.{1} # plus number of 1s ( )Z # zipped with ^5 # secondary key 0,1,2,3,4 &[cmp]o # Compare mapped values ``` [Answer] # T-SQL query, 147 bytes Using table variable as input > > p: player > > > v: value for roll > > > ``` DECLARE @ table(p int,v int) INSERT @ values(1,5),(1,5),(1,5),(1,5),(1,5) INSERT @ values(2,4),(2,3),(2,3),(2,1),(2,4) SELECT sign(min(u)+max(u))FROM(SELECT(p*2-3)*(s+sum(1+1/~s-1/v))*(s/5*5+v+30)u FROM(SELECT*,sum(1/v)over(partition by p)s FROM @)c GROUP BY v,s,p)x ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1205977/who-won-a-game-of-bar-dice)** ``` Player 1 wins returns -1 Tie returns 0 Player 2 wins returns 1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) crushed before I even posted it by Nick Kennedy :) ``` ’-oÆṃṀ$$Ạ?fÆṃ$L;$o5)M ``` A monadic Link accepting a list of players which outputs a list of (1-indexed) winners. So P1 is `[1]`, P2 is `[2]` and a tie is `[1,2]`. **[Try it online!](https://tio.run/##y0rNyan8//9Rw0zd/MNtD3c2P9zZoKLycNcC@zQwV8XHWiXfVNP3/@H2o5Me7pzx/390tKGOMRCa6JjE6igAOUZAaKpjGhsLAA "Jelly – Try It Online")** [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~112~~ ~~126~~ ~~123~~ 121 bytes Takes input as `(a)(b)`. Returns `-1` for P1 win, `1` for P2 or `0` for a tie. ``` $args|%{$d=$($_-ne1|group|sort c*,n*|%{$m=$_};(7*(($o=($_-eq1).Count)+$m.Count)+$m.Name+6*!$m)[!$o])-$d} [math]::Sign($d) ``` [Try it online!](https://tio.run/##dZJda8IwFIbv@ysyOY6kpmOnNR04CoXd72aXIiI204H9WFvZwPa3d0katepsKOTkPOfNm@QU@Y8sq63c7Tr4JBE5dLAqN1UzPkASAYWll0lsNmW@L5oqL2uydnnm6nQawbJ9pS8upZBHmpTfyJ7e8n1Wswmkg9n7KpWT0H2AlM0fIF8wD5LWmaereruYzT6@NhmFhHWt48TUIerjNKY@Ry54yEPGSUxD7uu5iTxkA2p6hyLPZwrVeqBJQwk1C9QK3lBCDZU5UXjUGuyoK31bHVPNBP/4Qm6H9YVnrYsdA@Nraig0usK4JHhNCeu@j3zj0ruhgpOWja@0eu@h9SUMgzdawtwEnnY8n4XcPSOa9@qj65sQF9RQi5GGjMnB0FAgh8LnIH8Lua5lojtD9SQs@3Qpq/2uVguPqlUVrH7fZEaqUYc1qhMtzGbHspHTdn8 "PowerShell – Try It Online") Test case `@( @(1,1,5,1,1), @(1,1,1,1,1), 1)` added. Unrolled: ``` $args|%{ $score=$( # powershell creates a new scope inside expression $(...) $_-ne1|group|sort count,name|%{$max=$_} # $max is an element with the widest group and the maximum digit except 1 $ones=($_-eq1).Count # number of 1s in a player's hand $scoreRaw=7*($ones+$max.Count)+$max.Name+6*!$max # where $max.Name is digit of the widest group $scoreRaw[!$ones] # output $scoreRaw if the array contains 1, otherwise output $null ) # powershell deletes all variables created inside the scope on exit $diff=$score-$diff } [math]::Sign($diff) # output the score difference ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~78~~ ~~75~~ 74 bytes *-1 byte by Greg Martin* ``` Order@@(#~FreeQ~1||Last@Sort[Reverse/@Tally@Flatten[#/. 1->Range@6]]&)/@#& ``` [Try it online!](https://tio.run/##dVHBaoQwFLz7FamCtBBrn268ueQkFArdbnsTD6GNreBaSEKhuLu/bpOnrbpQcshLZjIz7@UgzIc8CNO8iqHOh0f1JhXn18G5UFI@neF4fBDa8OdPZcq9/JJKy5i/iLb95kUrjJFdGcS3BKLtXnTvkmdVFd7EPAgHI7XRJCd93ycUKKMZzU60z2jiKlufSLQlEVDPETb/Ee4cDvYudRyLM7un9gwrnNllbycc5veo7/gJvqG9Q9PLAECnhQFgKTAZpBhgY3FAKWu4MBhxhgHH2nLWBukogYTptBAY82UYgCEKawGGLcLk8Jt2mWDuAHDef/iyxQRnNM5rbsE7ed5ONZ0p7@uy5gHJ85wECSX@Tmjt270QTXvlV6QKCeec4Od6ww8 "Wolfram Language (Mathematica) – Try It Online") Outputs -1 when player 1 wins, 1 when player 2 wins, and 0 for a tie. ``` Helper function to score a list: FreeQ[#,1] || If there are 0 1s, score is True Last@Sort[ Otherwise, take the largest element of Reverse/@Tally@ the {frequency, number} pairs in the flat list Flatten[ #/. 1->Range@6] where each 1 is replaced by {1,2,3,4,5,6}. ]& e.g. {1,3,3,5,5} -> {1,2,3,4,5,6,3,3,5,5} -> {3,5} Order @@ (...) /@ #& Apply this function to both lists, then find the ordering of the result. ``` [Answer] # Java 8, ~~244~~ ~~240~~ ~~236~~ ~~215~~ 199 bytes ``` a->b->{int c[][]=new int[2][7],m[]=new int[2],p,i=5;for(;i-->0;c[1][b[i]]++)c[0][a[i]]++;for(i=14;i-->4;)m[p=i%2]=Math.max(m[p],c[p][1]>0?i/2+9*(c[p][i/2]+c[p][1]):0);return Long.compare(m[0],m[1]);} ``` -4 bytes thanks to *@someone*. -21 bytes thanks to *@Neil*. Returns `1` if P1 wins; `-1` if P2 wins; `0` if it's a tie. [Try it online.](https://tio.run/##rZNda9swFIbv8ysOhYG9yJ6/x@rauxsMVhjkUuhCcZRUqS0bW24XQn57JsleS6lT5lIERtZ7zquj50h7@kCd/eb@XJS06@CWcnFcAHSSSl7AXqluL3npbntRSF4L98c4ueFCYoL@J@SnkGzH2jyHLWRwpk6@dvKjEqHABJNMsEfQoQHBXwmqXqygBvEsTrd1a6XccXIvLbBP8BpzQpZLu8AewXT4MUE88yMTGKV2hZuMfwpIdkvlnVvRP5ZaIahQH@WRe9/5l2D57bNlFtScLEfJvvbstGWybwX8qsXOLeqqoS1T@Z4uUEWkp3O6UKCafl0qUCOvh5pvoFIMrZVsudhhAtTWPAFWh06yyq176TZKkqWwrn6X9MBa8KG7q/tyA49cXF/Z6aX4rUubpjxY/@iQY4B8FKMEJSf7lZagQCtam2MZqjQ9/AnLSG0XzrfUSaGqM56wHDS14TzLocZkssrYWPpzLX00jskqNWej2abtb/YzeHc/9S66/GDyWBr/O@FHKJo8lqZoGjPfMrxgOarzLGNzcP/CFXlqzFvwVwPzNQMKkrO5Dyn66Iek4Wrw8YVehsMj@6grmhjlucrT4nT@Cw) **Explanation:** ``` a->b->{ // Method with 2 integer-array parameters & integer return int c[][]=new int[2][7], // Create a count-array for each value of both players, // initially filled with 0s m[]=new int[2], // The maximum per player, initially 0 p, // Temp-value for the player i=5;for(;i-->0; // Loop `i` in the range (5, 0]: c[1] // For player 2: [b[i] // Get the value of the `i`'th die, ]++) // and increase that score-count by 1 c[0][a[i]]++; // Do the same for player 1 for(i=14;i-->4;) // Then loop `i` in the range (14, 4]: m[p=i%2]= // Set the score of a player to: // (even `i` = player 1; odd `i` = player 2) Math.max( // The max between: m[p], // The current value, // And the value we calculate as follows: c[p][1]>0? // If this player rolled at least one 1: i/2 // Use the current value `i` integer-divided by 2 +9* // With 9 times the following added: (c[p][i/2] // The amount of dice for value `i//2` +c[p][1]) // Add the amount of dice for value 1 : // Else (no 1s were rolled): 0); // Use 0 return Long.compare(m[0],m[1]);} // Finally compare the maximum scores of the players, // resulting in -1 if a<b; 0 if a==b; 1 if a>b ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes ``` ’o5Rṗ5¤ṢŒr$€UẎṀ1e⁸¤×µ€_/Ṡo/ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw8x806CHO6ebHlrycOeio5OKVB41rQl9uKvv4c4Gw9RHjTsOLTk8/dBWoGC8/sOdC/L1////H22kY6JjqmOmYxaroxBtpmMEYgI5AA "Jelly – Try It Online") 1 for P1, -1 for P2, 0 for tie # Explanation ``` ’o5Rṗ5¤ṢŒr$€UẎṀ1e⁸¤×µ€_/Ṡo/ Main link µ€ For each list ’ Decrement each value (so 1s become falsy) o Vectorized logical or (this replaces previous 1s (now 0s) with the test values) 5Rṗ5¤ 1..5 cartesian-power 5 (1,1,1,1,1; 1,1,1,1,2; 1,1,1,1,3; ...) $€ For each test list ṢŒr Sort and run-length encode (gives [digit, #digit]) U Reverse each list (gives [#digit, digit]) Ẏ Tighten by one (gives a list containing each possible hand for each possible wildcard) Ṁ Take the maximum 1e⁸¤× Multiply the list values by (whether or not the original contained a 1) - becomes [0, 0] if not _/Ṡ Take the sign of the difference between the #digits and the digits o/ If the number of digits differs, then 1/-1 is returned; otherwise, check the value of the digit (could still be 0) ``` [Answer] # [Sledgehammer 0.4](https://github.com/tkwa/Sledgehammer/commit/e5213349bfb06086de2100e3b05ce7cc1747c95d), 27 bytes ``` ⢱⢙⢂⠠⡾⢃⠐⢈⠸⣞⠴⠻⠎⡥⡳⡐⢒⠘⢛⣩⡓⣮⡕⡠⣢⣡⠿ ``` Decompresses into this Wolfram Language function: ``` Order @@ (FreeQ[#1, 1] || Last[Sort[Reverse[Tally[Flatten[#1 /. 1 -> Range[6]]], 2]]] & ) /@ #1 & ``` which turns out to be exactly the same as my [Mathematica answer](https://codegolf.stackexchange.com/a/186484/39328). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~48~~ 45 bytes ``` UMθ⮌E⁷№ι∨λ¹UMθ׬¬⊟ι⁺⊟ιιUMθ⟦⌈ι±⌕ι⌈ι⟧I⁻⌕θ⌈θ⌕θ⌊θ ``` [Try it online!](https://tio.run/##bY4/C8IwEMV3P0XGK8ShKjg4Ftxai7iFDKEGPWiSNk2L3z5e458ieNwN@d17edfclW@camMsVVc4Y5S9Qs/ZWU/aDxqIwp6zwo02AHJ28tBylmdzHVa/ngsaPUDlQpradYCk4qxux@H95Az/GEWpHmhGkwSVvqmg4Yi0o8BllWWSnLVHuqRQQ4ASLX2chP0i7OfIL0T7geniGIUQOWeb1DtqSfEEXmw7Aynjemqf "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of arrays and outputs `-1` if player 1 wins, `0` for a tie, and `1` if player 2 wins. Explanation: ``` UMθ⮌E⁷№ι∨λ¹ ``` Replace each hand with the count of how many times the values `6..1` appear in the hand. The list is reversed because a) it makes it easier to find the highest value with the highest count and b) it makes it easier to remove the count of `1`s. The count of `1`s is doubled because it needs to be removed twice, once to check that it is nonzero and once to add it to the other counts. ``` UMθ׬¬⊟ι⁺⊟ιι ``` Add the count of `1`s to the counts for `6..2`, but set all of the counts to zero if the count of `1`s was zero. ``` UMθ⟦⌈ι±⌕ι⌈ι⟧ ``` For each hand find the highest count and the highest value with that count. (Actually we find value minus `6` as that's golfier.) ``` I⁻⌕θ⌈θ⌕θ⌊θ ``` Determine which hand won by subtracting the positions of the winning and losing hands. (If the hands are tied then the first hand is both winning and losing so the result is `0` as desired.) [Answer] # [C (gcc)](https://gcc.gnu.org/) / 32 bit, 117 bytes ``` t;m;s(int*r){int c[6]={};for(m=0;t=*r++;m=t>m?t:m)c[--t]+=5,t=t?c[t]+t:5;t=*c?*c+m:0;}f(a,b){t=s(a)-s(b);t=(t>0)-!t;} ``` [Try it online!](https://tio.run/##fVJBboMwEDzDK1yqSjaYFkPIAcfJF3qo1APlQJyQWgqkwu6liK@X2qZAIlWVD96d2R2PtcvDE@fDoGhNJRSN8lvU6QvwfF2wrqfVpYU1i6hifhsEtGZqW@9UViOeh6EqApZixdSO5zpWWWrq@M7nQZ1FtK9gifeoU0zCEoUS7pHmodpGKLxTtB/uRcPPn4cj2Eh1EJfH963rmsfrUjQQgc51TKbyQpsBzOROF2OCU7zWJ@ox6NY4tolNR371L080kNgay6c6TLARnflUHwPNPLnuN0w8NYDOsMmt/nR@3ye3/abcvL8aeWLF0tHOwqeTvzGNRzsLnyz9EzD/P7ZfJpN/w5GlP7XaZNG/svuHf2JLx9R1euo6eiOA2RQg9FoAsZHi63ipoEJPv5GvkMYDFtsJ2hG2enq6JBcF1uMUASmQVnI@Wk1W0HuQb42HTRUDBOyA90zAq2ikB7IRjCwYz6D3Io6ekejdfvjm1bk8ySGsk/gH "C (gcc) – Try It Online") Takes two zero-terminated integer arrays. Returns `1`, `0`, `-1` for `P1 Wins`, `P2 Wins`, `Tie`. [Answer] # [J](http://jsoftware.com/), ~~47~~ 44 bytes ``` *@-&([:({.([:>./#\@]+9^*@[*+)}.)1#.i.@6=/<:) ``` [Try it online!](https://tio.run/##fZBNC8IwDIbv@xXBgVs31y37AouTgeDJk9f5cRCHevEHiL@9pmllU0FeUtI@yZtsNz2RQQ@NggBmkIGiSCSstpu1jtpkGnYqfEg6lzL1d@0@nh@itoti8ZQCfXmVbd2kCyW08Lzz6XIHhAZyOiuoST1Fzlltcca4/IeRngou6SlKysnP4iMyr0jm1XIc2g02IOcVeobFt/tbZjiOu517wdNL4shGNG1wt7ji5WxOJT/thWt3t/GfyfmDkXc3ED/aKxY6e6fx9GF55DKD9Qs "J – Try It Online") Inspired by Nick Kennedy's idea. ## ungolfed ``` *@-&([: ({. ([: >./ #\@] + 9 ^ *@[ * +) }.) 1 #. i.@6 =/ <:) ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=max -pl`, 80 bytes ``` sub t{$t=pop;$_=max map$_ x$t=~s/$_//g,2..6;/./;$t&&$_.$t*($&||6)}$_=t($_)<=>t<> ``` [Try it online!](https://tio.run/##FY3BCoMwEAXv/YoclqClJkYwB2P8gvbYc7BQSkDN0mxBqO2nN43vMjAwPLw/pzal@LoxegNZDGjA2Xlc2TwiOLZm@Y0SnJSPUyOENlJIA8Q5OAF0LIBvmy4/OaICXNnbgfohJdUorQ9q3y8g@bDEVF1aUas68@wjdd2V/LRfpQqnPw "Perl 5 – Try It Online") **Input:** Each player on a separate line, no spaces **Output:** `1` Line one wins `0` Tie `-1` Line two wins ]
[Question] [ [Inspired by this SciFi.SE question.](https://scifi.stackexchange.com/questions/107675/why-does-mark-use-hexadecimal-to-communicate) --- ### Background (with minor spoiler): > > In the movie [*The Martian*](http://www.imdb.com/title/tt3659388/), protagonist Mark Watney uses an ASCII table to look up hexadecimal values of ASCII characters so he can attempt to communicate back to Earth.\* > > > ### Challenge With no input, output the following ASCII table exactly like this: ``` Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex 0 00 NUL 16 10 DLE 32 20 48 30 0 64 40 @ 80 50 P 96 60 ` 112 70 p 1 01 SOH 17 11 DC1 33 21 ! 49 31 1 65 41 A 81 51 Q 97 61 a 113 71 q 2 02 STX 18 12 DC2 34 22 " 50 32 2 66 42 B 82 52 R 98 62 b 114 72 r 3 03 ETX 19 13 DC3 35 23 # 51 33 3 67 43 C 83 53 S 99 63 c 115 73 s 4 04 EOT 20 14 DC4 36 24 $ 52 34 4 68 44 D 84 54 T 100 64 d 116 74 t 5 05 ENQ 21 15 NAK 37 25 % 53 35 5 69 45 E 85 55 U 101 65 e 117 75 u 6 06 ACK 22 16 SYN 38 26 & 54 36 6 70 46 F 86 56 V 102 66 f 118 76 v 7 07 BEL 23 17 ETB 39 27 ' 55 37 7 71 47 G 87 57 W 103 67 g 119 77 w 8 08 BS 24 18 CAN 40 28 ( 56 38 8 72 48 H 88 58 X 104 68 h 120 78 x 9 09 HT 25 19 EM 41 29 ) 57 39 9 73 49 I 89 59 Y 105 69 i 121 79 y 10 0A LF 26 1A SUB 42 2A * 58 3A : 74 4A J 90 5A Z 106 6A j 122 7A z 11 0B VT 27 1B ESC 43 2B + 59 3B ; 75 4B K 91 5B [ 107 6B k 123 7B { 12 0C FF 28 1C FS 44 2C , 60 3C < 76 4C L 92 5C \ 108 6C l 124 7C | 13 0D CR 29 1D GS 45 2D - 61 3D = 77 4D M 93 5D ] 109 6D m 125 7D } 14 0E SO 30 1E RS 46 2E . 62 3E > 78 4E N 94 5E ^ 110 6E n 126 7E ~ 15 0F SI 31 1F US 47 2F / 63 3F ? 79 4F O 95 5F _ 111 6F o 127 7F DEL ``` The final newline is optional. With the newline, the md5 of the output is `58824a1dd7264c0410eb4d727aec54e1`. Without, it is `41b6ecde6a3a1324be4836871d8354fe`. In case it helps, this is the output from the [`ascii` Linux command](http://packages.ubuntu.com/trusty/ascii) with the usage info at the top chopped off. You can recreate this on Ubuntu as follows: ``` sudo apt-get install ascii ascii | tail -n+7 ``` You **may not** use the `ascii` utility (or similar) in your answers. Because ASCII characters are small Enough with [this silly meme](http://meta.codegolf.stackexchange.com/a/5856/11259) already! --- I am aware this is similar to [Print the ASCII table](https://codegolf.stackexchange.com/questions/40490/print-the-ascii-table), but I believe the formatting of the output in this question is significantly more complex and warrants a different question. --- \*Note, I have not yet seen this movie. [Answer] # JavaScript (ES6), 323 ~~332 353~~ **Edit** I managed to shorten this a bit Step 1, believe it or not, using an array of 16 chars is shorter than `toString` + `toUpperCase` Step 2, fiddling around to use `.map` instead of `for`, so that I can transform it all to a single expression function, avoding console.log and/or return. **Edit 2** Moved DEL at place 0, idea borrowed from Cole Cameron ``` H=x=>(x=[...'0123456789ABCDEF']).map((d,r)=>x[S='slice'](0,8).map(c=>(o+=` ${w=c*16+r} ${c+d} `[S](-z)+("DELNULSOHSTXETXEOTENQACKBELBS HT LF VT FF CR SO SI DLEDC1DC2DC3DC4NAKSYNETBCANEM SUBESCFS GS RS US ".substr((w+1&127)*3,3)||String.fromCharCode(w)),z=c<5?8:9,'Dec Hex '[S](0,c<2?z+2:z)),o+=` `,z=7).join` `,o='')[0]+o ``` MD5: 41B6ECDE6A3A1324BE4836871D8354FE Pixel perfect, I'd say **LESS GOLFED** ``` H=x=>( x=[...'0123456789ABCDEF'], a="DELNULSOHSTXETXEOTENQACKBELBS HT LF VT FF CR SO SI DLEDC1DC2DC3DC4NAKSYNETBCANEM SUBESCFS GS RS US ", o='', // the string o will contain the body (16 rows) x.map((d,r)=> ( // main loop, r is thr row number, d is the second hex digit to print o+=`\n`, z=7, x.slice(0,8).map(c=> // loop on 8 columns, c is both column number and digit to print ( // append the column to o o += ` ${w=c*16+r} ${c+d} `.slice(-z) + (a.substr((w+1&127)*3,3)||String.fromCharCode(w)), z=c<5?8:9, // adjust the column size 'Dec Hex '.slice(0,c<2?z+2:z) // column head, right size ) // the .map result is the 8 columns heading ).join` ` // join the heading in a single string ))[0] // any element of the result map is the heading + o // concatenate the body ) ``` **Test** ``` H=x=>(x=[...'0123456789ABCDEF']).map((d,r)=>x[S='slice'](0,8).map(c=>(o+=` ${w=c*16+r} ${c+d} `[S](-z)+("DELNULSOHSTXETXEOTENQACKBELBS HT LF VT FF CR SO SI DLEDC1DC2DC3DC4NAKSYNETBCANEM SUBESCFS GS RS US ".substr((w+1&127)*3,3)||String.fromCharCode(w)),z=c<5?8:9,'Dec Hex '[S](0,c<2?z+2:z)),o+=` `,z=7).join` `,o='')[0]+o /* TEST */ console.log=x=>O.textContent=x console.log(H()) ``` ``` <pre id=O></pre> ``` [Answer] # C, ~~307~~ ~~310~~ ~~308~~ ~~307~~ 305 bytes Finally working 100%. ``` i,j,z=127;main(){for(;j++<8;)printf("Dec Hex%*s",j<3?4:j<6||j>7?2:3,"");for(;i<143&&putchar(!i|i>z?10:32);i+=16)i=i>z?i%z:i,printf("%*d %02X ",i>95?4:3,i,i),i%z>31?putchar(i):printf("%.3s","DELNULSOHSTXETXEOTENQACKBELBS HT LF VT FF CR SO SI DLEDC1DC2DC3DC4NAKSYNETBCANEM SUBESCFS GS RS US "+(i+1)%128*3);} ``` Output: ``` $ ./a.out Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex 0 00 NUL 16 10 DLE 32 20 48 30 0 64 40 @ 80 50 P 96 60 ` 112 70 p 1 01 SOH 17 11 DC1 33 21 ! 49 31 1 65 41 A 81 51 Q 97 61 a 113 71 q 2 02 STX 18 12 DC2 34 22 " 50 32 2 66 42 B 82 52 R 98 62 b 114 72 r 3 03 ETX 19 13 DC3 35 23 # 51 33 3 67 43 C 83 53 S 99 63 c 115 73 s 4 04 EOT 20 14 DC4 36 24 $ 52 34 4 68 44 D 84 54 T 100 64 d 116 74 t 5 05 ENQ 21 15 NAK 37 25 % 53 35 5 69 45 E 85 55 U 101 65 e 117 75 u 6 06 ACK 22 16 SYN 38 26 & 54 36 6 70 46 F 86 56 V 102 66 f 118 76 v 7 07 BEL 23 17 ETB 39 27 ' 55 37 7 71 47 G 87 57 W 103 67 g 119 77 w 8 08 BS 24 18 CAN 40 28 ( 56 38 8 72 48 H 88 58 X 104 68 h 120 78 x 9 09 HT 25 19 EM 41 29 ) 57 39 9 73 49 I 89 59 Y 105 69 i 121 79 y 10 0A LF 26 1A SUB 42 2A * 58 3A : 74 4A J 90 5A Z 106 6A j 122 7A z 11 0B VT 27 1B ESC 43 2B + 59 3B ; 75 4B K 91 5B [ 107 6B k 123 7B { 12 0C FF 28 1C FS 44 2C , 60 3C < 76 4C L 92 5C \ 108 6C l 124 7C | 13 0D CR 29 1D GS 45 2D - 61 3D = 77 4D M 93 5D ] 109 6D m 125 7D } 14 0E SO 30 1E RS 46 2E . 62 3E > 78 4E N 94 5E ^ 110 6E n 126 7E ~ 15 0F SI 31 1F US 47 2F / 63 3F ? 79 4F O 95 5F _ 111 6F o 127 7F DEL$ ./a.out > file.txt $ md5sum file.txt 41b6ecde6a3a1324be4836871d8354fe file.txt ``` Ungolfed: ``` /* some variables for the trip */ i,j,z=127; main() { /* print header row */ for(;j++<8;) printf("Dec Hex%*s", j<3?4:j<6||j>7?2:3, ""); /* Iterate through ASCII values, print a space after every column, newline after every 8th value */ for(;i<143 && putchar(!i|i>z ? 10 : 32); i+=16) { /* print dec/hex value */ printf("%*d %02X ", i>95?4:3, i, i=i>z?i%z:i); /* print character or friendly name for non-printable characters */ i%z>31 ? putchar(i) : printf("%.3s", "DELNULSOHSTXETXEOTENQACKBELBS HT LF VT FF CR SO SI DLEDC1DC2DC3DC4NAKSYNETBCANEM SUBESCFS GS RS US "+(i+1)%128*3); } } ``` Try it on [Ideone](http://ideone.com/OO5IuJ). Edit: 2 more bytes. Many thanks to Dan Allen and Digital Trauma. [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 535 bytes ``` 0000000: e0 05 2f 02 0f 5d 00 22 19 48 62 01 d3 1f 78 e2 ../..].".Hb...x. 0000010: 9a a0 8e 4e 5d d1 b4 c1 77 aa 32 58 ca 97 55 7e ...N]...w.2X..U~ 0000020: a8 01 87 7d db e4 00 55 8f c0 49 67 b6 56 02 5e ...}...U..Ig.V.^ 0000030: ae b2 4d e2 a9 f4 7f 99 a8 56 9e b7 4c 60 a4 79 ..M......V..L`.y 0000040: 6a 76 54 11 90 72 d6 b7 19 df 2f 57 39 2d 21 c0 jvT..r..../W9-!. 0000050: d1 4c 5e d6 21 29 c8 ed 7c a9 7b 8c 85 dc 62 a1 .L^.!)..|.{...b. 0000060: 65 98 e1 0b a7 36 83 c8 ca 88 0c 57 22 f6 56 1e e....6.....W".V. 0000070: 45 03 b6 74 21 a8 39 52 e9 71 b4 98 ed 71 38 9f E..t!.9R.q...q8. 0000080: 2d dc 21 d7 bf 60 41 cc bb bd a7 cb 0b 17 8d 65 -.!..`A........e 0000090: 05 13 04 0f 6c bb 67 62 aa c7 ad 6b be 9e 46 77 ....l.gb...k..Fw 00000a0: 35 b9 91 85 f5 47 31 2f c7 ec da c0 00 0e a6 48 5....G1/.......H 00000b0: 01 ba 8b cd b0 34 81 c4 74 9f 4e 3b c3 d0 f7 10 .....4..t.N;.... 00000c0: 46 a0 55 8d 49 5d b7 b0 c9 79 ac e5 5f ef 49 f2 F.U.I]...y.._.I. 00000d0: b0 1b 71 3a e1 30 7a fc ce a7 a8 d5 c3 9a 35 1a ..q:.0z.......5. 00000e0: 4e 27 92 40 4b b5 9b c4 0d 5c e8 cd 71 00 bd c1 N'.@K....\..q... 00000f0: ca aa d2 05 dc e1 0f d9 19 1d 6f 14 87 b3 e4 e8 ..........o..... 0000100: 9e 82 64 d8 e4 76 e7 24 0a 0e 88 72 a1 12 44 95 ..d..v.$...r..D. 0000110: d4 78 82 bd da 71 f3 fb 03 00 d1 4b c8 80 cb 49 .x...q.....K...I 0000120: 0b 98 be 26 ba 3e e8 82 e2 14 9b ba 1a cf bf bc ...&.>.......... 0000130: 30 4e c4 e8 7e b4 d5 46 e6 bc 73 97 c5 ed a6 e2 0N..~..F..s..... 0000140: 06 02 e7 1b 74 4d da 73 fb 15 68 50 c0 ed 32 9b ....tM.s..hP..2. 0000150: 0d d7 49 d5 c1 a2 e9 07 2c 77 81 6c d3 8d 59 26 ..I.....,w.l..Y& 0000160: 1c 35 ec 2b 7e cb 3a f1 cc 45 a9 e5 6d 3e 33 ca .5.+~.:..E..m>3. 0000170: 56 3c 8a 8d f6 13 e9 59 d4 52 07 44 ab 5e bc f4 V<.....Y.R.D.^.. 0000180: 1f ed f8 9c 8b 48 e1 c4 6c fd 47 d5 04 cc 6e aa .....H..l.G...n. 0000190: 3f 54 b8 cc cd 09 01 6d 20 3c 42 c9 44 da b1 c1 ?T.....m <B.D... 00001a0: 69 80 12 26 6b 65 e1 4d 1c c3 48 36 2b 14 00 61 i..&ke.M..H6+..a 00001b0: 04 6b 9a 59 2a 53 e3 64 a7 4f dd cc be 2c 20 5e .k.Y*S.d.O..., ^ 00001c0: f7 c7 64 34 e6 12 a6 44 c1 69 35 76 05 db 13 ab ..d4...D.i5v.... 00001d0: 52 10 b5 8e da 8e c5 3c 4c d0 69 0b 19 18 67 ef R......<L.i...g. 00001e0: 44 1c 7b 70 63 98 95 40 28 6e 3d e7 44 cb 24 83 D.{pc..@(n=.D.$. 00001f0: 88 62 63 3c 02 1c e7 db db 02 56 ae cd 9c e0 9c .bc<......V..... 0000200: 1c a1 c1 ae d1 dd 7b b7 e6 bd 5b 38 ee 75 c5 6c ......{...[8.u.l 0000210: 06 16 6c b2 fb 00 00 ..l.... ``` This above program uses LZMA compression. [Try it online!](http://bubblegum.tryitonline.net/#code=MDAwMDAwMDogZTAgMDUgMmYgMDIgMGYgNWQgMDAgMjIgMTkgNDggNjIgMDEgZDMgMWYgNzggZTIgIC4uLy4uXS4iLkhiLi4ueC4KMDAwMDAxMDogOWEgYTAgOGUgNGUgNWQgZDEgYjQgYzEgNzcgYWEgMzIgNTggY2EgOTcgNTUgN2UgIC4uLk5dLi4udy4yWC4uVX4KMDAwMDAyMDogYTggMDEgODcgN2QgZGIgZTQgMDAgNTUgOGYgYzAgNDkgNjcgYjYgNTYgMDIgNWUgIC4uLn0uLi5VLi5JZy5WLl4KMDAwMDAzMDogYWUgYjIgNGQgZTIgYTkgZjQgN2YgOTkgYTggNTYgOWUgYjcgNGMgNjAgYTQgNzkgIC4uTS4uLi4uLlYuLkxgLnkKMDAwMDA0MDogNmEgNzYgNTQgMTEgOTAgNzIgZDYgYjcgMTkgZGYgMmYgNTcgMzkgMmQgMjEgYzAgIGp2VC4uci4uLi4vVzktIS4KMDAwMDA1MDogZDEgNGMgNWUgZDYgMjEgMjkgYzggZWQgN2MgYTkgN2IgOGMgODUgZGMgNjIgYTEgIC5MXi4hKS4ufC57Li4uYi4KMDAwMDA2MDogNjUgOTggZTEgMGIgYTcgMzYgODMgYzggY2EgODggMGMgNTcgMjIgZjYgNTYgMWUgIGUuLi4uNi4uLi4uVyIuVi4KMDAwMDA3MDogNDUgMDMgYjYgNzQgMjEgYTggMzkgNTIgZTkgNzEgYjQgOTggZWQgNzEgMzggOWYgIEUuLnQhLjlSLnEuLi5xOC4KMDAwMDA4MDogMmQgZGMgMjEgZDcgYmYgNjAgNDEgY2MgYmIgYmQgYTcgY2IgMGIgMTcgOGQgNjUgIC0uIS4uYEEuLi4uLi4uLmUKMDAwMDA5MDogMDUgMTMgMDQgMGYgNmMgYmIgNjcgNjIgYWEgYzcgYWQgNmIgYmUgOWUgNDYgNzcgIC4uLi5sLmdiLi4uay4uRncKMDAwMDBhMDogMzUgYjkgOTEgODUgZjUgNDcgMzEgMmYgYzcgZWMgZGEgYzAgMDAgMGUgYTYgNDggIDUuLi4uRzEvLi4uLi4uLkgKMDAwMDBiMDogMDEgYmEgOGIgY2QgYjAgMzQgODEgYzQgNzQgOWYgNGUgM2IgYzMgZDAgZjcgMTAgIC4uLi4uNC4udC5OOy4uLi4KMDAwMDBjMDogNDYgYTAgNTUgOGQgNDkgNWQgYjcgYjAgYzkgNzkgYWMgZTUgNWYgZWYgNDkgZjIgIEYuVS5JXS4uLnkuLl8uSS4KMDAwMDBkMDogYjAgMWIgNzEgM2EgZTEgMzAgN2EgZmMgY2UgYTcgYTggZDUgYzMgOWEgMzUgMWEgIC4ucTouMHouLi4uLi4uNS4KMDAwMDBlMDogNGUgMjcgOTIgNDAgNGIgYjUgOWIgYzQgMGQgNWMgZTggY2QgNzEgMDAgYmQgYzEgIE4nLkBLLi4uLlwuLnEuLi4KMDAwMDBmMDogY2EgYWEgZDIgMDUgZGMgZTEgMGYgZDkgMTkgMWQgNmYgMTQgODcgYjMgZTQgZTggIC4uLi4uLi4uLi5vLi4uLi4KMDAwMDEwMDogOWUgODIgNjQgZDggZTQgNzYgZTcgMjQgMGEgMGUgODggNzIgYTEgMTIgNDQgOTUgIC4uZC4udi4kLi4uci4uRC4KMDAwMDExMDogZDQgNzggODIgYmQgZGEgNzEgZjMgZmIgMDMgMDAgZDEgNGIgYzggODAgY2IgNDkgIC54Li4ucS4uLi4uSy4uLkkKMDAwMDEyMDogMGIgOTggYmUgMjYgYmEgM2UgZTggODIgZTIgMTQgOWIgYmEgMWEgY2YgYmYgYmMgIC4uLiYuPi4uLi4uLi4uLi4KMDAwMDEzMDogMzAgNGUgYzQgZTggN2UgYjQgZDUgNDYgZTYgYmMgNzMgOTcgYzUgZWQgYTYgZTIgIDBOLi5-Li5GLi5zLi4uLi4KMDAwMDE0MDogMDYgMDIgZTcgMWIgNzQgNGQgZGEgNzMgZmIgMTUgNjggNTAgYzAgZWQgMzIgOWIgIC4uLi50TS5zLi5oUC4uMi4KMDAwMDE1MDogMGQgZDcgNDkgZDUgYzEgYTIgZTkgMDcgMmMgNzcgODEgNmMgZDMgOGQgNTkgMjYgIC4uSS4uLi4uLHcubC4uWSYKMDAwMDE2MDogMWMgMzUgZWMgMmIgN2UgY2IgM2EgZjEgY2MgNDUgYTkgZTUgNmQgM2UgMzMgY2EgIC41Lit-LjouLkUuLm0-My4KMDAwMDE3MDogNTYgM2MgOGEgOGQgZjYgMTMgZTkgNTkgZDQgNTIgMDcgNDQgYWIgNWUgYmMgZjQgIFY8Li4uLi5ZLlIuRC5eLi4KMDAwMDE4MDogMWYgZWQgZjggOWMgOGIgNDggZTEgYzQgNmMgZmQgNDcgZDUgMDQgY2MgNmUgYWEgIC4uLi4uSC4ubC5HLi4ubi4KMDAwMDE5MDogM2YgNTQgYjggY2MgY2QgMDkgMDEgNmQgMjAgM2MgNDIgYzkgNDQgZGEgYjEgYzEgID9ULi4uLi5tIDxCLkQuLi4KMDAwMDFhMDogNjkgODAgMTIgMjYgNmIgNjUgZTEgNGQgMWMgYzMgNDggMzYgMmIgMTQgMDAgNjEgIGkuLiZrZS5NLi5INisuLmEKMDAwMDFiMDogMDQgNmIgOWEgNTkgMmEgNTMgZTMgNjQgYTcgNGYgZGQgY2MgYmUgMmMgMjAgNWUgIC5rLlkqUy5kLk8uLi4sIF4KMDAwMDFjMDogZjcgYzcgNjQgMzQgZTYgMTIgYTYgNDQgYzEgNjkgMzUgNzYgMDUgZGIgMTMgYWIgIC4uZDQuLi5ELmk1di4uLi4KMDAwMDFkMDogNTIgMTAgYjUgOGUgZGEgOGUgYzUgM2MgNGMgZDAgNjkgMGIgMTkgMTggNjcgZWYgIFIuLi4uLi48TC5pLi4uZy4KMDAwMDFlMDogNDQgMWMgN2IgNzAgNjMgOTggOTUgNDAgMjggNmUgM2QgZTcgNDQgY2IgMjQgODMgIEQue3BjLi5AKG49LkQuJC4KMDAwMDFmMDogODggNjIgNjMgM2MgMDIgMWMgZTcgZGIgZGIgMDIgNTYgYWUgY2QgOWMgZTAgOWMgIC5iYzwuLi4uLi5WLi4uLi4KMDAwMDIwMDogMWMgYTEgYzEgYWUgZDEgZGQgN2IgYjcgZTYgYmQgNWIgMzggZWUgNzUgYzUgNmMgIC4uLi4uLnsuLi5bOC51LmwKMDAwMDIxMDogMDYgMTYgNmMgYjIgZmIgMDAgMDAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC4ubC4uLi4&input=) [Answer] ## C, ~~385~~ ~~384~~ 358 bytes ``` i,n,j;char a[100]="NULSOHSTXETXEOTENQACKBELBS HT LF VT FF CR SO SI DLEDC1DC2DC3DC4NAKSYNETBCANEM SUBESCFS GS RS US DEL";z(o){printf("%3d %02X %.*s ",j,j,3,a+o);}main(){for(;i<8;i++){printf("%3s %3s ","Dec","HEX ");}printf("\n");for(;n<16;n++){for(j=n;j<=n+112;j+=16){if(j==127)z(96);else j<32?z(j*3):printf("%3d %02X %c ",j,j,j);}printf("\n");}return 0;} ``` The guy above beat me to the punch but I still wanted to submit because I enjoyed this one. De-golfed: ``` #include<stdio.h> i,n,j; char a[100] = "NULSOHSTXETXEOTENQACKBELBS HT LF VT FF CR SO SI DLEDC1DC2DC3DC4NAKSYNETBCANEM SUBESCFS GS RS US DEL"; z(o){printf("%3d %02X %.*s ",j,j,3,a+o);} main(){ for(;i<8;i++){printf("%3s %3s ","Dec","HEX ");}printf("\n"); for(;n<16;n++){ for(j=n;j<=n+112;j+=16){ if(j==127)z(96); else j<32?z(j*3):printf("%3d %02X %c ",j,j,j); } printf("\n"); } return 0; } ``` UPDATE : replaced a var with j. Saved a byte ;) UPDATE2: Trimmed a few extra thingys and functionized a print thingy to save some bytes. [Answer] # JavaScript ES6 ~~432~~ ~~405~~ ~~398~~ 385 ``` o="Dec Hex " o=`${o} ${o} ${o+o+o+o} ${o} ${o}\n` for(i=0;i<16;i++){for(j=0;j<8;j++){k=i+j*16 o+=k>9&&k<16?' ':k<96||k>99?' ':' ' o+=k+" "+(k<16?0:'')+k.toString(16).toUpperCase()+" " o+=k>31?String.fromCharCode(k):"NULSOHSTXETXEOTENQACKBELBS HT LF VT FF CR SO SI DLEDC1DC2DC3DC4NAKSYNETBCANEM SUBESCFS GS RS US ".substr(k*3,3) }o+="\n"} console.log(o.substr(0,o.length-2)+'DEL') ``` [Answer] # Golfscript, 225 bytes ``` "\x04\x04\x02\x02\x02\x03\x03\x02"{"Dec Hex"" ":s@*}%n[128,{3s*\+-4>s+.~.96<@>\256+16base{10,"ABCDEF"1/+=}%1>{+}/}%"\x1f\xbb\x89\xbc\xaf\x82=F\xd7U%\x80\x8a\xf6\xc7U\xa6al)A\xf6\x19\xfe\x03\x83\xef-\x9f\xe7m\xeb\x82h\xf3\xbfEm6V\x1fD\x8c\xd7~\xcb\x95&(\x1e/:\x8e\xc5\xb0\x0b\xd6\xd4\xd09\xdd""\xff\x1e"{base}/{90,65>1342s++1/=}%3/32/"\x7f"{,32>}%1/*]zip{s*}%16/zip{s*n}% ``` [Answer] # Python 2.7, 389 Bytes Probably not going to try and trim this down anymore, but it was fun to get it this far. ``` r=range c='NULSOHSTXETXEOTENQACKBELBS HT LF VT FF CR SO SI DLEDC1DC2DC3DC4NAKSYNETBCANEM SUBESCFS GS RS US ' h='' p=['']*16 o=[11,11,9,9,9,10,10,9] e=['%3s '%str(i)+('%02X ')%(i)+('DEL',c[i*3:i*3+3].strip() if i<32 else chr(i))[i<127] for i in r(128)] for i in r(8): l=e[i*16:(i+1)*16] h+='Dec Hex'.ljust(o[i]) p=[p[j]+l[j].ljust((0,o[i])[i<7]) for j in r(16)] print h+'\n'+'\n'.join(p) ``` [Answer] # Python 3.4, 216 Bytes Also valid Python 2.7. Used [FryAmTheEggman's idea/suggestion](https://codegolf.stackexchange.com/questions/68621/create-an-ascii-to-hex-table-for-mark-watney#comment166852_68621) about curses.ascii.controlnames, which saves almost 100 bytes. ``` import curses.ascii as a o='' w=4,4,2,2,2,3,3,1 for x in w:o+='Dec Hex'+' '*x o+=' ' for n in range(16): o+='\n' for x in w:o+='%3d %02X %-*s'%(n,n,x,n>31and[chr(n),'DEL'][n>126]or a.controlnames[n]);n+=16 print(o) ``` --- ``` $ python ascii.py | md5 58824a1dd7264c0410eb4d727aec54e1 ``` [Answer] # Ruby (2.2.2p95), 277 ~~295 306 331 364~~ ``` a='Dec Hex ';puts"#{a} "*2+a*4+" #{a}"*2,16.times.map{|i|8.times.map{|j|(k=i+j*16;k==127?' 127 7F DEL':"#{k} #{'%.2X'%k} #{'NULSOHSTXETXEOTENQACKBELBS HT LF VT FF CR SO SI DLEDC1DC2DC3DC4NAKSYNETBCANEM SUBESCFS GS RS US '[k*3..k*3+2]||k.chr}").rjust(j<2?10+j :9+j/6)}.join} ``` ungolfed ``` s = "Dec Hex " * 2 + "Dec Hex " * 4 + " Dec Hex " * 2 a = 127.times.map { |i| "#{i} #{'%.2X'%i} #{'NULSOHSTXETXEOTENQACKBELBS HT LF VT FF CR SO SI DLEDC1DC2DC3DC4NAKSYNETBCANEM SUBESCFS GS RS US '[i*3..i*3+2]||i.chr}" } a << ' 127 7F DEL' x = 16.times.map { |i| 8.times.map { |j| a[i + j * 16].rjust(j < 2 ? 10 + j : 9 + j / 6) }.join }.join "\n" puts s, x ``` [Answer] # [Microscript II](https://github.com/SuperJedi224/Microscript-II), 1314 bytes Probably far from optimal. ``` "Dec Hex "pp"Dec Hex "ppps"Dec Hex "ppoP" 0 00 NUL 16 10 DLE 32 20 48 30 0 64 40 @ 80 50 P 96 60 ` 112 70 p\n 1 01 SOH 17 11 DC1 33 21 ! 49 31 1 65 41 A 81 51 Q 97 61 a 113 71 q\n 2 02 STX 18 12 DC2 34 22 \" 50 32 2 66 42 B 82 52 R 98 62 b 114 72 r\n 3 03 ETX 19 13 DC3 35 23 # 51 33 3 67 43 C 83 53 S 99 63 c 115 73 s\n 4 04 EOT 20 14 DC4 36 24 $ 52 34 4 68 44 D 84 54 T 100 64 d 116 74 t\n 5 05 ENQ 21 15 NAK 37 25 % 53 35 5 69 45 E 85 55 U 101 65 e 117 75 u\n 6 06 ACK 22 16 SYN 38 26 & 54 36 6 70 46 F 86 56 V 102 66 f 118 76 v\n 7 07 BEL 23 17 ETB 39 27 ' 55 37 7 71 47 G 87 57 W 103 67 g 119 77 w\n 8 08 BS 24 18 CAN 40 28 ( 56 38 8 72 48 H 88 58 X 104 68 h 120 78 x\n 9 09 HT 25 19 EM 41 29 ) 57 39 9 73 49 I 89 59 Y 105 69 i 121 79 y\n 10 0A LF 26 1A SUB 42 2A * 58 3A : 74 4A J 90 5A Z 106 6A j 122 7A z\n 11 0B VT 27 1B ESC 43 2B + 59 3B ; 75 4B K 91 5B [ 107 6B k 123 7B {\n 12 0C FF 28 1C FS 44 2C , 60 3C < 76 4C L 92 5C \\ 108 6C l 124 7C |\n 13 0D CR 29 1D GS 45 2D - 61 3D = 77 4D M 93 5D ] 109 6D m 125 7D }\n 14 0E SO 30 1E RS 46 2E . 62 3E > 78 4E N 94 5E ^ 110 6E n 126 7E ~\n 15 0F SI 31 1F US 47 2F / 63 3F ? 79 4F O 95 5F _ 111 6F o 127 7F DEL" ``` [Answer] ## JavaScript, ~~415~~ ~~413~~ ~~4231~~ ~~411~~ ~~406~~ ~~402~~ ~~4142~~ 412 bytes ``` x=>eval('a=`${d="Dec Hex "} `[r="repeat"](2)+d[r](3)+`${d} `[r](2)+d+` `;z="NULSOHSTXETXEOTENQACKBELBS HT LF VT FF CR SO SI DLEDC1DC2DC3DC4NAKSYNETBCANEM SUBESCFS GS RS US ".match(/.{3}/g);z[127]="DEL";for(j=i=0;i<128;i++){a+=(" "+((b=i%8*16)+j)).slice(-3)+" "+(0+(c=b+j).toString(16).toUpperCase()).slice(-2)+" "+(c<32||i==127?z[c]:String.fromCharCode(c))+(b==112?` `:(b < 80 ? " " : " "));if(b==112)j++}a') ``` I couldn't figure out how to print the chars prior to char code 32, so just listed them as a string. The hash I've got seems to match (`41b6ecde6a3a1324be4836871d8354fe`). Demo + Ungolfed: ``` function t() { a = `${d="Dec Hex "} `.repeat(2) + d.repeat(3) + `${d} `.repeat(2) + d + "\n"; z = "NULSOHSTXETXEOTENQACKBELBS HT LF VT FF CR SO SI DLEDC1DC2DC3DC4NAKSYNETBCANEM SUBESCFS GS RS US ".match(/.{3}/g); z[127] = "DEL"; for (j = i = 0; i < 128; i++) { a += (" " + ((b = i % 8 * 16) + j)).slice(-3) + " " + (0 + (c = b + j).toString(16).toUpperCase()).slice(-2) + " " + (c < 32 || i == 127 ? z[c] : String.fromCharCode(c)) + (b==112?"\n":(b < 80 ? " " : " ")); if(b==112)j++; } return a } document.write("<pre>" + t() + "</pre>") ``` --- 1 - fixed spacing 2 - again fixed spacing [Answer] # MATLAB, 363 bytes Not as small as C but comparable... ``` h='';s=@sprintf;for i=[4 4 2 2 2 3 3 2]h=s([h 'Dec Hex%*s'],i,'');end h=[h 10];a='NULDLESOHDC1STXDC2ETXDC3EOTDC4ENQNAKACKSYNBELETBBS CANHT EM LF SUBVT ESCFF FS CR GS SO RS SI US ';for i=0:15for j=0:7k=i+16*j;if j<2b=1+6*i+3*j;h=[h s('%3d %02X %-3s ',k,k,a(b:b+2))];else h=[h s('%*d %02X %c ',3+(j>5),k,k,k)];end end h=[h(1:end-1) 10];end disp([h(1:end-2) 'DEL']); ``` [Answer] # [///](https://esolangs.org/wiki////), 998 bytes ``` //\/\/// / /Dec Hex / 0/ 1/ 2/ 3/ 4/ 5/ 6 / 7 / 8 / 9/0 /1 /2 /3 /4 /5 /6 /7 /8 /9 /A /B /C /D  /E  /F / /    NUL 6DL 2 80 4@ 0P 6` 12 pSOH 7DC3! 91 5 1Q 7a 13 qSTX 8DC4" 02 6 2R 8b 14 rETX 9DC5# 13 7 3S 9c 15 sEOT 0DC6$ 24 8 4T 00d 16 tENQ 1NAK 7% 35 9 5U 01e 17 uACK 2SYN 8& 46 0 6V 02f 18 v BEL 3ET9' 57 1G 7W 03g 19 w BS 4CAN 0( 68 2H 8X 04h 20 x HT 5EM 1) 79 3I 9Y 05i 21 y 0L 6SU2* 8: 4J 0Z 06j 22 z 1VT 7ES3+ 9; 5K 1[ 07k 23 { 2F 8FS 4, 0< 6L 2\\ 08l 24 | 3CR 9GS 5- 1= 7M 3] 09m 25 } 4 SO 0 RS 6 . 2 > 8 N 4 ^ 10 n 26 ~ 5 SI 1 US 7 \/ 3 ? 9 O 5 _ 11 o 27 DEL ``` [Try it online!](https://tio.run/##FdJncxtVGAXgyd6u3VFvK2n3Hnrnbi90W5LjYEUmlhwImBKCIUCopoS6P91c3vP5mTNz5r16dP/q4eXV9bXR5sLGmNAA@oZZXT7A8eXjUDsGkSYGsaYGiWYGqeYGmRYGuZYGhVYGpXYNKu0Z1LptIuiOiaG7JoHumRS6bzLogcmhh6aAHpkSemwq6ImpoafmANo3h9Azs4SemxX0wqyhA3ME3ZgWzI3Qxh5sGsdpb883IAVprzYLltB2yCsWOZAZb78DNxLt90KvkO3PQOJEtX9siNPZnR6DlKSzWnZYSjtPgNcsJpA570zdWHTuhF4pO/etSFXnp4Y63d3@A5CKdFfLLsto90mIyHZBFrzru4nonoVeJbufW5Gp7s8Nc3rr/0VNeqtlj@W09xREzFIGWfLezE1Fbxd6tew9sCJXvauGO/316R40Iv3Vss8K2n8aImEZh6x4f@5mor8HiSLZ/8KSQvV/aYQzWG/vgMZksD04ASvp4BmIlOUCsuaDhZuLwbk1sRxcWlOqwa@NdIYHyxPQhAx397ZgFR0@C5GxQkJFfBi4hRjetSaRwy@tqdTwt0Y5o8P1BjQlo/XeZzUdPQeRs1JBxXx0E24pRu9bk8rRV9bUavR74zrjw11IMzJeHmzBIzp@HqJglQuV8PEx3EqM7T5RJscPQZJIjR83njM53oc0J5P17ZDHdPICRMlqDyrlk1twazG5Z0kuJ19bEqvJHy0SOdNNAFqQ6e7c5wmdvghRselrUBmfvgsvEtMPrSnk9BtrEjX9s0Vix79re0rir3cznlL/JYia@a9D5dw/gRcL/yNrSul/a02q/L9aJHFmR7anIrOjXcgzOnsZMmKzN6AKPtvAS8Ts4sKiSs4eWZSp2d8tkjrz5VlIazK/aVFO569Axmz@JlTJ57fhpWL@sTW1nH9nTa7m/7RI5ix2pyGLyOLMmoIuXoVM2OItqIovtvAysfjEjhzJxffWFGrxb4vkTrC7FdoPDs6tKWlwYSBTFrwNVfPgFF4ugk8timXwg0WlClbrzfX1fw "/// – Try It Online") [Answer] # [PHP](https://php.net/), ~~330~~ 321 bytes ``` $a=[NUL,SOH,STX,ETX,EOT,ENQ,ACK,BEL,BS,HT,LF,VT,FF,CR,SO,SI,DLE,DC1,DC2,DC3,DC4,NAK,SYN,ETB,CAN,EM,SUB,ESC,FS,GS,RS,US,127=>DEL];foreach($t=[3,3,1,1,1,2,2,0]as$i)echo'Dec Hex ',str_repeat(' ',$i);echo" ";for($x=0;$x<16;)for($y=$x++;$y<128;$y+=16)printf("% 3d %1$02X % -".$t[$y/16].s.($y<112?' ':" "),$y,$a[$y]?:chr($y)); ``` [Try it online!](https://tio.run/##TVD9j5pAEP35@CummzVAnFqWL4lIjSLWy3Fqb7W5xhiDsB4mvYMAl@hfbxdz/cjkZWYy772dnTIvr8NRmZcgqqqo9pUoi6o5vb1ohu5DcdjXTVI1mu5faRJsF5sY@XKOfP2MUYvlGqPFdxyHDziJYpxwnK8xnuGPNc5mGD5JNvJ7nMYRTkMmYUpYEjYuxg/Ify6kzwTDscyPyDcTjHiIM47fOD5x3HBkZj/4Oo3inX8sKpGkuUabYGuhhewWpgxjl9T0pIs0L9SpSGEuzqBi3dy@I5JGU2UrCX7LIKCQ1kuj58Dw6XnIXF@/9ZeAnrtdn16GzPRk6gbM1cvq9NYcNdIBK4MOo4b5DB34THq02dLLF@buenVPazXMHMl3BkQhOtIL0kTOd6NBmrfWenvB18yp318hAFlo7XFfRLM//nqvc00H3Vfa9WA1X@2jZYxAHqfOAAjChw7/jD6IGvw1DEB1PM@0E5ZlfdO1U8NmhjjYsuknInVswVQoKuXuf4XNDq5IM@EmVsIs0z4I27Ncr88yz3Lso1BBV@5GQFZjzgnITWbj@/gT@bfG9Tc "PHP – Try It Online") Less golfy: ``` $a=[NUL,SOH,STX,ETX,EOT,ENQ,ACK,BEL,BS,HT,LF,VT,FF,CR,SO,SI,DLE, DC1,DC2,DC3,DC4,NAK,SYN,ETB,CAN,EM,SUB,ESC,FS,GS,RS,US,127=>DEL]; $t=[3,3,1,1,1,2,2,0]; foreach( $t as $i ) echo 'Dec Hex ', str_repeat( ' ', $i ); echo" \n"; for( $x=0; $x<16; ) { for( $y=$x++; $y<128; $y+=16 ) { printf( "% 3d %1$02X % -" . $t[$y/16] . 's' . ( $y<112 ?' ' : "\n" ), $y, $a[$y] ?: chr($y) ); } } ``` [Answer] ## Common Lisp (SBCL), 309 ``` (progn(format t"~{~v,0TDec Hex ~}"#1='(0 11 22 31 40 49 59 69))(dotimes(y 16)(fresh-line)(loop for x from 0 for k in #1#for i =(+(* 16 x)y)do(format t"~v,0T~3d ~2,'0x ~a"k i i(if(graphic-char-p #2=(code-char i))#2#(case i(8"BS")(9"HT")(10"LF")(12"FF")(13"CR")(127"DEL")(t(string-upcase(char-name #2#))))))))) ``` A script to be run which outputs the following to standard output, ie. the version without a final newline (md5: 41b6ecde6a3a1324be4836871d8354fe). ``` Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex 0 00 NUL 16 10 DLE 32 20 48 30 0 64 40 @ 80 50 P 96 60 ` 112 70 p 1 01 SOH 17 11 DC1 33 21 ! 49 31 1 65 41 A 81 51 Q 97 61 a 113 71 q 2 02 STX 18 12 DC2 34 22 " 50 32 2 66 42 B 82 52 R 98 62 b 114 72 r 3 03 ETX 19 13 DC3 35 23 # 51 33 3 67 43 C 83 53 S 99 63 c 115 73 s 4 04 EOT 20 14 DC4 36 24 $ 52 34 4 68 44 D 84 54 T 100 64 d 116 74 t 5 05 ENQ 21 15 NAK 37 25 % 53 35 5 69 45 E 85 55 U 101 65 e 117 75 u 6 06 ACK 22 16 SYN 38 26 & 54 36 6 70 46 F 86 56 V 102 66 f 118 76 v 7 07 BEL 23 17 ETB 39 27 ' 55 37 7 71 47 G 87 57 W 103 67 g 119 77 w 8 08 BS 24 18 CAN 40 28 ( 56 38 8 72 48 H 88 58 X 104 68 h 120 78 x 9 09 HT 25 19 EM 41 29 ) 57 39 9 73 49 I 89 59 Y 105 69 i 121 79 y 10 0A LF 26 1A SUB 42 2A * 58 3A : 74 4A J 90 5A Z 106 6A j 122 7A z 11 0B VT 27 1B ESC 43 2B + 59 3B ; 75 4B K 91 5B [ 107 6B k 123 7B { 12 0C FF 28 1C FS 44 2C , 60 3C < 76 4C L 92 5C \ 108 6C l 124 7C | 13 0D CR 29 1D GS 45 2D - 61 3D = 77 4D M 93 5D ] 109 6D m 125 7D } 14 0E SO 30 1E RS 46 2E . 62 3E > 78 4E N 94 5E ^ 110 6E n 126 7E ~ 15 0F SI 31 1F US 47 2F / 63 3F ? 79 4F O 95 5F _ 111 6F o 127 7F DEL ``` ### Details * `(0 11 22 31 40 49 59 69)` contains the position of each column in a line, as obtained by inspecting the desired output. There were many corner cases that are simply better handled by hard-coding the exact position for each column and letting the `~T` format directive tabulate as needed. * Since names of characters are implementation-dependent, this code targets only the SBCL interpreter (I tested with CCL, which uses other names). I rely on `char-name` for most non-graphic characters, but some of them have explicit mappings to the expected output. ### Ungolfed ``` (progn (format t"~{~v,0TDec Hex ~}" '(0 11 22 31 40 49 59 69)) (dotimes(y 16) (fresh-line) (loop for x from 0 for k in '(0 11 22 31 40 49 59 69) for i = (+ (* 16 x) y) for c = (code-char i) do (format t "~v,0T~3d ~2,'0x ~a" k i i (if (graphic-char-p c) c (case i (8"BS") (9"HT") (10"LF") (12"FF") (13"CR") (127"DEL") (t (string-upcase (char-name c))))))))) ``` ]
[Question] [ Implement the shortest Sudoku solver using guessing. Since I have received a few request I have added this as an alternative [question](https://codegolf.stackexchange.com/questions/355/implement-a-non-guessing-sudoku-solver) for those wishing to implement a brute force sudoku solver. **Sudoku Puzzle:** ``` | 1 2 3 | 4 5 6 | 7 8 9 -+----------------------- A| 3 | 1 | B| 6 | | 5 C| 5 | | 9 8 3 -+----------------------- D| 8 | 6 | 3 2 E| | 5 | F| 9 3 | 8 | 6 -+----------------------- G| 7 1 4 | | 9 H| 2 | | 8 I| | 4 | 3 ``` **Answer:** ``` | 1 2 3 | 4 5 6 | 7 8 9 -+----------------------- A| 8 3 2 | 5 9 1 | 6 7 4 B| 4 9 6 | 3 8 7 | 2 5 1 C| 5 7 1 | 2 6 4 | 9 8 3 -+----------------------- D| 1 8 5 | 7 4 6 | 3 9 2 E| 2 6 7 | 9 5 3 | 4 1 8 F| 9 4 3 | 8 1 2 | 7 6 5 -+----------------------- G| 7 1 4 | 6 3 8 | 5 2 9 H| 3 2 9 | 1 7 5 | 8 4 6 I| 6 5 8 | 4 2 9 | 1 3 7 ``` **Rules:** 1. Assume all mazes are solvable by logic only. 2. All input will be 81 characters long. Missing characters will be 0. 3. Output the solution as a single string. 4. The "grid" may be stored internally however you wish. 5. The solution must using a brute force guessing solution. 6. Solutions should solve within a reasonable time limit. **Example I/O:** ``` >sudoku.py "030001000006000050500000983080006302000050000903800060714000009020000800000400030" 832591674496387251571264983185746392267953418943812765714638529329175846658429137 ``` [Answer] # k (72 bytes) Credit for this goes to Arthur Whitney, creator of the k language. ``` p,:3/:_(p:9\:!81)%3 s:{*(,x)(,/{@[x;y;:;]'&21=x[&|/p[;y]=p]?!10}')/&~x} ``` [Answer] # Python, 188 bytes This is a further shortened version of my winning submission for [CodeSprint Sudoku](https://sudoku.interviewstreet.com/), modified for command line input instead of stdin (as per the OP): ``` def f(s): x=s.find('0') if x<0:print s;exit() [c in[(x-y)%9*(x/9^y/9)*(x/27^y/27|x%9/3^y%9/3)or s[y]for y in range(81)]or f(s[:x]+c+s[x+1:])for c in'%d'%5**18] import sys f(sys.argv[1]) ``` If you're using Python 2, `'%d'%5**18` can be replaced with ``5**18`` to save 3 bytes. To make it run faster, you can replace `'%d'%5**18` with any permutation of `'123456789'` at a cost of 1 byte. If you want it to accept the input on stdin instead, you can replace `import sys;f(sys.argv[1])` with `f(raw_input())`, bringing it down to **177 bytes**. ``` def f(s): x=s.find('0') if x<0:print s;exit() [c in[(x-y)%9*(x/9^y/9)*(x/27^y/27|x%9/3^y%9/3)or s[y]for y in range(81)]or f(s[:x]+c+s[x+1:])for c in'%d'%5**18] f(raw_input()) ``` **EDIT:** [Here's a link to a more detailed walkthrough.](http://blog.cyphase.com/2012/12/07/playing-sudoku-beach/) [Answer] ## Python, 197 characters ``` def S(s): i=s.find('0') if i<0:print s;return for v in'123456789': if sum(v==s[j]and(i/9==j/9or i%9==j%9or(i%9/3==j%9/3and i/27==j/27))for j in range(81))==0:S(s[:i]+v+s[i+1:]) S(raw_input()) ``` [Answer] # Perl, 120 bytes Oh, I remember golfing that back in 2008... And it in fact stopped working in perl 5.12 since implicit setting of @\_ by split was removed then. So only try this on a sufficiently old perl. Run with the input on STDIN: ``` sudoku.pl <<< "030001000006000050500000983080006302000050000903800060714000009020000800000400030" ``` `sudoku.pl`: ``` ${/[@_[map{$i-($i="@-")%9+$_,9*$_+$i%9,9*$_%26+$i-$i%3+$i%9-$i%27}0..8%split""]]/o||do$0}for$_=$`.$_.$'.<>,/0/||print..9 ``` [Answer] # Answer in D: ``` import std.algorithm; import std.conv; import std.ascii; import std.exception; import std.stdio; void main(string[] args) { enforce(args.length == 2, new Exception("Missing argument.")); enforce(args[1].length == 81, new Exception("Invalid argument.")); enforce(!canFind!((a){return !isDigit(to!dchar(a));}) (args[1]), new Exception("Entire argument must be digits.")); auto sudoku = new Sudoku(args[1]); sudoku.fillIn(); writeln(sudoku); } class Sudoku { public: this(string str) nothrow { normal = new int[][](9, 9); for(size_t i = 0, k =0; i < 9; ++i) { for(size_t j = 0; j < 9; ++j) normal[i][j] = to!int(str[k++]) - '0'; } reversed = new int*[][](9, 9); for(size_t i = 0; i < 9; ++i) { for(size_t j = 0; j < 9; ++j) reversed[j][i] = &normal[i][j]; } boxes = new int*[][](9, 9); indexedBoxes = new int*[][][](9, 9); for(size_t boxRow = 0, boxNum = 0; boxRow < 3; ++boxRow) { for(size_t boxCol = 0; boxCol < 3; ++boxCol, ++boxNum) { for(size_t i = 3 * boxRow, square = 0; i < 3 * (boxRow + 1); ++i) { for(size_t j = 3 * boxCol; j < 3 * (boxCol + 1); ++j) { boxes[boxNum][square++] = &normal[i][j]; indexedBoxes[i][j] = boxes[boxNum]; } } } } } void fillIn() { fillIn(0, 0); } @property bool valid() { assert(full); for(size_t i = 0; i < 9; ++i) { for(int n = 1; n < 10; ++n) { if(!canFind(normal[i], n) || !canFind!"*a == b"(reversed[i], n) || !canFind!"*a == b"(boxes[i], n)) { return false; } } } return true; } override string toString() const { char[81] retval; for(size_t i = 0, k =0; i < 9; ++i) { for(size_t j = 0; j < 9; ++j) retval[k++] = to!char(normal[i][j] + '0'); } return to!string(retval); } private: @property bool full() { for(size_t i = 0; i < 9; ++i) { if(canFind(normal[i], 0)) return false; } return true; } bool fillIn(size_t row, size_t col) { if(row == 9) return valid; size_t nextRow = row; size_t nextCol = col + 1; if(nextCol == 9) { nextRow = row + 1; nextCol = 0; } if(normal[row][col] == 0) { for(int n = 1; n < 10; ++n) { if(canFind(normal[row], n) || canFind!"*a == b"(reversed[col], n) || canFind!"*a == b"(indexedBoxes[row][col], n)) { continue; } normal[row][col] = n; if(fillIn(nextRow, nextCol)) return true; } normal[row][col] = 0; return false; } else return fillIn(nextRow, nextCol); } int[][] normal; int*[][] reversed; int*[][] boxes; int*[][][] indexedBoxes; } ``` With the sample input, it takes **.033s** on my Phenom II X6 1090T when compiled with `dmd -w` (i.e. without optimizations), and it takes **.011s** when compiled with `dmd -w -O -inline -release` (i.e. with optimizations). [Answer] ## Perl, 235 chars ``` $_=$s=<>;$r=join$/,map{$n=$_;'.*(?!'.(join'|',map+($_%9==$n%9||int($_/9)==int($n/9)||int($_/27)==int($n/27)&&int($_/3%3)==int($n/3%3)and$_<$n?'\\'.($_+1):$_>$n&&substr$s,$_,1)||X,@a).')(.).*'}@a=0..80;s!.!($&||123456789).$/!eg;say/^$r/ ``` This is a golfed version of [something I posted many years ago to the Fun With Perl mailing list](http://www.nntp.perl.org/group/perl.fwp/2006/04/msg3836.html): a sudoku-solving regexp. Basically, it mangles the input into 81 lines, each containing all the numbers that could occur in the corresponding square. It then constructs a regexp to match one number from each line, using backreferences and negative lookahead assertions to reject solutions that violate the row, column or region constraints. Then it matches the string against the regexp, letting Perl's regexp engine do the hard work of trial and backtracking. Astonishingly, it's possible to create a single regexp that works for any input, like my original program does. Unfortunately, it's quite slow, so I based the golfed code here on the hardcoded-givens version ([found later in the FWP thread](http://www.nntp.perl.org/group/perl.fwp/2006/04/msg3838.html)), which tweaks the regexp to reject early any solutions that it knows will later violate a constraint. This makes it reasonably fast for easy to moderate level sudokus, although particularly hard ones can still take a rather long time to solve. Run the code with `perl -M5.010` to enable the Perl 5.10+ `say` feature. The input should be given on standard input, and the solution will be printed to standard output; example: ``` $ perl -M5.010 golf/sudoku.pl 030001000006000050500000983080006302000050000903800060714000009020000800000400030 832591674496387251571264983185746392267953418943812765714638529329175846658429137 ``` [Answer] # J, 103 ``` 'p n'=:(;#)I.0=a=:("."0)Y ((a p}~3 :'>:?n#9')^:([:(27~:[:+/[:(9=#@~.)"1[:,/(2 2$3),;.3],|:,])9 9$])^:_)a ``` *expected run time: O(gazillion billion years)* [Answer] 1-liner coffee-script `solve = (s, c = 0) -> if c is 81 then s else if s[x = c/9|0][y = c%9] isnt 0 then solve s, c+1 else (([1..9].filter (g) -> ![0...9].some (i) -> g in [s[x][i], s[i][y], s[3*(x/3|0) + i/3|0][3*(y/3|0) + i%3]]).some (g) -> s[x][y] = g; solve s, c+1) or s[x][y] = 0` [Here is the bigger version with sample usage](https://gist.github.com/3863614): ``` solve = (sudoku, cell = 0) -> if cell is 9*9 then return sudoku x = cell%9 y = (cell - x)/9 if sudoku[x][y] isnt 0 then return solve sudoku, cell+1 row = (i) -> sudoku[x][i] col = (i) -> sudoku[i][y] box = (i) -> sudoku[x - x%3 + (i - i%3)/3][y - y%3 + i%3] good = (guess) -> [0...9].every (i) -> guess not in [row(i), col(i), box(i)] guesses = [1..9].filter good solves = (guess) -> sudoku[x][y] = guess; solve sudoku, cell+1 (guesses.some solves) or sudoku[x][y] = 0 sudoku = [ [1,0,0,0,0,7,0,9,0], [0,3,0,0,2,0,0,0,8], [0,0,9,6,0,0,5,0,0], [0,0,5,3,0,0,9,0,0], [0,1,0,0,8,0,0,0,2], [6,0,0,0,0,4,0,0,0], [3,0,0,0,0,0,0,1,0], [0,4,0,0,0,0,0,0,7], [0,0,7,0,0,0,3,0,0] ] console.log if solve sudoku then sudoku else 'could not solve' ``` [Answer] ## D (322 chars) For each unsolved square it builds an array of available options and then loops over it. ``` import std.algorithm,std.range,std.stdio;void main(char[][]args){T s(T)(T p){foreach(i,ref c;p)if(c<49){foreach(o;"123456789".setDifference(chain(p[i/9*9..i/9*9+9],p[i%9..$].stride(9),p[i/27*27+i%9/3*3..$][0..21].chunks(3).stride(3).joiner).array.sort)){c=o&63;if(s(p))return p;}c=48;return[];}return p;}s(args[1]).write;} ``` with whitespace: ``` import std.algorithm, std.range, std.stdio; void main(char[][] args) { T s(T)(T p) { foreach (i, ref c; p) if (c < 49) { foreach (o; "123456789".setDifference(chain( p[i/9*9..i/9*9+9], p[i%9..$].stride(9), p[i/27*27+i%9/3*3..$][0..21].chunks(3).stride(3).joiner ).array.sort)) { c = o&63; if (s(p)) return p; } c=48; return []; } return p; } s(args[1]).write; } ``` [Answer] ## Clojure - 480 bytes The size exploded, but atleast it's a pretty number. I think it could be improved a lot by using just 1D-vector. Anyways, the test case takes a little under four seconds on my laptop. I thought it would be fitting to define a function, as it is a functional language after all. ``` (defn f[o &[x y]](if x(if(> y 8)(apply str(map #(apply str %)o))(first(for[q[(o y)]v(if(=(q x)0)(range 1 10)[(q x)])d[(assoc o y(assoc(o y)x v))]s[(and(every? true?(concat(for[i(range 9)](and(or(not=((d y)i)v)(= i x))(or(not=((d i)x)v)(= i y))))(for[m[#(+ %2(- %(mod % 3)))]r[(range 3)]a r b r c[(m y b)]e[(m x a)]](or(and(= e x)(= c y))(not=((d y)x)((d c)e))))))(f d(mod(+ x 1)9)(if(= x 8)(+ 1 y)y)))]:when s]s)))(f(vec(for[a(partition 9 o)](vec(map #(Integer.(str %))a))))0 0))) ``` Examples: ``` (f "030001000006000050500000983080006302000050000903800060714000009020000800000400030") => "832591674496387251571264983185746392267953418943812765714638529329175846658429137" (f "004720900039008005001506004040010520028050170016030090400901300100300840007085600") => "654723981239148765871596234743819526928654173516237498482961357165372849397485612" ``` A slightly ungolfed (and prettier) version: ``` (defn check-place [o x y v] (and (every? true? (for [i (range 9)] (and (or (not= ((o y) i) v) (= i x)) (or (not= ((o i) x) v) (= i y))))) (every? true? (for [r [(range 3)] a r b r c [(+ b (- y (mod y 3)))] d [(+ a (- x (mod x 3)))]] (or (and (= d x) (= c y)) (not= ((o y) x) ((o c) d))))))) (defn solve-sudoku [board & [x y]] (if x (if (> y 8) (apply str (map #(apply str %) board)) (first (for [v (if (= ((board y) x) 0) (range 1 10) [((board y) x)]) :let [a (mod (+ x 1) 9) b (if (= x 8) (+ 1 y) y) d (assoc board y (assoc (board y) x v)) s (and (check-place d x y v) (solve-sudoku d a b))] :when s] s))) (solve-sudoku (vec (for [a (partition 9 board)] (vec (map #(Integer. (str %)) a)))) 0 0))) ``` [Answer] # J, 94 bytes Works in exactly the same way as the K version, namely with a BFS (so it shall output all solutions). It prints spaces between output digits, but so does the K program. I’m not counting “s=:” as this is just naming the function (just like I wouldn’t count the filename in another language). ``` s=: [:<@((]i.0:)}"0 _~(>:i.9)-.{&((+./ .=|:)3(],.[,@#.<.@%~)9 9#:i.81)@i.&0#])"1^:(0 e.,)@;^:_"."0 s'030001000006000050500000983080006302000050000903800060714000009020000800000400030' 8 3 2 5 9 1 6 7 4 4 9 6 3 8 7 2 5 1 5 7 1 2 6 4 9 8 3 1 8 5 7 4 6 3 9 2 2 6 7 9 5 3 4 1 8 9 4 3 8 1 2 7 6 5 7 1 4 6 3 8 5 2 9 3 2 9 1 7 5 8 4 6 6 5 8 4 2 9 1 3 7 ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~244~~ ~~242~~ ~~218~~ 215 bytes ``` $a=(24,24,6)*3|%{,(0..8|%{($r++)});,(0..8|%{$c%81;$c+=9});$c++;,((1,1,7)*3|%{+$q;$q+=$_});$q-=$_} $f={param($s)$l,$r=$s-split0,2;if($p=$a|?{$l.length-in$_}){1..9|?{"$_"-notin($p|%{$s[$_]})}|%{&$f "$l$_$r"}}else{$s}} ``` [Try it online!](https://tio.run/##1VLbrpswEHznKyzOpoJykS9g7EaolfrcL6gqhBLnHFQCBBO1EuHb0zWkR@17VeksaFnPjGf2gaH/YUb7Ytr2foe6DHgW4yvD9@K2m@OApqnCIYAxisIl3L8icNgptodDVGqE8RshF7CYxcV2N4LLHi5RCZXjL4kbPDiV81CP9TkAG0Ibw1iCTezQNhON@b45BTCUUN8@ztCmremep5ek6ZzFzNJUI@5D5SddPzUdSt0e9itU35ZwwfkdnIgPLVQw@stiWmuQXpb7p8AjWDEJiK8EzzWTRZZpKVTBc5YXjMtMK8FUXmRSaM5loXORMaUzoRgvJEqQUDnXgmtW5CqTEhulVFA/Xs1d/VNznEXhk9Bb7Z9@b4@ZjLqSruX4uMIAqhwoKN9wB1KxYhQDNtVGqvXw1/ZP/2l/@hb3D8mN7Mi8BoG9Hvvv15iA@TmYw2SOpCRQbdzUnA0ev5jaXkeTfO7P57o7Pm6uitHYazuhxv2qD6@VXdbuQ/CQJIe@m@qms6854YctwPf@cPKW@y8 "PowerShell – Try It Online") The script finds all solutions for a sudoku. Unrolled: ``` $a=(24,24,6)*3|%{ # array of indexes for a sudoku... ,(0..8|%{($r++)}) # rows ,(0..8|%{$c%81;$c+=9});$c++ # columns ,((1,1,7)*3|%{+$q;$q+=$_});$q-=$_ # and squares } $f = { param($s) # optional log. remove this statement in a release version. if($script:iter++ -lt 100 -or ($script:iter%100)-eq0){ Write-Information ('{0}: {1,6}: {2}'-f (get-Date), $script:iter, ($s-replace0,' ')) -InformationAction Continue } $left,$right=$s-split0,2 # split by a first 0; $left.length is a position of this 0 if $s contains the 0 if( $parts=$a|?{$left.length-in$_} ){ # get sudoku parts (rows, columns, squares) contain the position 1..9|?{ # try a digit "$_"-notin($parts|%{$s[$_]}) # all digits in these parts will be unique if parts do not contain the digit }|%{ &$f "$left$_$right" # recursive call with the digit } #|select -f 1 # uncomment this to get a first result only } else{ $s } } ``` Test cases: ``` @( # 5 iterations, my notebook: 00:00:00, all # 5 iterations, my notebook: 00:00:00, first only , ( "832591674496387251571264983185746392267953418943812765714638529329175846658400030", "832591674496387251571264983185746392267953418943812765714638529329175846658429137" ) # ~29600 iterations, my notebook: 00:01:27, all # ~2100 iterations, my notebook: 00:00:10, first only # , ( "830001000006000050500000983080006302000050000903800060714000009020000800000400030", # "832591674496387251571264983185746392267953418943812765714638529329175846658429137" ) # ~49900 iterations, my notebook: 00:02:39, all # ~22400 iterations, my notebook: 00:01:20, first only # , ( "030001000006000050500000983080006302000050000903800060714000009020000800000400030", # "832591674496387251571264983185746392267953418943812765714638529329175846658429137" ) ) | % { $sudoku, $expected = $_ $time = Measure-Command { $result = &$f $sudoku } "$($result-contains$expected): $time" $result } ``` [Answer] ## Perl (195 chars) ``` use integer;@A=split//,<>;sub R{for$i(0..80){next if$A[$i];my%t=map{$_/9==$/9||$_%9==$i%9||$_/27==$i/27&&$_%9/3==$i%9/3?$A[$_]:0=>1}0..80;R($A[$i]=$_)for grep{!$t{$_}}1..9;return$A[$i]=0}die@A}R ``` All credit goes to the creator [here](http://www.ecclestoad.co.uk/2005/06/sudoku-solver-in-three-lines-explained), and the explanation can be found there as well. ]
[Question] [ Originally from [caird coinheringaahing's idea](https://codegolf.meta.stackexchange.com/questions/24021/advent-of-code-golf), I (Bubbler) am hosting [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/questions/24068/announcing-advent-of-code-golf-2021-event-challenge-sandbox). On each day from today (Dec 1) until Christmas (Dec 25), a challenge will be posted at UTC midnight, just like an Advent calendar. It is a free-for-all and just-have-fun-by-participation event, no leaderboards and no prizes for solving them fast or solving them in the shortest code. More details can be found in the link above. For this year's event, the challenge ideas were drawn from the previous AoC events (2015 - 2020). --- The story continues from [AoC2015 Day 3](https://adventofcode.com/2015/day/3), Part 2. --- Santa is delivering presents to an infinite two-dimensional grid of houses. He begins by delivering a present to the house at the starting location, and then follows the commands written as a sequence of moves `^>v<` (moving to the neighboring house to the north, east, south, or west respectively), delivering a present at the house after each move. Next year, Santa brings up a Robo-Santa for faster delivery. Santa and Robo-Santa start at the same location (giving two presents to the same house), and take turns to move based on the commands. Assume the command is `^v^v^v^v^v`. Santa alone would deliver a bunch of presents to only two houses (the start and its north neighbor), but with a Robo-Santa, they would deliver presents to 11 different houses (Santa moving north 5 times and Robo-Santa moving south 5 times). Now Santa wonders: Given a sequence of instructions, how many Santas (Santa and any Robo-Santas) are needed to deliver presents to the maximum number of houses? If two or more Robo-Santas are present, Santa and the Robo-Santas will take turns cyclically to follow the commands, everyone stopping when the commands run out (the number of commands does not have to be divisible by the number of Santas). If multiple options are available, choose the smallest number of Robo-Santas (it takes time and money to build them). **Input:** A nonempty string of `^>v<` instructions. **Output:** The minimum number of Santas in total for maximum delivery. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` >>>>> -> 1 (everyone moving to the same house is surely a loss) ^v^v^v^v^v -> 2 (one additional Robo-Santa will deliver to 11 different houses, the possible maximum) v>^>v<^< -> 5 (5 Santas will deliver to 7 distinct houses; 1, 3, 4, or 7 Santas will deliver to 6 distinct houses and other choices to fewer houses) vv>^<^^<v> -> 1 (Any of 1, 4, 6, or 7 Santas will deliver to 8 distinct houses, but 1 is the best choice out of them) ``` [Answer] # TypeScript Types, 670 bytes ``` // @ts-ignore type c<T,A=[]>=(((T extends T?(t:0)=>T:0)extends infer U?(U extends U?(u:U)=>0:0)extends(v:infer V)=>0?V:0:0)extends(_:0)=>infer W?c<Exclude<T,W>,[...A,0]>:A);type i<T>=T extends[0,infer X]?X:[1,T];type d<T>=T extends[1,infer X]?X:[0,T];type m<P,C>={"^":[i<P[0]>,P[1]],v:[d<P[0]>,P[1]],"<":[P[0],i<P[1]>],">":[P[0],d<P[1]>]}[C];type n<P,C>=[P[0]|m<P[1],C>,m<P[1],C>];type s<S,I>=I extends`${infer C}${infer I}`?S extends[infer A,...infer B]?s<[...B,n<A,C>],I>:0:c<S[number][0]>;type q=[[[],[]],[[],[]]];type M<S,K=S,B=[],BN=[],N=[q]>=K extends`${infer _}${infer K}`?B extends[...s<N,S>,...infer _]?M<S,K,B,BN,[...N,q]>:M<S,K,s<N,S>,N,[...N,q]>:BN["length"] ``` [Try it online!](https://www.typescriptlang.org/play?#code/PTAEAEBcGcFoEsDmA7A9gJwKYChIE8AHTUAYwB4AVAGgEEBeAbQF0A+OgCk4tEwA9JMyACbRQFAPztIALgAMASjosKc+XwHDR8ZADNM6UAFVJhnv0EijkgK7TDilrNXqL0dgDdp2vQYBqD2XFfOWdzTXYAfVUlb31QAHVxcgBRXhIAG2shTEoqeJYqBgA6EpoqWVZpGnkAbnwiUHhKNm4XTQZZKliDAA0mcR7pBgBGKgomOsJiIWa6VrCREa7dOL6Boc7xyYaAWzIABSoAYTYAbwAiAD1zoab9jtYqe+GmJipPBhn7ioLn16pzmQbgxvm87iNWG9zixgaCqF8ISwmABfBhHCb1YjIA7HNggh4AHz2f1xVGJENxGKmoGgZAAylQAJJsRlmDQiAAGABJTt1QEdkTy+YzkRzxHS2a4GHyyiUinyAEL9WnFEoKqjYsonN7MkLkOkMZDWHYAI30TAeLG2xAAjowGMxCv8HW9mK9raAALL0qgAaToDIVjDeCoAcsGqOGGDbWHRfZLNNzeSsDBFBcmfKBfaLxAqE4s5bTQ1Q6QU5XyIv1vQzfVR1WHCnLizGWNJq36qEWSwVi6qis3KmGGOd0oJEJAABbnJjYXDUiiyUB0L1AlhrtfQmrYECgXeXcRzhoUYZLldXdyXC9Xy+b7dgPcHzFiABMp+953cLEuLHcZEuq63HcH0PYgKAAZjfIF3E-f9Ln-T9byA0B92wIA) [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 89 bytes ``` s->vecsort([-#Set(Vec(Ser([I^c|c<-Vec(Vecsmall(s))%11])/(1-x^i),#s+1))|i<-[1..#s]],,1)[1] ``` [Try it online!](https://tio.run/##NYzBCgIhFEV/RRwCH@mEe3PfeqCN@GAQC2Eq8Q1SMP9uY9C9XDhnc/NckrrndmPnRsrWGOhVVuHUMMVVXGMQUyzCXTBswaju@@gxL4sggIPWHk5CqzcmkAMdNcCWjHJ6HAfyXkoNTvs257x8BDFlWS7pue7Iu3B26zeSOW57uGQc67/dqkVbDZof72IQTbXcQ/sC "Pari/GP – Try It Online") The ASCII codes of `<^>v` are`[60, 94, 62, 118]`, which become `[5, 6, 7, 8]` when modulus 11. After that, it is the usual power series tricks: $$(a\_0+a\_1x+\cdots)/(1-x^k)=a\_0+a\_1x+\cdots+(a\_0+a\_k)x^k+(a\_1+a\_{k+1})x^{k+1}+\cdots$$ [Answer] # [Rust](https://www.rust-lang.org/), 239 234 bytes ``` |i|{let mut r=vec![];for l in 1..i.len(){let(mut s,mut v)=(vec![0;l*2],vec![(0,0)]);for c in i.bytes(){s[c as usize%3&1]+=1-(c as i64%5&2);v.push((s[0],s[1]));s.rotate_left(2);}v.sort();v.dedup();r.push((!v.len(),l));}r.sort();r[0].1} ``` [Try it online!](https://tio.run/##NZDdbsIwDIXveQqDROWwELVs7GL9eZEqRR2kWqRSWJxG2qDP3iWBOVJkHZ/POrIZyc7dAOdWD8jgtgBfvbLQfXQDJmQNg20FByhhvuv7LYzOowVTOnVc1jLvLgZ60ANkQmjRK78lmDCYiIffsRKjOc37zU7y2GPKUyZZxI8B1@LzxyryNNVHaAlG0r9q/Zpk8qXMthg1/f623ic7ljtxHekLkepUcqozyVhOwlxsa9WhV51Fb5qcoIuxGOwndRqvvjNPcOkeWXnvycn8G43fJ7JpzuMdQjjUXLEQMKlxVYVaccgYB1w17v95aRclVzWVK5rCC/uH4JWiaQr3wOTzwqFaImXsQX0vcaM4dKh9lDidFtP8Bw "Rust – Try It Online") Ungolfed: ``` |i| { let mut r = vec![]; for l in 1..i.len() { let (mut s, mut v) = (vec![0; l * 2], vec![(0, 0)]); for c in i.bytes() { s[c as usize % 3 & 1] += // %3 - bit 1 flips, s[0] or s[1] 1 - (c as i64 % 5 & 2); // %5 - bit 2 flips, 0 or 2 v.push((s[0], s[1])); s.rotate_left(2); } v.sort(); v.dedup(); r.push((!v.len(), l)); // dirty negation to reverse tuple sort order } r.sort(); r[0].1 }; ``` History: * -5 by removing the type annotation for `i` (thanks @Aiden4) [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 111 bytes ``` lambda s:(L:=range(len(s)))[-max((len({0}|{sum(1j**(ord(d)%11)for d in s[j::~i])for j in L}),~i)for i in L)[1]] ``` [Try it online!](https://tio.run/##VczRCoIwFMbx@55iBME5UtDoJob6BL6BOVhMa6JTNhuF6auvHBR4vqv/7@L0r@He6dO5N75KLr4R7VUKYhlkLDFC30poSg0WEfNDK54QcjxO79E@WqB1FEFnJEjcUYpVZ4gkShOb14zNqghSL5JNuJ9VaBUac1oUvjdKD1DBNl1ui7j5C3e/rdilPHUxj9f41Zjz2C0v/Ac "Python 3.8 (pre-release) – Try It Online") Use `%11` trick from [alephalpha's answer](https://codegolf.stackexchange.com/a/237857/44718). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 39 [bytes](https://github.com/abrudz/SBCS) ``` ⊃⍒{≢∪0,∊+⍀n ⍵⍴y↑⍨n×⍵}¨⍳n←≢y←0J1*'^<v'⍳⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@jruZHvZOqH3UuetSxykDnUUeX9qPehjyFR71bH/VuqXzUNvFR74q8w9OB/NpDKx71bs571DYBqBooM8HAy1BLPc6mTB0o/Kh3HsjA/2lcdiDAlcYVVwaDQE6ZXZxdmU2cDYgJZNvEAbXZAQA "APL (Dyalog Unicode) – Try It Online") `y←0J1*'^<v'⍳⍞`: Take character input and map the characters to complex numbers, storing the resulting vector in j. ``` < > ^ v ¯1 1 0J1 0J¯1 ``` `⍳n←≢y`: Store the length of y in n and create a range from 1 to n (possible number of Santas) `{ ... }¨`: For each number of Santas evaluate the a function which returns the number of houses visited. `⊃⍒`: The first index of the maximal value. (Indices that would sort the vector descendingly; take the first one) For the inner function `⍵` is the number of Santas to test and the other variables are still accessible. `y↑⍨n×⍵`: Pad y to length `n×⍵` by appending 0's. `n ⍵⍴`: Reshape into a matrix with n columns and `⍵` rows. `+⍀`: Get cumulative sums of the columns. `0,∊`: Flatten and prepend a 0. `≢∪`: Count the number of unique values. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 43 bytes ``` FLθ«F⊕ι«J⁰¦⁰F✂θκLθ⊕ι✳⊗⌕^>vλ¹*»⊞υLKA⎚»I⊕⌕υ⌈υ ``` [Try it online!](https://tio.run/##XU/NCsIwDD5vTxF2SqWCnhVBFEFRGOhZqDW6YtdqbYcgPnutGwiaU/L9ElkJJ63QMZ6sA1yTOfsKb4zBM89aaGmko5qMpyOqDs9Wob7uLA44DNgo3a1wq5UkvHG4cPjmcPjzMyidMh7nypH0yhqc23DQiVwoc8RiP2kKDjoJOQzb8E5f9IrP9cqzMtwrDN@Okugy1RqTI/EzTcJh2l5555uJu//5oa1J9o14qDrUGNhnRjE2k9Q93o9jv9Fv "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FLθ« ``` Loop over the length of the string, representing the number of Robo-Santas. ``` F⊕ι« ``` Loop over Santa and his Robo-Santas. ``` J⁰¦⁰F✂θκLθ⊕ι✳⊗⌕^>vλ¹* ``` Draw the route this (Robo-)Santa takes, starting at the origin. (Would be -5 bytes for input in `urdl` format. Interestingly giving PolygonHollow its preferred `urdl` format would be [39 bytes](https://tio.run/##S85ILErOT8z5///9nmXv96w5t@PQaiDrUdfUcztBrFWPGjccWgYk3u9Z/n7PikdzNoNR07kd53aBlUNUbtI6tPtR17zzrUCx93uA@hY@6pt1aPf7PSuB8o96pp5vfdTTcb71//@UotKilJzSHAA "Charcoal – Try It Online"), so slightly longer.) ``` »⊞υLKA ``` Save the count of all visited houses. ``` ⎚ ``` Clear the canvas ready for the next possible number of Robo-Santas or to output the result. ``` »I⊕⌕υ⌈υ ``` Find how many Robo-Santas are needed for the maximum possible count and add one for Santa himself. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` āει8ìS"^>v<"6ÅȇD8Ê>∞₆+çNè©sr.Λ®¢}Zk> ``` [Try it online](https://tio.run/##AUoAtf9vc2FiaWX//8SBzrXOuTjDrFMiXj52PCI2w4XDiOKAoUQ4w4o@4oie4oKGK8OnTsOowqlzci7Om8KuwqJ9Wms@//92Pl4@djxePA) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKS/f8jjee2nttpcXhNsFKcXZmNktnh1sMdjxoWulgc7rJ71DHvUVOb9uHlfodXHFpZXKR3bvahdYcW1UZl2/2vPbxehwtkFld5RmZOqkJRamKKQmYeV0o@l4KCfn5BiT7ESiiF5gobBRWw2rzU/3YgwBVXBoNcZXYgl8TZcJUBWTZxcTZldlwA). **Explanation:** ``` ā # Push a list in the range [1,input-length] ε # Map over each of these integers: ι # Uninterleave the (implicit) input-string into this many parts, # resulting in the route of each individual (Robo-)Santa 8ì # Prepend an 8 in front of each string S # Then convert it to a flattened list of characters "^>v<" # Push string "^>v<" 6ÅÈ # Push list [0,2,4,6] ‡ # Transliterate all "^" to 0; ">" to 2; etc. D # Duplicate this list of digits 8Ê # Check for each that it's NOT equal to 8 (0 if 8; 1 otherwise) > # Increase each by 1 (1 if 8; 2 otherwise) ∞ # Push an infinite positive list: [1,2,3,...] ₆+ # Add 36 to each: [37,38,39,...] ç # Convert each to a character with this codepoint: # ["%","&","'",...] Nè # Index the map-index into this list © # Store the character in variable `®` (without popping) sr # Rearrange the three values on the stack from a,b,c to b,c,a .Λ # Use the modifiable Canvas builtin with these three arguments ®¢ # Count the amount of character `®` in the Canvas-string }Z # After the map: push the max (without popping the list) k # Get the first (0-based) index of this max > # Increase it by 1 to make it 1-based # (after which it is output implicitly as result) ``` **In-depth step-by-step explanation:** (Uses input `v>^>v<^<` as example.) 1) `āει`: the `ā` results in the amount of (Robo-)Santas we want to check per iteration, and the `ει` will map this to routes per individual (Robo-)Santa: [Try just this step online.](https://tio.run/##yy9OTMpM/f//SOO5red2/v9fZhdnV2YTZwMA) 2) `8ìS"^>v<"6Åȇ` will convert these routes to something usable by the Canvas builtin. The Canvas Builtin uses three arguments to draw a shape: * Length of the lines we want to draw * Character/string to draw * The direction to draw in, where each digit represents a certain direction: ``` 7 0 1 ↖ ↑ ↗ 6 ← X → 2 ↙ ↓ ↘ 5 4 3 ``` And in addition there are a couple of special directions (`+×8`), for which we'll only use `8` in this program. `8` will reset the Canvas starting point. So something like `["v>^",">v<","^<"]` (three (Robo-)Santa routes) will with `8ìS"^>v<"6Åȇ` translate to: `[8,4,2,0,8,2,4,6,8,0,6]`. [Try the first two steps online.](https://tio.run/##yy9OTMpM/f//SOO5red2WhxeE6wUZ1dmo2R2uPVwx6OGhf//l9mBBOJsAA) 3) Using what we created in step 2 as the directions-argument, `D8Ê>` for our lengths-argument, and `∞₆+çNè` for the character we want to draw, we use the modifiable Canvas builtin `.Λ`. With the example of the three (Robo-)Santa routes above, it'll have the following three arguments: * Lengths: `[1,2,2,2,1,2,2,2,1,2,2]` (1 for every `8`, 2 for every actual movement) * Character: `"'"` * Directions: `[8,4,2,0,8,2,4,6,8,0,6]` Step 3.1: Draw 1 character at starting point `8`: ``` ' ``` Step 3.2: Draw 2-1 character in direction 4/`↓`: ``` ' ' ``` Step 3.3: Draw 2-1 character in direction 2/`→`: ``` ' '' ``` Step 3.4: Draw 2-1 character in direction 0/`↑`: ``` '' '' ``` Step 3.5: Draw 1 character at starting point `8` again. Step 3.6: Draw 2-1 character in direction `2`/`→`: ``` '' '' ``` Step 3.7: Draw 2-1 character in direction 4:/`↓`: ``` '' '' ``` Step 3.8: Draw 2-1 character in direction 6/`←`: ``` '' '' ``` Step 3.9: Draw 1 character at starting point `8` again. Step 3.10: Draw 2-1 character in direction 0/`↑`: ``` ' '' '' ``` Step 3.11: Draw 2-1 character in direction 6/`←`: ``` '' '' '' ``` The reason we draw a different character every time and also have a leading `8` to reset to the starting point, is because there isn't any way to clear the Canvas. The next iteration we use the `.Λ`, it'll basically continue where it left off in the previous iteration. We therefore have to do an initial reset, and we draw all the characters on top of each other, which can be seen in the TIO below: [Try the first three steps online.](https://tio.run/##yy9OTMpM/f//SOO5red2WhxeE6wUZ1dmo2R2uPVwx6OGhS4Wh7vsHnXMe9TUpn14ud/hFYdWFhfpnZv9/3@ZHUhhnA0A) [See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210) 4) `®¢}`: count (`¢`) how many distinct houses all the (Robo-)Santa have visited, by checking how many times the current character (which we've saved in variable `®`) is in the resulting Canvas-string. [Try the first four steps online.](https://tio.run/##AUYAuf9vc2FiaWX//8SBzrXOuTjDrFMiXj52PCI2w4XDiOKAoUQ4w4o@4oie4oKGK8OnTsOowqlzci7Om8KuwqL//3Y@Xj52PF48) 5) `Zk>`: now that we have the amount of houses that can be visited depending on the amount of (Robo-)Santa going around doing their routes, we can get the maximum (`Z`) amount of houses visited, and get the first (1-based) index of this maximum (`k>`) to get the lowest amount of (Robo-)Santa necessary to achieve this maximum amount of visited houses, which will be output as our result. [Answer] # Java, 349 bytes ``` s->{var p=new HashSet<String>();for(int i=s.length();i>0;i--){for(int j=0;j<i;j++){int x=0,y=0;p.add(i+","+x+","+y);for(int k=j;k<s.length();k+=i){int c=s.charAt(k)%11;var t=c==6?y++:(c==7?x++:(c==8?y--:x--));p.add(i+","+x+","+y);}}}int[]n=new int[s.length()];p.stream().map(a->a.substring(0,a.indexOf(','))).map(Integer::parseInt).forEach(i->n[i-1]++);int m=0,i=0;for(;i<n.length;i++){m=n[i]>n[m]?i:m;}return m+1;} ``` [Try it online.](https://tio.run/##bVJNi9swEL3nVwyGshKORXJpF8tyKKXQHtoecgwOaG0lkT8UIyluQvBvT8eOk91Dx2CNnmbe08yolJ2MyqK66aY9Wg8l7tnJ65r9kO6wVp7PZnktnYNfUhu4zgBNG6/sTuYKfk/IhEJO1t5qswdH@XjQz8bFeel1juEGBNxclF47aaEVRv2FSSi5Z6aE8t3RkoFNC8dqZfb@gKBOF1xHEb0@Tkux4GWieRmG9DoAZ7GYXxBsmSwKosNgHoTn8X9556xEyavkA28VCn3Pz1EuP0j71ZOKflou@XBHL3IhPq8uYRgT9L6szpP3urpEUXzGG9H/K/Z9j6ybzIxVDu67aoYpzlslG0JZI1sio1Qyd3pzYxPIYi6ZNoU6/9mRl/kLpfeon9j4vbJx3ErrFO4ow7q@y/xAdJSajY6WGXaDD9U02A2N3RgK5zoxkzbXQ7sagcEZZjTZSscN763yJ2ugCZe8v/H70NrTW41Dm2bXHXUBDT6CacSbDCT9MH7Ugcf0vXL@m3QKYgjSwWDbPT7o0m3aJdsEOvSS7Tbp0oC5ttaeBBBQ@mQcbH1xXjXsePKsRWpfG/IkDyFAflwMy58ofT68/vYP) **Explanation:** ``` s -> { var p = new HashSet<String>(); // using Hash-Set for built in distinct elements int h = s.length(), i = h, j, x, y, k, c, n[] = new int[h]; // setting up variables for (; i > 0; i--) // loop for possible Santas for (j = 0; (k = j++) < i;) // loop every Santa for (p.add(i + ",0," + (x = y = 0)); k < h; k += i) { // add starting position and loop Santa over moves c = (c = s.charAt(k) % 11) == 6 ? y++ : c == 7 ? x++ : c == 8 ? y-- : x--; p.add(i + "," + x + "," + y); // change position and add it } for (p.stream() // .map(a -> a.substring(0, a.indexOf(44))) // only look at Santas number for each house .map(Integer::parseInt) // .forEach(I -> n[I - 1]++); h-- > 0;) // add visited Houses together i = n[h] > n[i] ? h : i; // finding the index of the greatest element return -~i; // negate and bit-flip } ``` Improvements: * -37 bytes: Using `var` where possible and changing `switch-case` statement to tenary operators * -1 byte: treating chars as int and using alephalpha's modulo-trick * -2 bytes: spaces * -66 bytes: thanks to ceilingcat (learned some java magic I wasn't aware of) What I learned (as I never coded a challenge befor nor golfed code): * Java is a horrible language to golf (but I'm not good enough in other languages... so ¯\*(ツ)*/¯ ) * I am far to slow to be competetiv in this AoCG-thing... [Answer] # Python, 134 bytes ``` k,*t,x=input(),1 for _ in k: p=[0]*x;q={0} for c in k:n=p.pop(0)+1j**(ord(c)%11);p+=n,;q|={n} t+=(-len(q),x),;x+=1 print(min(t)[1]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY4xDoIwFEBnegoWk5YWQzdjKRch4IASK_r7IYXUoKuXcGHReCVvowbHl5eXvPsTz25vYZoevavj1fvWiMgJrw1g7ygTktS2CzehgbBZkwB1nhSRV60ekysJfq6aHWhcokWaMC4PUURtt6UVW0jJFHINQrUXPcK3cVzT-LgD2jLhmVCea0mwM-DoyQB1LJcFm2_-U9NryMpsSMt05g8) -21 bytes by stealing alephalpha's codepoint mapping trick. -11 bytes thanks to pxeger [Answer] # [Ruby](https://www.ruby-lang.org/), ~~121 ...~~ 93 bytes ``` ->s{a=0;q=s.bytes;q.map{[-((*w=[0i]*a+=1)|q.map{|y|w.rotate![0]+=1i**y%=19}).size,a]}.min[1]} ``` [Try it online!](https://tio.run/##PY3RCoMgGIXve4oWBK2V6NbNSHsRUbBhEKyt0lWufPZmRPv/q/Mdzjn9pzRrRda0ULMgMO@IAqXRUuUdaEQ70zSK4pFQWLNYXAg6LztfzDKC/q2FlicKmXPqODYhQXd7Bqr@ykQwC5r6RRGza@tHGQAIQufJp3zoLR9gXgzBvrZ3TssUmjCzhNBbck1QApn1vNavaFBsF7Bd8OH4gwyF68Ic/7UDmHM8uMz6Aw "Ruby – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 98 bytes -5 bytes thanks to [@att](https://codegolf.stackexchange.com/users/81203/att). ``` Ordering[i=1;s=I^ToCharacterCode@#~Mod~11;0Union@@Accumulate@Partition[s,i,i++,{i,1},0]-i&/@s,-1]& ``` [Try it online!](https://tio.run/##NYyxCoMwGIRfJURwMaKZjSHFqUOpQzuFBIKm9YeqEGMW0Ve3Wuh9y303XG98Z3vjoTH7C5X73bXWwfCWUNJiKq/6MVadcabx1lVja0W03cZ2o7TInwOMgxCXppn7@WO8FbVxHvyxyokAgSQhCxC6klylEGdiIilV8V4f/15GKOXoJSOlUIwygRbMz2CCsA5/Tgtc88A0@/VDmNYscLzuXw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [J](http://jsoftware.com/), 44 bytes ``` 1+0{[:\:[:([:#@~.@,+/\)"2-@#\]\0j1^'>^<v'&i. ``` [Try it online!](https://tio.run/##Vcw9C8IwEIDhvb/iSMC0tE0/wCWkoSi4KA6ujYGqKdpBwUJEFP96jESR3nHLy/H0FlHSQcWAQAI5MHcphflmtbBFnD8aJlnDwobh@kXrJM5khMq0xnIr875QRChuyOREbRSsZxSW@g67dtAHaM/DTV8ZdBX9Ox5BZYjlM8MyclxGEaYjKgj0/niBAirogIjPEJ@mPhmhhOGKf2vpqzK/JSPAuHeunO0U@wY "J – Try It Online") *-3 after stealing a trick from ovs's APL answer. Explanation is similar to ovs's.* My other attempt used key rather than column sums for simulating the multiple robots: ``` 1+0{[:\:[:#@~.@,"2(#\|/#\)+/\/."#.0j1^'>^<v'&i. ``` [Answer] # BQN, 56 bytes ``` {1+⊑⍒((∾⟜-1∾≠𝕩)⊏˜">v<"⊐𝕩)⊸{≠⍷∾{+`0∾𝕩}¨𝕨⊔˜(≠𝕨)⥊↕𝕩}¨1+↕≠𝕩} ``` [Try It!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgezEr4oqR4o2SKCjiiL7in5wtMeKIvuKJoPCdlakp4oqPy5wiPnY8IuKKkPCdlakp4oq4e+KJoOKNt+KIvnsrYDDiiL7wnZWpfcKo8J2VqOKKlMucKOKJoPCdlagp4qWK4oaV8J2VqX3CqDEr4oaV4omg8J2VqX0KCkQg4oaQIOKAolNob3cgRgpEICI+Pj4+IgpEICJedl52XnZedl52IgpEICJ2Pl4+djxePCIKRCAidnY+XjxeXjx2PiI=) BQN is the Language of The Month for December! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` O%11sJµZı*Ż€ÄFQL)MḢ ``` A monadic Link accepting a list of characters which yields an integer, the optimal number of Santas. **[Try it online!](https://tio.run/##AS0A0v9qZWxsef//TyUxMXNKwrVaxLEqxbvigqzDhEZRTClN4bii////dj5ePnY8Xjw "Jelly – Try It Online")** [Answer] # [Clojure](https://clojure.org/), 259 bytes ``` (let[s(read-line)](print(first(reduce(fn[[a b][c d]](if(< b d)[c d][a b]))(for[i(range 1(inc(count s)))][i(count(set(mapcat #(reductions(fn[[x y]m](case m\^[x(dec y)]\>[(inc x)y]\v[x(inc y)]\<[(dec x)y]))[0 0]%)(for[j(range i)](take-nth i(drop j s))))))]))))) ``` [Try it online!](https://tio.run/##LY9BisMwDEWvIhgK0qLQ7ksv4qjg2spUmcQOtlOS02dit1oI/pf4enJjHJYk@46jFJMxifXnUYMQ45w0FOw15XL4fnGCfTDGwpONA8@M2uMNnuCp6TYhwj4mo5hs@BW4ogaHLi6hQCYiPiZNYZaCk52dLfDziS8aQ24nVth4YnQ2C0zdw6zoxcFG3N1NDYSVNu7eh19F9W@mrVSfyFzgwqcPyPAF0eOhYv/kHMoLFH2KMwwNqVK1vu/3Wv8 "Clojure – Try It Online") Ungolfed: ``` (let [s (read-line)] (print (first (reduce (fn [[a b] [c d]] (if (< b d) [c d] [a b])) (for [i (range 1 (inc (count s)))] [i (count (set (mapcat #(reductions (fn [[x y] m] (case m \^ [x (dec y)] \> [(inc x) y] \v [x (inc y)] \< [(dec x) y])) [0 0] %) (for [j (range i)] (take-nth i (drop j s))))))]))))) ``` Commented, slightly longer version using threading: ``` (let [s (read-line)] (->> (for [i (range 1 (inc (count s)))] ; Create a list of number of houses covered by 1..n (Robo-)Santas (n = length of instruction): [i (->> ; for example, for ">>>>>" => ([1 6] [2 4] [3 3] [4 3] [5 2]) (for [j (range i)] ; - split commands for i (Robo-)Santas: (take-nth i (drop j s))) ; for example, for "^v^v^v^v^v" with 2 (Robo-Santas) => ((\^ \^ \^ \^ \^) (\v \v \v \v \v)) (mapcat ; - provide a list of all houses covered with a command (splitted to commands for each (Robo)-Santa): #(reductions ; for example, for "^v^v^v^v^v" with 2 (Robo-Santas) => ([0 0] [0 -1] [0 -2] [0 -3] [0 -4] [0 -5] [0 0] [0 1] [0 2] [0 3] [0 4] [0 5]) (fn [[x y] m] ; - given a house of position [x y] and move command m: (case m \^ [x (dec y)] ; move to [x y-1] \> [(inc x) y] ; move to [x+1 y] \v [x (inc y)] ; move to [x y+1] \< [(dec x) y])) ; move to [x-1 y] [0 0] %)) ; - start from house [0 0] and work moves from there set ; - convert the list to a set to remove duplicate houses count)]) ; - count number of houses in the set (reduce ; From the list created above, pick the best option (fn [[a b] [c d]] ; for example, for ">>>>>", the list ([1 6] [2 4] [3 3] [4 3] [5 2]) => [1 6] (if (< b d) [c d] [a b]))) ; - compare number of houses, returning first if the number is same (less (Robo-)Santas is better) first ; Extract number of (Robo-)Santas from the best option print)) ``` [Answer] # JavaScript (ES6), 130 bytes Expects an array of characters. This is using `reduce()` ... because why not. ``` a=>a.reduce(r=>(n++,v=new Set(a.map(o=(c,i)=>o[i%=n]=~~o[i]+({'>':1,'<':-1,v:q=a.length}[c]||-q))).add(0).size)>m?(m=v,n):r,n=m=0) ``` [Try it online!](https://tio.run/##bczBasMwEATQe7/CBIp3sazEhV6MdvMRPRoLhKykLraU2I4KbZpfd11CevLMZQ6P@TDRjHZoT1PuQ@PmA82G2MjBNRfrYCAGn2UiknefyZubwMjenCAQWNEicajaZ/I13W7LqjP4TjktC5GqtMwLEcszGdk5f5zefypbX6/5GRGlaRrYoRzbL4fc76GnKDyWg/DU0w5nG/wYOie7cIQDVFLKDf9lUyMm92y3SfG04nR89I4X97LmImuOSqvH5eJeV90CldYq8v9fMf8C "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = array of characters a.reduce(r => // reduce a[] using r as the accumulator: ( // n++, // increment n v = new Set( // define v as the size of this set: a.map(o = (c, i) => // for each char. c at position c in a[]: o[i %= n] = // reduce i modulo n ~~o[i] + ( // coerce o[i] to an integer and add: { '>': 1, // +1 if c = '>' '<': -1, // -1 if c = '<' v: q = a.length // +a.length if c = 'v' }[c] // || -q // -a.length if c = '^' ) // ) // end of map() ) // end of Set() .add(0) // add the starting position 0 .size // get the final size of the set ) > m ? // if v is greater than m: (m = v, n) // update m to v and r to n : // else: r, // leave r unchanged n = m = 0 // start with r = n = m = 0 ) // end of reduce() ``` [Answer] # [R](https://www.r-project.org/), 134 bytes ``` function(v)which.max(Map(function(x)sum(unique(c(0,unlist(Map(function(i)cumsum(d[y==i]),y<-1:x))))|T),seq(d<-1i^(utf8ToInt(v)%%11)))) ``` [Try it online!](https://tio.run/##Zc5NC4JAEAbge79CDGEWLNogiFi9d@iUt2hhWQ0X2jXbDxX677YKBtrMbZ6XmXn3ZdVIprorU4bppH9YxY2oFDjUlIKXW8lauLAX/KBF2kqwStS2AA672Kqn0GYeEohbOeTyW5ck4o7ijmzwqUW@PhmKdVFD7ieCgjWPY1adlfEnowjjITL/CsJ0qBAF6wCvFkTd1KPvl@5SmjpCyaiH4I@9E0qJm9b3Xw "R – Try It Online") ]
[Question] [ My userid is 100664. In binary this is `11000100100111000`. An interesting property of this number is that it can be created entirely by concatenating strings which are repeated at least twice: ``` 11 000 100100 111 000 ``` The first few such numbers are \$3,7,10,12,15,24,28,31,36,40,42, 43, 45,48,51,53,54,56,58,60,63,80,87,96,99,103,112,115,117,120,122,124,127\$ (let me know if I've missed any as I worked these out by hand). Your challenge is to calculate these. (Leading zeros don't count, e.g. `9 = 001001` is not part of the sequence.) As with all [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenges, you may either: * Take a number \$n\$ and output the nth term * Take a number \$n\$ and output the first n terms * Take no input and output these forever [Here's a reference implementation courtesy of Bubbler](https://tio.run/##hVDNaoQwEL7nKQZ6SKYrEpVehDyJyBLZaLO1MUQPWei7u6NZLfRSQhj45vtj/GP5nFy1rm8@WLeI7fOikPR4ViKyPuhhBgVNZ52w2FR1@36HfgpgwToI2g1GlFkhJe7ofUMJqLBN2nyewiK@zEON@ru7aYi1GI0TEbNI/q/cnYqsM4N1e1zc3eLmlirYHmIjW6V4wdtDlvjIdBJRJImuv8U@JNYMNO0SM/eTFxIZJLnOII0SMzDupjj8AKc1@eXae4LEQSD01e5CSRou8LdiezIUjHZexGzOhqf6n3OkXsekGriuTw) # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! # Testcases These are 0-indexed. ``` 0 => 3 1 => 7 3 => 12 5 => 24 10 => 42 15 => 53 20 => 63 25 => 103 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` BŒṖŒɠṂ’ƊƇµ# ``` A full program that accepts a positive integer, \$n\$, from STDIN and prints a list of the first \$n\$ emanresu numbers. **[Try it online!](https://tio.run/##ASIA3f9qZWxsef//QsWS4bmWxZLJoOG5guKAmcaKxofCtSP//zMz "Jelly – Try It Online")** ### How? ``` BŒṖŒɠṂ’ƊƇµ# - Main Link: no arguments # - start with k=0 and count up, collecting the first n (from STDIN) k which are truthy under: µ - the monadic chain, f(k): B - convert (k) to binary ŒṖ - all partitions (of the binary representation of k) Ƈ - filter - keep those (partitions) which are truthy under: Ɗ - last three links as a monad, f(partition): Œɠ - run-lengths of equal elements (e.g. 101,101,1,1,1,0 -> 2,3,1) Ṃ - minimum ’ - decrement (vectorises) -> 0 is falsey, other numbers are truthy (a result of f(k) which is non-empty is truthy) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~78~~ 71 bytes -7 thanks to m90, wasif, and ovs ``` import re i=1 while[re.match('..((.+)\\2+)+$',bin(i))and print(i)]:i+=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEolSvT1pCrPCMzJzW6KFUvN7EkOUNDXU9PQ0NPWzMmxkhbU1tFXScpM08jU1MzMS9FoaAoM68EyIm1ytS2Nfz/HwA "Python 3 – Try It Online") I feel like manually setting the index isn't optimal but idk how to avoid it in this situation. Further optimizations: Since bin(i) always prepends 0b to our string, and match always checks from the start, we can remove the slicing from [2:] and instead embed that in the regex. By combining the match statement with an `and` for the print, it short circuits and only prints i if re.match returns something other than None. And by wrapping the and statement in a list, it forces it to always be evaluated as true in our while condition. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 56 bytes ``` {T`d`10`.1*$ ^0*$ 1$& /^((.+)\2+)+$/&*\(`1 01 +`10 011 1 ``` [Try it online!](https://tio.run/##K0otycxLNPz/vzokISXB0CBBz1BLhSvOAEgYqqhx6cdpaOhpa8YYaWtqq@iracVoJBhyGRhyaQOVAmlDLqBOAA "Retina – Try It Online") Link is to verbose version of code. Outputs the infinite sequence. Explanation: ``` { ``` Repeat forever. ``` T`d`10`.1*$ ``` Increment the current binary value. ``` ^0*$ 1$& ``` If it overflows, carry the `1`. ``` /^((.+)\2+)+$/& ``` Is this an Emanresu number? ``` *\(` ``` If so then print the result of the rest of the program but then restore the current binary value. ``` 1 01 +`10 011 1 ``` Convert from binary to decimal. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes ``` ℕ≜{ḃ~cḅ∋₁ᵐ&!} ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh7s6H3Ut/f@oZeqjzjnVD3c01yU/3NH6qKMbJLd1gppi7f//AA "Brachylog – Try It Online") [Generates](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) numbers infinitely. ``` ℕ≜ Choose a nonnegative integer. ḃ Its binary representation ~c can be partitioned such that ḃ if runs of equal partitions are grouped, ᵐ each group ∋₁ has a second element. { & } Output that integer ! once. ``` I had hoped to use `j` here, but it can't even get close. [Answer] # JavaScript, 63 bytes ``` for(n=1;;n++)/^((.+)\2+)+$/.test(n.toString(2))&&console.log(n) ``` [Try it online!](https://tio.run/##BcFRCoAgDADQy4RsjIz8CqRT9BuBiIkhW@jo@vbeE77QYyuvzt82xi0NeF@9ZyJcLgBLeDpCmharqSuwVTm0Fc7gEI2Jwl1qslUyMI7xAw) [Answer] # [Perl 5](https://www.perl.org/), 45 bytes ``` /^((.+)\2+)+$/&&say$.while$_=sprintf"%b",++$. ``` [Try it online!](https://tio.run/##K0gtyjH9/18/TkNDT1szxkhbU1tFX02tOLFSRa88IzMnVSXetrigKDOvJE1JNUlJR1tbRe///3/5BSWZ@XnF/3V9TfUMDAE "Perl 5 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 15 bytes *Saved 2 bytes thanks to @Dudecoinheringaahing* Takes an integer \$n\$ from STDIN and generates the first \$n\$ terms. This is probably twice as long as it should be... ``` BŒṖ‘ḄŒɠ€ỊẸ€ẠṆø# ``` [Try it online!](https://tio.run/##y0rNyan8/9/p6KSHO6c9apjxcEfL0UknFzxqWvNwd9fDXTtAjF0LHu5sO7xD@f9/YwMA "Jelly – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~16~~ 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ï├1mìsM`0°ö≈ ``` [Run and debug it](https://staxlang.xyz/#p=8bc3316d8d734d6030f894f7&i=) Prints the sequence forever. -4 bytes using the partitioning idea. [Answer] # [Japt](https://github.com/ETHproductions/japt), 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs the first `n` terms. It's *really* annoying me that the RegEx takes up nearly ¾ of this solution but I can't seem to come up with a shorter, non-RegEx based one :\ ``` Ȥè"^((.+)%2+)+$"}jU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yKToIl4oKC4rKSUyKykrJCJ9alU&input=MTA) ``` Ȥè"^((.+)%2+)+$"}jU :Implicit input of integer U È :Function taking an integer as argument ¤ : To binary string è : Count "^((.+)%2+)+$" : RegEx /^((.+)\2+)+$/ } :End function jU :Get the first U integers that return a truthy value ``` [Answer] # [R](https://www.r-project.org/), ~~85~~ 81 bytes ``` while(T<-T+1)grepl("^((.+)\\2+)+$",Reduce(paste0,T%/%2^(0:log2(T))%%2))&&print(T) ``` [Try it online!](https://tio.run/##DcdBCoAgEADAv0jKLlqZx@gV4TGEqMUEKTGj51tzm1zre4RIYKfWygF9phSBOYBO4rIYibJhaqb92QjSehfSyvKeGwd6jJc3YBE5N4hCpBzO8r/WDw "R – Try It Online") A regex-based solution. Prints values indefinitely. Thanks to @pajonk for saving 4 bytes! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞ʒb.œ2ìεγ€g2@P}à ``` Outputs the infinite sequence. [Try it online.](https://tio.run/##ASQA2/9vc2FiaWX//@KInsqSYi7FkzLDrM61zrPigqxnMkBQfcOg//8) **Explanation:** ``` ∞ # Push an infinite list of positive integers: [1,2,3,...] ʒ # Filter this list by: b # Convert the current integer to binary .œ # Get all partitions of this binary string 2ì # Prepend a 2 before each part (this is necessary because `γ` will # ignore leading 0s, and thus incorrectly group "1" and "01" together) ε # Map each partition to: γ # Group adjacent equivalent elements together €g # Get the length of each group 2@ # Check for each length if it's >= 2 P # Check if all are truthy (by taking the product) }à # After the map: check if any partition is truthy (by taking the max) # (after which the filtered list is output implicitly as result) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 23 bytes ``` λbvS∑`^((.+)\\2+)+$`r;ȯ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=r&code=%CE%BBbvS%E2%88%91%60%5E%28%28.%2B%29%5C%5C2%2B%29%2B%24%60r%3B%C8%AF&inputs=9&header=&footer=) A juicy port of JavaScript. Man I do love me some regex in golfing languages. Takes `n` and outputs the first n terms. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` ΠøṖ'ĠvḢA)ȯ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCLOoMO44bmWJ8SgduG4okEpyK8iLCIiLCIxMCJd) Port of Jelly. -2 bytes thanks to emanresu A and lyxal [Answer] # [Julia 1.0](http://julialang.org/), 65 bytes ``` !i=replace(bitstring(i+=1),r"((.+)\2+)"=>"")>""||println(i),!i;!1 ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/XzHTtii1ICcxOVUjKbOkuKQoMy9dI1Pb1lBTp0hJQ0NPWzPGSFtTydZOSUkTiGtqCoAqSnLyNDI1dRQzrRUN//8HAA "Julia 1.0 – Try It Online") ]
[Question] [ ### Input: * An integer `n` * Two equal-sized square matrices (with their width/height being a multiple of `n`) ### Output: One of two distinct values of your own choice, one being for truthy results and one for falsey results (so yes, `1/0` instead of `true/false` are valid outputs for languages like Java, even though [they're not considered official truthy/falsey values](https://codegolf.meta.stackexchange.com/a/2194/52210)). The truthy/falsey output indicates whether we can rearrange blocks of size `n by n` in one matrix to make it equal to the other matrix. ### Example: Input: ``` Matrix 1: 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 0 9 8 1 1 1 1 1 1 Matrix 2: 3 2 9 8 7 8 1 1 1 1 5 4 3 4 5 6 1 0 9 0 7 6 1 1 5 6 1 2 3 4 1 2 7 8 9 8 Integer n: 2 ``` Output: `truthy` **Why?** If we split the matrices in blocks of `2 by 2`, we can see that all blocks on one matrix can also be found in the other matrix: ``` Matrix 1: 1 2 | 3 4 | 5 6 7 8 | 9 0 | 1 2 --------------- 3 4 | 5 6 | 7 8 9 8 | 7 6 | 5 4 --------------- 3 2 | 1 0 | 9 8 1 1 | 1 1 | 1 1 Matrix 2: 3 2 | 9 8 | 7 8 1 1 | 1 1 | 5 4 --------------- 3 4 | 5 6 | 1 0 9 0 | 7 6 | 1 1 --------------- 5 6 | 1 2 | 3 4 1 2 | 7 8 | 9 8 ``` ## Challenge rules: * You can assume the matrices will only contain non-negative digits (range `[0,9]`) * You can assume the width/height of the matrices are equal, and a multiple of `n` * You can assume `n` will be in the range `[1, 50]`, and the width/height of the matrices are in the range `[1,100]`. * The individual blocks of `n by n` can only be used once to determine if the matrices are permutations of each other when split into blocks of `n by n`. * There can be multiple `n by n` blocks that are the same. * The `n by n` blocks will remain in the same orientation when checking if the two matrices are permutation of each other when split into blocks of `n by n`. ## 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 with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), 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 (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases: ``` Input: Matrix 1: Matrix 2: Integer: 1 2 3 4 5 6 3 2 9 8 7 8 2 7 8 9 0 1 2 1 1 1 1 5 4 3 4 5 6 7 8 3 4 5 6 1 0 9 8 7 6 5 4 9 0 7 6 1 1 3 2 1 0 9 8 5 6 1 2 3 4 1 1 1 1 1 1 1 2 7 8 9 8 Output: truthy Input: Matrix 1: Matrix 2: Integer: 1 2 3 4 5 6 3 2 9 8 7 8 1 7 8 9 0 1 2 1 1 1 1 5 4 3 4 5 6 7 8 3 4 5 6 1 0 9 8 7 6 5 4 9 0 7 6 1 1 3 2 1 0 9 8 5 6 1 2 3 4 1 1 1 1 1 1 1 2 7 8 9 8 Output: truthy Input: Matrix 1: Matrix 2: Integer: 1 2 3 4 5 6 3 2 9 8 7 8 3 7 8 9 0 1 2 1 1 1 1 5 4 3 4 5 6 7 8 3 4 5 6 1 0 9 8 7 6 5 4 9 0 7 6 1 1 3 2 1 0 9 8 5 6 1 2 3 4 1 1 1 1 1 1 1 2 7 8 9 8 Output: falsey Input: Matrix 1: Matrix 2: Integer: 1 2 3 4 1 2 3 4 4 2 3 4 5 2 3 4 5 3 4 5 6 3 4 5 6 4 5 6 7 4 5 6 7 Output: truthy Input: Matrix 1: Matrix 2: Integer: 1 2 3 4 3 4 3 4 2 2 3 4 5 4 5 4 5 3 4 5 6 1 2 5 6 4 5 6 7 2 3 6 6 Output: falsey Input: Matrix 1: Matrix 2: Integer: 1 2 2 3 1 3 4 1 1 Output: falsey Input: Matrix 1: Matrix 2: Integer: 0 8 1 Output: falsey Input: Matrix 1: Matrix 2: Integer: 1 2 3 4 1 2 1 2 2 5 6 7 8 5 6 5 6 9 0 0 9 0 9 9 0 4 3 2 1 2 1 4 3 Output: falsey Input: Matrix 1: Matrix 2: Integer: 1 2 1 2 9 5 1 2 2 3 4 3 4 7 7 3 4 8 3 9 5 1 2 8 3 6 1 7 7 3 4 6 1 Output: truthy Input: Matrix 1: Matrix 2: Integer: 1 0 2 0 0 3 1 1 1 0 0 3 2 1 1 1 1 1 1 2 0 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 Output: falsey ``` [Pastebin with matrices in `[[,]]` format.](https://pastebin.com/DPZaACL9) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~19~~ ~~18~~ 17 bytes -2 thanks to ngn. Anonymous tacit infix function. Takes `n` as left argument and list of two matrices as right argument. Requires zero-indexing (`⎕IO←0`). Incidentally, this function works on arrays of any number of dimensions. ``` ≡.{∧,⍵⊂⍨⊂0=⍺|⍳≢⍵} ``` [Try it online!](https://tio.run/##jVM9SwNBEO3zK7ZLM5HdvW/BysYIGjB2R4rDXEQIKiZFRG0Ugglc0MIfoI12FmJj6U/ZP3LO7G7MoblLOLjbnZ157@3Mu@S83@heJv2z40Y6Gqan3bSbq9lTs6XGDzxXk@eNK3X/Cir7VNNblb3hm2@p7OtaZR9q8oLxm7yHuSqbmbLp3fe7o8aPuGsfbOP7cKfZzuuH6WDIjpJBOmACmATmbNZre8nw4mQkqFwX7LZb@/U4FiDBARc88DsQBxBCBBwwijsbB4ziLsKzAHceuPpMYhbHbDoT8Pt0OnMu@ZeLagxKsWaOZ7gQU3NxzUV4EJu41qnrJBidIXFJ1mP2bvYra2JJzFkSqy1axVxg3so2Ib1t10IyrmybSI77j0aUt8O1mFRvMInHYBKPj6uSKxal@5W6jdKKsSCTGQfliBVcQTkXr@Lw1gEP1xlA0ZGcHKgbqP1YIUBov0pbb1pM7o203@gMMdZpdlStcfHnGLUhfiM9WvJwYExSohHzbD3mFdwe6gERpm/uuETjDw "APL (Dyalog Extended) – Try It Online") `≡.{`…`}` identical results of the following function applied to each matrix `⍵` with `n` as `⍺`?  `≢⍵` size of matrix  `⍳` indices 0…size–1  `⍺|` division remainder when divided by `n`  `⊂` enclose to use along all dimensions  `⍵⊂⍨` use that to partition\* the matrix into a matrix of submatrices   \* begins new partition when corresponding element is less than the previous; removes elements marked by zero  `,` ravel the matrix into a list of submatrices  `∧` sort ascending [Answer] # [Python 2](https://docs.python.org/2/), ~~108~~ 103 bytes ``` lambda s,*a:len(set(`sorted(sum([zip(*[iter(zip(*l))]*s)for l in zip(*[iter(m)]*s)],[]))`for m in a))<2 ``` [Try it online!](https://tio.run/##hVLLboMwELzzFRxttAfs8Kyaa2/ceqNIoQpRkYBEQA7tz9PdNQ8noqo4YM/Ozj7Gt@/x69rp6XL8mJqy/TyX7gBe@dJUnRiqUZyGaz9WZzHcW5H/1Dfh5fVY9YKPjZSFN8jLtXcbt@5cK95ypIC8kPJEhJYIpZSvesrUMc8VaDhAACFEyIohgRR8QBRvMw6I4i3FWIy3EAKOaWT5yKaYgvUrCifTKEwEk2ITlmQjjAIs7LMwJUNucG6K8zSYphIUdm593Y3uRWjIFGRauvDe36sVVvvwYYXfymaoHMeeHIvMG9gaw9M8@TZNMJMpYMgkYMgkEOHJ6jDgmuq5Ff1XK6b4Ug4FzdJsSbWb66854f/kbWbbV5985NHY1UVQscV6JptJyfCUXaMYJuy78lxze0@meoL/lJdIZsfbnhGcyQhabyDhhZBA9LiUx5cw/QI "Python 2 – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~94 68~~ 63 bytes ``` {[eqv] map *.rotor($^a).map({[Z] $_}).flat.rotor($a²).sort,@_} ``` [Try it online!](https://tio.run/##nVLLaoRAELz7FX1YgoZG1PVJCOQ7MkzEw3raxV1XAov4U/mE/Jjph67DkkOIHpyZ6qrqnvJ86I/5fLrBUwuvMI/mcPm0cGrO8Bz23dD1/u6jCUI68EfzbmFXT0HYHpthRZvvryC8dv2Ab/U0t10PCca4h9EDuDY3aP1djcaYGBPcY4oZ5hZNgSVWGFFlQrvlHOmUdhVhBe0yTAVjvYiqGYvx/lqLZKGPkTIlumWrhMqTjMhHIs8SaPRcWhNegtpaaa0NvMnzdIZ09domofJlos2CVsskTnd/ZtjgZfVL8B9Geg/pwmFcOayjHNbJaeVaxYuVij/IEUGv06WAUCIqpYKMkDvw0LabacQZSluS6OajBG0gk9i5Uw68krwYI9KvNtvvo4YlfSuZmVMt3Nsx1EO2EAhwAi9lRhbJZc75Bw "Perl 6 – Try It Online") Anonymous code block that takes input as `size, [matrix1, matrix2]` and returns a boolean `True/False`. There might be a more efficient way of splitting the matrix into chunks than `rotor`. ### Explanation: ``` { } # Anonymous code block map ,@_ # For both matrices *.rotor($^a) # Split the matrix into N sized chunks .map({[Z] $_}) # Then zip each of those chunks together .flat # Flatten the resulting list .rotor($a²) # Then split into the NxN lists .sort # And sort them [eqv] # And then check if the lists are equivalent ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` εε²ô}ø˜²ô²ô{]Ë ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3NZzWw9tOryl9vCO03NADBCujj3c/f9/dHS0oY6BjhEQG@gYx@oAeXAI5BnpwCGQZ6wDhUC2iQ4cAnmmOnAYC@RCTYGZCTKdQjNjuYwA "05AB1E – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ż⁹/ẎsṢʋ€E ``` **[Try it online!](https://tio.run/##y0rNyan8///onkeNO/Uf7uorfrhz0anuR01rXP///x8dHW2oo2Cko2Cso2Cio2Cqo2AWy6WgE22uo2Cho2Cpo2CgowBSABZEqNFRACkAC1qCVZqDBYFSJjCVRmCNBmBDICoNwSIIFBvLpRMNVQo3BVMpsqFw60FGw6w3gFkPNhQkCFcD9RjMTCOIFVA3xcb@NwIA "Jelly – Try It Online")** (or [with pre-processing](https://tio.run/##y0rNyan8///onkeNO/Uf7uorfrhz0anuR01rXP8/3L3l4Y5NQKb/sXYgGXZopeHD3d0Pd646tO7oJA@gSNShJYeX//9vqGCkYKxgomCqYKYAAsZAvqWChYI5EIOAEReIZalgoABSCQKGUGiqYMIF0wlTDeMbKhhwQUwxA6kDy4HMMAfLGXKBbAGqAdsEAhA9YJdwGSogIMQ@IwWIGywA "Jelly – Try It Online") for easier copy & paste from the test cases) A dyadic Link accepting a list of the two matrices (as lists of lists) on the left and the integer on the right which yields `1` or `0` for truthy or falsey respectively. ### How? ``` ż⁹/ẎsṢʋ€E - Link: [M1, M2]; N € - for each of [M1, M2]: ʋ - last four links as a dyad (i.e. f(M, N)): ⁹ - (chain's right argument, N) ⁹/ - N-wise-reduce with: ż - zip together Ẏ - tighten s - split into chunks of length N Ṣ - sort E - equal? ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 18 bytes ``` ®mòV yòV rc n qÃr¥ ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=rm3yViB58lYgcmMgbiBxw3Kl&input=W1tbMSAyIDMgNCA1IDZdCls3IDggOSAwIDEgMl0KWzMgNCA1IDYgNyA4XQpbOSA4IDcgNiA1IDRdClszIDIgMSAwIDkgOF0KWzEgMSAxIDEgMSAxXV0KW1szIDIgOSA4IDcgOF0KWzEgMSAxIDEgNSA0XQpbMyA0IDUgNiAxIDBdCls5IDAgNyA2IDEgMV0KWzUgNiAxIDIgMyA0XQpbMSAyIDcgOCA5IDhdXV0KMgotUQ==) Explanation: ``` ® à #Apply this to each of the input matrices: mòV # Split each row into groups of n yòV # Split each column into groups of n rc # Flatten into a list of nxn submatrices n # Sort that list q # Turn it into a string r¥ #Return true if both matrices had identical results ``` The "Turn it into a string" step is necessary because Japt [doesn't compare arrays by value](https://ethproductions.github.io/japt/?v=1.4.6&code=WzEsMl09PVsxLDJd&input=) and the builtin to work around that [doesn't work for multidimensional arrays](https://ethproductions.github.io/japt/?v=1.4.6&code=W1sxLDJdLFszLDRdXWVbWzEsMl0sWzMsNF1d&input=). [Answer] # TSQL, 164 bytes Populating a table variable in order to have input, this creating input and inserting data has not been included in the byte count. Only the actual query to extract the data. Golfed(not including test table - it can be found in the ungolfed version): ``` SELECT iif(exists(SELECT*FROM(SELECT string_agg(v,'')within group(order by x,y)s,m FROM @t GROUP BY x/@,y/@,m)x GROUP BY s HAVING max(m)=min(m)or sum(m-.5)<>0),0,1) ``` Ungolfed: ``` -- test data DECLARE @ INT = 2 -- x = x-position of the input -- y = y-position of the input -- v = value -- m = matrix(0 or 1) DECLARE @t table(x int, y int, v int, m int) --insert first matrix values INSERT @t values (0,0,1,0),(0,1,2,0),(0,2,1,0),(0,3,2,0), (1,0,3,0),(1,1,4,0),(1,2,3,0),(1,3,4,0), (2,0,8,0),(2,1,3,0),(2,2,9,0),(2,3,5,0), (3,0,6,0),(3,1,1,0),(3,2,7,0),(3,3,7,0) INSERT @t values (0,0,9,1),(0,1,5,1),(0,2,1,1),(0,3,2,1), (1,0,7,1),(1,1,7,1),(1,2,3,1),(1,3,4,1), (2,0,1,1),(2,1,2,1),(2,2,8,1),(2,3,3,1), (3,0,3,1),(3,1,4,1),(3,2,6,1),(3,3,1,1) -- query SELECT iif(exists ( SELECT * FROM ( SELECT string_agg(v,'')within group(order by x,y)s,m FROM @t GROUP BY x/@,y/@,m ) x GROUP BY s HAVING max(m)=min(m)or sum(m-.5)<>0 ),0,1) ``` **[Try it out](https://data.stackexchange.com/stackoverflow/query/965629/matrix-jigsaw-puzzles)** [Answer] # JavaScript (ES6), 88 bytes ``` (n,a,b)=>(g=a=>a.map((r,y)=>r.map((v,x)=>o[y/n<<7|x/n]+=[v]),o=[])&&o.sort()+o)(a)==g(b) ``` [Try it online!](https://tio.run/##3VPbasJAEH3vVwQKuotTzcXciutX9C3sw2qjtNisJCIK/fd0ZjfGtNZU6JvMQzK3M3OGs@9qr6pl@bbdPRX6Na9XomYFKFhwMWdrocRcjT/UlrESjhgqrbOHAzo6O06K2Sz@PEwKORLZXnLQIpN8MNDjSpc7xkeaM8WFWLMFr5e6qPQmH2/0mg1f8mrnLFWVO4@e8@wMnZGzYj44WeaBDwFMIYRIQhZDAim4gFH0mjhgFL0UczF6IUxNzscqF6sp50FrUhIspW1DN31qtbDYbmBdA0utkNm4Wcn0@WBXSqTk/OEaJ7/l5N0Np6DlFNwNp2nLadrhhAANt/NQ/Gs42T1vLO2ZHf6q@1tmU9iWUtiWUrstpfYI//pmRxf6tNMsPiLY2/dixN8xXNvbf@/kGueuWlxShyFntHK@t10zNFIipiSi1GiBcljeOzu9nH1Wq90iwW9qzkliik/3xlBTiqGOwhJzJ2qP/riV5/6Y7WI78Qx@vAGi0poBb8zcozVzhtZOF/LMw7KgvnmM/wLlvP4C "JavaScript (Node.js) – Try It Online") ### How? This code is: * extracting all sub-matrices in each input matrix as a concatenation of cells * sorting the sub-matrices in lexicographical order * testing whether the result is the same for both input matrices It is taking advantage of the limits described in the challenge: * A matrix consists of single digits, so we can just concatenate all cells of a sub-matrix without any separator and still get a unique representation of it (e.g. `[[1,2],[3,4]]` can be stored as `"1234"`). * The width of the input matrices is less than or equal to \$100\$. To convert the coordinates \$(x,y)\$ in an input matrix into a unique slot index \$I\$ in our storage area, we can do: $$I=\left\lfloor\frac{y}{n}\right\rfloor\times128+\left\lfloor\frac{x}{n}\right\rfloor$$ or as JS code: `y / n << 7 | x << n` ### Commented ``` (n, a, b) => // n, a, b = input variables (integer, matrix 1, matrix 2) (g = a => // g = helper function taking one of the two matrices a.map((r, y) => // for each row r[] at position y in a[]: r.map((v, x) => // for each value v at position x in r[]: o[ // update o[]: y / n << 7 | // the position of the slot is computed by taking advantage x / n // of the limit on the matrix width (see above) ] += [v] // coerce v to a string and append it to o[slot] // all slots are initially undefined, so all resulting strings // are going to start with "undefined", which is harmless ), // end of inner map() o = [] // start with o = empty array ) && // end of outer map() o.sort() + o // sort o[] and coerce it to a string by concatenating it with itself )(a) == g(b) // test whether g(a) is equal to g(b) ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 217 bytes ``` (n,a,b)->{java.util.Arrays A=null;int l=a.length,x=l/n,j=0,z;var c=new String[x*x];A.fill(c,"");var d=c.clone();for(;j<l*l;d[z]+=b[j/l][j++%l])c[z=j/l/n+j%l/n*x]+=a[j/l][j%l];A.sort(c);A.sort(d);return A.equals(c,d);} ``` [Try it online!](https://tio.run/##vVRLb6MwEL73V1hIlaA41OaNKJVy2dueekQcDIEW1pgsmG7aKr89OzakXfWhvXWk@DHzzXwzQzwde2Sbbvfr1Pb7YZSog7szy5Y7V@nFB10zi0q2g1DGirNpQj9ZK14uEGqFrMeGVTX6gdQdoXIYeM0EakywIYFhzYu8YOdDaaWAO8Jvkky2FTg2KDuZAjNcWpvblzfa7TiypwltMzFznqpwPGMOr8W9fMCHjF8L3GUEP6ePbERVJuo/6E6OrbjPD1eHIt06Tcu5WWHDsDRkl1VOxQdRm1baDKOZdjf8iqe7/LmwszLvrnmRd7Z9yQuryp8zuF8Lu7uEFcLZGVsRYIfYE7TIrKzzaWelYy3nUaCtU/@eGZ@AGJTHkyp3P5ccSl0rfhzaHeqhg@aaboHYeD9ZawdlPUnTxcigrucHIY7ihFAXq3MU4ySOwsDHnktJEmOqxQCw54JlUSgzgCnBCYlCSjGcIRSmLoSKDf0BVhr6PTTe99D4Kw1WVNoLKxrjC/W/ru7Xrp4Paj8ANXVB7Xph@EkPwUeBXQ@S/mAmyhR/Trj0gZAE@9CGJVcIF4TARZKEYJf63ieumhL8Yy8JcEgjnWsSgDqKdHtiDwAh/ehKXEK8tdnY1YI9LdjXggMtOhdKFdgl/wW/f9f6X65Jl0Gwvk3EXk@l9W5mjPU0c4ky1DgNDASI1JvMWvbSWuu4e5pk3TvDLJ09hJFcmIvf@wTWgaO9V8bXN6bGwQGIJmfa81aaBj636ezVg1VNFHU/rEMH9AtITQ9VVQsgksJ2g84YuNn2mQahPm8LAB1gc6oHNk6m5fRsb1ab22rjx5YjBz3mzJX@qNd1lPRLRcfTXw "Java (JDK) – Try It Online") ## Explanation The idea is to pick each small cell as a string, which is comparable, and then to sort those strings and compare them in order. ``` (n,a,b)->{ java.util.Arrays A=null; // Shortcut A for the several java.util.Arrays that'll come int l=a.length,x=l/n,i=0,j,z; // Variable declarations var c=new String[x*x]; // Declare the small squares list A.fill(c,""); // Fill the lists of small squares with the empty string. var d=c.clone(); // Make a copy of the list, for the second matrix for(;i<l;i++) for(j=0;j<l;d[z]+=b[i][j++]) // For each matrix cell c[z=i/n+j/n*x]+=a[i][j]; // Fill the small square with the value, string-wise A.sort(c);A.sort(d); // Sort both small squares list return A.equals(c,d); // Return true if they're equal, false otherwise. } ``` Note: some lines are obsolete. ## Credits * -12 bytes thanks to Kevin Cruijssen! * -4 bytes thanks to ceilingcat. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~54~~ 49 bytes ``` 1FθF⪪ιηF÷L§κ⁰η⊞υEκ§⪪μηλW∧υ⊟υ¿№✂υ⁰⊘⊕Lυ¹ι≔Φυ⁻⌕υιλυ⎚ ``` [Try it online!](https://tio.run/##TU7fa4MwEH7vX3H0KYEbqGvXlj6VjrHCBkIfxQfRtB5No9Po9t@7S2LHIiHe9@u@si66sin0NKUdGSuW8VLuF5emA/Elwb/nVpMVhFDLGTkZ@0ojVUp8KHO1tTjYk6nUj7ghRFIGZTr0tRgQPovW4Q9JSLs7DYKWkrd916QViIOpnD5tWjEwDnQBcWwGLnXWVCrHRQjvhR5VxRXKTt2Vsfw/l3AmhJgvsfvQ93Q14o20VZ3vQWboeQ5bKGxHGOQelO4VHLUqOiH305TxiTHBZ1zhGl9yzDa4xR1GyChPM46M8rRjbsPTGleeS1gVsdpxMf59eY4LgMwLguW/4GEOwRzggyMf7MyYBdyX8r4EQ6lt7pOTfHoa9S8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of equal-sized two-dimensional arrays. Outputs 1 on success, nothing on failure. Explanation: ``` 1 ``` Assume success. ``` Fθ ``` Loop over the arrays. ``` F⪪ιη ``` Divide the array into `n`-sized row chunks. ``` F÷L§κ⁰η ``` Loop over each column chunk. ``` ⊞υEκ§⪪μηλ ``` Extract the column chunk for each row of the row chunk and save the resulting submatrix in a list. ``` W∧υ⊟υ ``` While the list is nonempty, remove the last chunk of the list, which under normal circumstances comes from the second array. ``` ¿№✂υ⁰⊘⊕Lυ¹ι ``` Count the number of occurrences of that chunk in the first half of the list, which under normal circumstances contains the remaining chunks from the first array. ``` ≔Φυ⁻⌕υιλυ ``` If nonzero then remove the first occurrence of that chunk from the list. ``` ⎚ ``` If zero then clear the output, making it falsy. [Answer] # [J](http://jsoftware.com/), 55 bytes ``` [:-:/[([:/:~([*-@[)]\,@])"3(((;])@(#@]$1{.~[),;.1])&>]) ``` [Try it online!](https://tio.run/##ZU/LTsMwELz7K0alojZK0qRx08RRUSQkTj1xNT4kiApx4QOQ@uth1w9ChC0/ZndnZ@dz3hS7K84GO2QoYejkBZ5eLs@zNbnZW2nN3tykfcgHq9xrNji1qaWUvVODvBvctvoublZlfVE5df/o1KwExHg2DRpsUeGAGhpHQie06Ejgf6yltyGsKX6gfOlj1bLFlBpyQSAsBYEYGgZy6RuGXPMryG8UFOL97eOL8BVjPwVQRxCQ9mgU7IWA/mMmjZ80oxUeMlbWcSLtZzt6Jtcwk3ysxcWIlUSS4dPS3UUTJ9q0xLSUd7E3p5JDpvCfKCud@Qc "J – Try It Online") A horrible solution, just made it work - I have no power to golf it... [Answer] ## Haskell, ~~74~~ 73 bytes ``` import Data.Lists i#m|c<-chunksOf i=c.transpose=<<c m (m!n)i=i#m\\i#n==[] ``` Note: TIO hasn't installed `Data.Lists`, so I'm using `Data.List` instead an add the missing function `chunksOf`: [Try it online!](https://tio.run/##3VNNi8JADL3PrxhxDwpZaetXu9jbHhf2B4xlKVVx0E5L24U97H/vJplaxRaUxZMGdCbJy0vim31cHrbHY13rNM@KSr7HVTz50GUl9DD9TVavyf7bHMrPndRhMqmK2JR5Vm7D1SqRqRilAzPWIaau13powlBFdQv4kiqSIX6J1mXkT4muKj5s7flNXsRGmyLL2T8WYod5owEe0lgbPG8yIWVeaFPJF7mTSrngwRRmMIdFBGoJPgTgAHrx1vgBvXgLMLbE2xxmHPMwy8FsirnQWhQhw/mjONNiLzNPVSwDVmIGhxmoCijr5@4Y54Htzr9i8MTTjeQ@30hTIftnQlQz25kJT81MnT7/g5qJh1BThkVRhkVRJYuiSgs8dcXZJbd0HQIsYXd/Sw5OB3qvgpp/7KQVh7TBA7FSerdt@52zpmhQUlPASqAYIu95j2ep2iZ8/A14gySfZc@2MdqgMHohL5@XRJUWnYZ7qB2E0JTTK/1T961xwcZ4G63x5K317Mfl92Xre/wmH1ffq/8A "Haskell – Try It Online") ``` i#m= -- function '#' makes a list of all transposed jigsaw blocks of matrix 'm' -- of size 'i' c<-chunksOf i -- define helper function 'c' that splits it's argument into -- chunks of site 'i' c m -- split the matrix into chunks of size 'i' =<< -- for each chunk transpose -- transpose c. -- and split into chunks of size 'i', again -- flatten one level of nesting ('=<<' is concatMap) (m!n)i= -- main function i#m\\i#n -- remove every element of i#n from i#m ==[] -- and check if it results in an empty list ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 178 bytes ``` (a,b,n)=>{string[]s(int[][]c){int i=0,l=a.Length,m=l/n;var r=new string[m*m];for(;i<l*l;)r[i/l/n*m+i%l/n]+=c[i/l][i++%l];Array.Sort(r);return r;}return s(a).SequenceEqual(s(b));} ``` [Try it online!](https://tio.run/##hZJda4MwFIbv/RXeFGJ7Vj/7RWphF9vVLga9FBlWbBfQSKNujOJvd0lNq@lqh2D09STv855jXDzFBWleKxqvCS2DMAiht8Iuz9PN3m9QBDughr85FSUj9BCEBZJ1sXHiTzrxLUj9aPqW0EP5CZmfmhR/RUxnPk2@dbktG2ch3ucMYbJOxyk2WEBMXjnOJmTE13Dix0IJAzKZjNIQPzMW/Uy3OSsRMzBLyopRneFaPhUoMqbb5FglNE5ejlWUogLtDAPXDdZM09QkpJ7ZH7bu6wJFSidNvPHVBgdc8GAG8xou4gKWsAIL@MdOlFXAP3biilcuuDgDr1/p8K0WP6JXacP1qrUa99mcATZxTmtw55wbx5aNu/bZrDObcLyKbdU5c/9MB9rMyzPbOx9XifZI9A0EIDi8q3dk@77sClkZgPPfADoYOY8/4TpBzkFto/OgjZ7qIPYrDoJBcRAMcy4ozXBEPHHzlNRSlj1SUruPUisB@Us/jDsYhpMp/0K78QrjChj3MhkFxhuEsdROeoPmN3@HJ8w8adb8Ag "C# (Visual C# Interactive Compiler) – Try It Online") -1 thanks to @KevinCruijssen! -8 thanks to @ceilingcat! Less golfed code: ``` // anonymous function // a and b are 2d jagged arrays // n is the size of the sub matrix (a,b,n)=>{ // helper function that translates // the sub matrices into strings // of digits. string[]s(int[][]c){ // i and j are loop counters int i=0,j, // l is the size of a side of a matrix l=a.Length, // m is the number of sub matrices // per side of a matrix m=l/n; // the concatenated digits are // stored in a single dimension // array var r=new string[m*m]; // flattened loop builds up // the digit strings for(;i<l*l;) r[i/l/n*m+i%l/n]+=c[i/l][i++%l]; // The resulting array is // sorted before it is returned for // ease of comparison. Array.Sort(r); return r; } return s(a).SequenceEqual(s(b)); } ``` [Answer] # [PHP](https://php.net/), ~~186~~ ~~163~~ 162 bytes ``` function($a,$b,$n){$f=function($j,$n){foreach($j as$x=>$r)foreach($r as$y=>$v)$o[count($j)*($x/$n|0)+$y/$n|0].=$v;sort($o);return$o;};return$f($a,$n)==$f($b,$n);} ``` [Try it online!](https://tio.run/##pVTbjpswEH0uX@EHP@DWagzhKkr7IQhFNAvNrrKADES7avfb05mxA2hbdZOt/MB45pyZMx6b/tCfv3zrDz2rte70Ttd9p8f79oerRMb11O7GehjzczO1@/G@a11eSf5d8lb85E2@eB/I1XS6rvYH2LJq4E/5V67F7NPoewbfSfCu2HdTOwJQfHT504a3v5T4xJ/JKD/n/JQNoMPlnch0PU665V32cjEbUtGKPEeT1GQv58xxNhsGkll1PDKUPTgOHz2Ws8L5UBSe9OVWBjKUUSmLWCYylUqCF3bWL8ELuxRiMexCGVDMB5QCNMY8Oa@ylJgX44axjl@4Ji/wKa@ivMiVhfGTJuL50mhKytIpM1AevFIOKNvBkhksq9yquRJrKoTvqYB@g0W/wSLfYJEfgWUrRKsKJqfNAjhzWhdkTEgGIWUh80Ekf8pcD0vhcEgOjWp1EKZoSKNEcTjElEaBMcBfKqTrCsuVMLUS@KbUJg4sng8CfBYLvtUYE2oN@dHSnqeWEgpAKHr76j6hrHlRCruouXlRS/Oa2/XolpqsPt3s/8qKsvFBDYduOt4x8/TYqKeawZPGN@Y4p0rv7qbH3mXzrwLM0YMRSvpCdeYzwfLcMEV2Hcd7B2drOE11HP5FCiwpIFJwVaHQcsJ1Q28ViiwpWnf0Fim2pPgWUmJJyS3yUktKbxmSupy4@lup828 "PHP – Try It Online") Like all good challenges, I started off thinking this was fairly easy and it threw me some curves. Nicely done @Kevin Cruijssen! Chunks the matrix into strings containing the values for each block. Arrays are then sorted and compared for equality. Ungolfed: ``` function jigsaw_chunk( $j, $n ) { foreach( $j as $x => $r ) { foreach( $r as $y => $v ) { $o[ count( $j ) * floor( $x/$n ) + floor( $y/$n )] .= $v; } } sort( $o ); return $o; } function jigsaw_test( $a, $b, $n ) { return jigsaw_chunk( $a, $n ) == jigsaw_chunk( $b, $n ); } // Test 6 var_dump( jigsaw_test( [[1,2],[3,4]], [[2,3],[1,1]], 1 ) ); ``` Output ``` bool(false) ``` [Answer] # [Red](http://www.red-lang.org), ~~148~~ ~~147~~ 142 bytes ``` func[a b n][g: func[m][ sort collect[loop k:(length? m)/ n[i: 0 loop k[keep/only collect[loop n[keep take/part m/(i: i + 1) n]]]]]](g a)= g b] ``` [Try it online!](https://tio.run/##5VK7coMwEOz1FVvCpOBh/GLGk39Iq1GBsSAMQjCEFPl6ckgyMk6bzlJ1t7e7txqN8jZ/yBsXrMrn6luXvMAVWvA6hyk7wdlXP04oe6VkOXHV9wPaPFBS19PnO7owguZNjphZiLdSDlGv1Q/bcLQB2FS0MhoKUuyigGgN3pCEZGlOUKMIL6hxFfMwNnpCBQ4GOjxBih0y7HEQtnPECWfEIMR1HA5CXOdMM0fq7JGtMykxYmLeZxKsVzAB7ucs@3nuUcv6kd7qFxs/o2U6Fje7C5/E7n5a/FLGXiZr8kJZdw9ZN7ICLroLLlzpMq7wXZ1q8R8S2Z@FPIxnwa3dVn27jn@ABffcRdxzF93DUtGHn38B "Red – Try It Online") ]
[Question] [ The challenge is to write codegolf for the [Hafnian of a matrix](https://en.wikipedia.org/wiki/Hafnian). The Hafnian of an \$2n \times 2n\$ symmetric matrix \$A\$ is defined as: $$\operatorname{haf}(A) = \frac 1 {n!2^n} \sum\_{\sigma \in S\_{2n}} \prod^n\_{j=1} A\_{\sigma(2j-1),\sigma(2j)}$$ Here \$S\_{2n}\$ represents the set of all permutations of the integers from \$1\$ to \$2n\$, that is \$[1, 2n]\$. The Wikipedia link talks about adjacency matrices but your code should work for any real valued symmetric input matrices. For those interested in applications of the Hafnian, the [mathoverflow](https://mathoverflow.net/questions/273324/applications-of-hafnians/273325) link discusses some more. Your code can take input however it wishes and give output in any sensible format but please include in your answer a full worked example including clear instructions for how to supply input to your code. The input matrix is always square and will be at most 16 by 16. There is no need to be able to handle the empty matrix or matrices of odd dimension. ## Reference implementation Here is some example python code from Mr. Xcoder. ``` from itertools import permutations from math import factorial def hafnian(matrix): my_sum = 0 n = len(matrix) // 2 for sigma in permutations(range(n*2)): prod = 1 for j in range(n): prod *= matrix[sigma[2*j]][sigma[2*j+1]] my_sum += prod return my_sum / (factorial(n) * 2 ** n) print(hafnian([[0, 4.5], [4.5, 0]])) 4.5 print(hafnian([[0, 4.7, 4.6, 4.5], [4.7, 0, 2.1, 0.4], [4.6, 2.1, 0, 1.2], [4.5, 0.4, 1.2, 0]]) 16.93 print(hafnian([[1.3, 4.1, 1.2, 0.0, 0.9, 4.4], [4.1, 4.2, 2.7, 1.2, 0.4, 1.7], [1.2, 2.7, 4.9, 4.7, 4.0, 3.7], [0.0, 1.2, 4.7, 2.2, 3.3, 1.8], [0.9, 0.4, 4.0, 3.3, 0.5, 4.4], [4.4, 1.7, 3.7, 1.8, 4.4, 3.2]]) 262.458 ``` --- The wiki page has now (March 2 2018) been updated by ShreevatsaR to include a different way of calculating the Hafnian. It would be very interesting to see this golfed. [Answer] # [R](https://www.r-project.org/), ~~150~~ ~~142~~ ~~127~~ 119 bytes ``` function(A,N=nrow(A),k=1:(N/2)*2)sum(apply(gtools::permutations(N,N),1,function(r)prod(A[cbind(r[k-1],r[k])])))/prod(k) ``` [Try it online!](https://tio.run/##PY6xDoIwGIR3n8Lx/82P2BKjaWTgBTq5EQYoYgjQNqVEefpaHBguXy6Xu5wL3fGRhG7RyvdGQ0Ey1858oEAaciZAphxPHOdlgtracYW3N2achbAvNy2@3lozSJJIjPYZh9aZFopSNb1uwZVDwiqKqLBCxPSfDhg6mGrv@i8oyOhyvkbdKEPixBEPe8rEnbZXeYQyY0SzbvaJGH4 "R – Try It Online") Uses the same trick I discovered golfing down [this answer](https://codegolf.stackexchange.com/a/156888/67312) to index the matrix `P`, and [@Vlo](https://codegolf.stackexchange.com/users/30693/vlo) suggested an approach to entirely remove the `for` loop for -6 bytes! To create a new test case, you can do `matrix(c(values,separated,by,commas,going,across,rows),nrow=2n,ncol=2n,byrow=T)`. Explanation: (the code is the same; it uses an `apply` rather than a `for` loop but the logic is otherwise identical). ``` function(A){ N <- nrow(A) #N = 2*n k <- 1:(N/2) * 2 #k = c(2,4,...,N) -- aka 2*j in the formula P <- gtools::permutations(N,N) #all N-length permutations of 1:N for(i in 1:nrow(P)) F <- F + prod(A[cbind(P[i,k-1],P[i,k])]) # takes the product of all A_sigma(2j-1)sigma(2j) for fixed i and adds it to F (initialized to 0) F / prod(k) #return value; prod(k) == n! * 2^n } ``` [Answer] # [Pyth](https://pyth.readthedocs.io), 24 bytes ``` sm*Fmc@@Qhkek2d{mScd2.pU ``` **[Try it here!](http://pyth.herokuapp.com/?code=sm%2aFmc%40%40Qhkek2d%7BmScd2.pU&input=%5B%5B0%2C+4.7%2C+4.6%2C+4.5%5D%2C+%5B4.7%2C+0%2C+2.1%2C+0.4%5D%2C+%5B4.6%2C+2.1%2C+0%2C+1.2%5D%2C+%5B4.5%2C+0.4%2C+1.2%2C+0%5D%5D&debug=0)** --- ### Old version, 35 bytes ``` *c1**FK/lQ2^2Ksm*Fm@@Q@[[email protected]](/cdn-cgi/l/email-protection) ``` [Try it here!](http://pyth.herokuapp.com/?code=%2ac1%2a%2aFK%2FlQ2%5E2Ksm%2aFm%40%40Q%40dtyk%40dykK.pU&input=%5B%5B3%2C0.7%5D%2C%5B0.5%2C3%5D%5D&debug=0) [Answer] # [Stax](https://github.com/tomtheisen/stax), 23 22 19 17 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü;Y╙◘▌Φq↓ê²╧▐å↑┌C ``` [Run and debug it online](https://staxlang.xyz/#c=%C3%BC%3BY%E2%95%99%E2%97%98%E2%96%8C%CE%A6q%E2%86%93%C3%AA%C2%B2%E2%95%A7%E2%96%90%C3%A5%E2%86%91%E2%94%8CC&i=%5B%5B3.0%2C0.7%5D%2C%5B0.5%2C3.0%5D%5D%0A%5B%5B1.0%2C2.0%2C3.0%2C4.0%2C5.0%2C6.0%2C7.0%2C8.0%5D%2C%5B1.0%2C2.0%2C3.0%2C4.0%2C5.0%2C6.0%2C7.0%2C8.0%5D%2C%5B1.0%2C2.0%2C3.0%2C4.0%2C5.0%2C6.0%2C7.0%2C8.0%5D%2C%5B1.0%2C2.0%2C3.0%2C4.0%2C5.0%2C6.0%2C7.0%2C8.0%5D%2C+%5B1.0%2C2.0%2C3.0%2C4.0%2C5.0%2C6.0%2C7.0%2C8.0%5D%2C%5B1.0%2C2.0%2C3.0%2C4.0%2C5.0%2C6.0%2C7.0%2C8.0%5D%2C%5B1.0%2C2.0%2C3.0%2C4.0%2C5.0%2C6.0%2C7.0%2C8.0%5D%2C%5B1.0%2C2.0%2C3.0%2C4.0%2C5.0%2C6.0%2C7.0%2C8.0%5D%5D&a=1&m=2) The corresponding ascii representation of the same program is this. ``` %r|TF2/{xsE@i^H/m:*+ ``` The program suffers from some floating point rounding error. In particular, it reports `33673.5000000011` instead of `33673.5`. But I think the accuracy is acceptable given that this program operates on floating point values. It's also very slow, taking almost a minute for the example inputs on this machine. ``` % get size of matrix r|T get all permutations of [0 ... size-1] F for each, execute the rest of the program 2/ get consecutive pairs { m map each pair... xsE@ the matrix element at that location i^H/ divided by 2*(i+1) where i=iteration index :* product of array + add to running total ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ā<œε2ô{}Ùεε`Isèsè;]PO ``` [Try it online!](https://tio.run/##MzBNTDJM/f//SKPN0cnnthod3lJde3jmua3ntiZ4Fh9eAUTWsQH@//9HRxvoKJjomYMIMxBhGqujEA0WAEoY6RkCaT0TiJgZTEBHwVDPCCJmCpYHCwBZsbEA "05AB1E – Try It Online") --- ### Old version, 32 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` āœvIg;©Lε·UIyX<èèyXèè}P}Oθ®!/®o/ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//SOPRyWWe6daHVvqc23poe6hnZYTN4RWHV1RGgMjagFr/czsOrVPUP7QuX////@hoYx0DPfNYnWgDPVMd49hYAA "05AB1E – Try It Online") **How it works?** ``` āœvIg;©Lε·UIyX<èèyXèè}P}Oθ®!/®o/ – Full program. Argument: A matrix M. ā – The range [1 ... len(M)]. œ – Permutations. v } – Iterate over the above with a variable y. Ig;© – Push len(M) / 2 and also store it in register c. Lε } – For each integer in the range [1 ... ^]: ·U – Double it and store it in a variable X. yX< – Push the element of y at index X-1. I è – And index with the result into M. yXè – Push the element of y at index X. è – And index with the result into ^^. P – Take the product of the resulting list. O – Sum the result of the mapping. θ – And take the last element*. ®! – Take the factorial of the last item in register c. ®o – Raise 2 to the power of the last item in register c. / / – And divide the sum of the mapping accordingly. * – Yeah, this is needed because I mess up the stack when pushing so many values in the loop and not popping correctly ;P ``` [Answer] # [R](https://www.r-project.org/), ~~84~~ 78 bytes ``` h=function(m)"if"(n<-nrow(m),{for(j in 2:n)F=F+m[1,j]*h(m[v<--c(1,j),v]);F},1) ``` [Try it online!](https://tio.run/##XU/LCsIwELz7FcFTVtOQl1pf1/6EeJBCsUJTKFoF8dvrbrtVFMKG2RlmZpuuO@@LW8yvZR1lBdOymMq4S2JT3xGqZ1E38iLKKNwmQrbP5tXBqstxdpbVod0lSS4RgmqPsM1eykKHxOnalA@ZS6NE0AseBpRw@AAm/5IVjeVHjBDXTlv8dWBugEpY7UZD4npI1qT7tbbak9KOIm1orGkXmAhEOApkSe84QjcUW38qooHv2@lvkRXpHBGedilncHHDhBkuCzz6DD8Epbzz2uEZeOkSoHsD "R – Try It Online") Edit: Thanks to Vlo for -6 bytes. It seems that everybody here is implementing the standard reference algorithm with permutations, but I tried to take advantage of the community knowledge gained in the [related challenge](https://codegolf.stackexchange.com/questions/157049/calculate-the-hafnian-as-quickly-as-possible), which is basically the same task targeted for fastest code instead of golf. It turns out that for a language that is good at slicing matrices (like R), the recursive algorithm: `hafnian(m) = sum(m[i,j] * hafnian(m[-rows and columns at i,j])` is not only faster, but also quite golfy. Here is the ungolfed code: ``` hafnian<-function(m) { n=nrow(m) #Exits one step earlier than golfed version if(n == 2) return(m[1,2]) h = 0 for(j in 2:n) { if(m[1,j] == 0) next h = h + m[1,j] * hafnian(m[c(-1,-j),c(-1,-j)]) } h } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` LŒ!s€2Ṣ€QḅL_LịFHP€S ``` [Try it online!](https://tio.run/##y0rNyan8/9/n6CTF4kdNa4we7lwEpAIf7mj1ifd5uLvbzSMAyA/@f7gdSEX@/x/NpRAdbaCjYKJnGqujEA2kdBQMYmN14MLmIMIMSQFQAChhpGcIpPVMIGJmMAEdBUM9I4RBeiZgAYSRhnrGIKMMYcJ6BiDCEiQGNcoQxDYCmWcOVwQ2xRwkbwiXMoHoArOAhhhD5MEGghWBpYxALGOQnYZ6FhB5S6iBUF3GIK4pkv0Qu8AGgnWBpUBcI5AXYgE "Jelly – Try It Online") ### Alternate version, 15 bytes, postdates challenge ``` LŒ!s€2Ṣ€QœịHP€S ``` Jelly *finally* got n-dimensional array indexing. [Try it online!](https://tio.run/##TY89DsIwDIV3ThH2yKqTtKU3YGAAMaEoIwvqxsTKwsBWbsDMBRAj6kHKRYLt9G@Jn9@zPyunY11fYty0zfL8u75M935S2bWP7nNfb0nu4/dG5RCjXyjvM60c5EErT0WrLAQ92iU/xWyADAoMIFVwySsGQysEM4HAiTEhESyjcLAh46dir0cha8O8chwSSsk5jpFLW6IIYlMuQBmSyLCyfBNhlfKqB/Zbltt8dj/dEqBsScSt4S@EPw "Jelly – Try It Online") ### How it works ``` LŒ!s€2Ṣ€QœiHP€S Main link. Argument: M (matrix / 2D array) L Take the length, yielding 2n. Œ! Generate all permutations of [1, ..., 2n]. s€2 Split each permutation into pairs. Ṣ€ Sort the pair arrays. Q Unique; deduplicate the array of pair arrays. This avoids dividing by n! at the end. H Halve; yield M, with all of its elements divided by 2. This avoids dividing by 2**n at the end. œị At-index (n-dimensional); take each pair of indices [i, j] and yield M[i][j]. P€ Take the product the results corresponding the same permutation. S Take the sum of the products. ``` The 19-byte version works in a similar fashion; it just has to implement `œị` itself. ``` ...ḅL_LịFH... Return value: Array of arrays of index pairs. Argument: M L Length; yield 2n. ḅ Convert each pair of indices [i, j] from base 2n to integer, yielding ((2n)i + j). _L Subtract 2n, yielding ((2n)(i - 1) + j). This is necessary because indexing is 1-based in Jelly, so the index pair [1, 1] must map to index 1. F Yield M, flattened. ị Take the indices to the left and get the element at these indices from the array to the right. H Halve; divide all retrieved elements by 2. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~288~~ ~~285~~ ~~282~~ ~~293~~ ~~292~~ ~~272~~ ~~271~~ 263 bytes * Saved three bytes by fiddling with two post-increments and for loop placement. * Saved three bytes by fiddling with anothter post-increment, moving both variable initializations before the branch -- golfed `if(...)...k=0...else...,j=0...` to `if(k=j=0,...)...else...` -- and performed an index shift. * Required eleven bytes by supporting `float` matrices. * Saved a byte thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder); golfing `2*j+++1` to `j-~j++`. * Saved twenty bytes by removing a superfluous `int` variable type declaration and not using a factorial function but instead calculating the factorial value by using an already existing for loop. * Saved a byte by golfing `S=S/F/(1<<n);` to `S/=F*(1<<n);`. * Saved eight bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` float S,p,F;j,i;s(A,n,P,l,o,k)float*A;int*P;{if(o-l)for(k=0;k<l;s(A,n,P,l,o+1))P[o]=k++;else{for(p=j=l;j--;)for(i=l;i--;)p-=P[j]==P[i];if(!p){for(F=p=1,j=0;j<n;F*=j)p*=A[P[2*j]*2*n+P[j+++j]];S+=p;}}}float h(A,n)float*A;{int P[j=2*n];S=0;s(A,n,P,j,0);S/=F*(1<<n);} ``` [Try it online!](https://tio.run/##vY89a8MwFEXn9le4gYI@rlvLsdMWWUMWz4aMRkMIcWPZtUWSzei3u7KblNKh2QriwUPnXs7bhe@73ThWbb89BxtY5NKglieyRocCLXo0dP5la1l3Z1bIoa5IH7a06o@kUZFssvYnzwWlRdlr1XAu9@1pP0ygVUa10oShnHO1X@ppsaEqSqOVn7WWvvnB0jmQK6sEjO83WSdzpgy1TK3LooyZ0SxmHfdBzrnRWm64stI593XGYZL5lh68deBR5SOe9IVXWYOIys2zyhkRWdZR6caPbd0ROtzf2aOPVWTxWCFY4EDIXFdqOgjEWCJBihVe8Io3iAhCQMQQS4gEIoVYOcSUyr960glPEAoHcQMNBa7vNvzb7593h@SGYIQgeUovI7oc5MZP "C (gcc) – Try It Online") # Explanation (271 bytes version) ``` float S,p,F; // global float variables: total sum, temporary, factorial j,i; // global integer variables: indices s(A,n,P,l,o,k)float*A;int*P;{ // recursively look at every permutation in S_n if(k=j=0,o-l) // initialize k and j, check if o != l (possible permutation not yet fully generated) for(;k<l;s(A,n,P,l,o+1)) // loop through possible values for current possible permuation position P[o]=k++; // set possible permutation, recursively call (golfed into the for loop) else{for(p=-l;j<l;j++) // there exists a possible permutation fully generated for(i=0;i<l;) // test if the possible permutation is a bijection p+=P[j]==P[i++]; // check for unique elements if(!p){ // indeed, it is a permutation for(F=p=1,j=0;j<n;F*=j) // Hafnian product loop and calculate the factorial (over and over to save bytes) p*=A[P[2*j]*2*n+P[j-~j++]]; // Hafnian product S+=p;}}} // add to sum float h(A,n)float*A;{ // Hafnian function int P[j=2*n];S=0; // allocate permutation memory, initialize sum s(A,n,P,j,0); // calculate Hafnian sum S/=F*(1<<n);} // calculate Hafnian ``` [Try it online!](https://tio.run/##vVRLb9pAED6XXzGpVMmPocEE0ofjQy6oRySOCFWLvYY1613XXqNS5P51OoshIUCanoqQZVsz32tmHXcXcbzbpVIzAxMscBTCld/tLSyknjMJbeWalYLNJa@@gtGGXld1jmB4XuiSlRuElMVGU43sZCiuQl5CC2X4gpen4EIlIuZVp3IeUeEYJWpcuXsN3mNIDd443LYgJY/rshJrLjcgtV4ByeRrXm6g4GVeG2aEVgQIk@@qAyJ1VlEW9VB3pXtVlFDCkH7xiwNhqQQyhHjJ4xX1goabCCQ4ha4qQVLhBYnSBjbcQFpLErPgipfM8MTtAKS6dMLVgwxPHPmB6z7RkvQCzLLU9WIJT/BrJmte2W4glyVXBs6oW2Z6KewNMcF4qmfRyvdfG2jFL0Ba/fgiy5hJMrrQMuWJHZEmdXyvxEolT1xWfGt9FVFXhhl5y3zfPWWihpID/ykqUwF7Jj3N7CyrQ1Qi6oWCEN1rBgyvjB2G1XMVU1i2uch4fMyk8KPxNJtFdBW@PwvPIdsBW3O1Ej9qEi15TmlX1Ewrc1O429fXmJaV8wRBmJb5RIrltn5GUREFSHtHOalw5EXZ8@S/sVQJRjMsdVLHpt0Eu3g0gbiWlEqb/PFkgaNpvfcV@xuaTMXWHOYbCsbuGtn1osfpeNr3spnX95RP3ru/aTozcn7JaFsmflSETdO85pElyZ6ozjvtl2Bp9/jpRG5fVh8J0lodRkALRIuZRaRmFk4oh0sGKXVszZ5OMue5tp@Vk0NpJcDxFGXYc8Orgp/DO4rZN05uo5HnBA8Pyg2bf2vc5Uwox9123hUl2Uid9x9ShPe4dJy9/enM3QbYxzsc4BDv8RN@xi8Y9DAIMOhjcIfBAIMhBvcN9l03/BvO0JYPsBs0GLxR2g3w@H@7@Fzff35ucPCGwB7C4OPwcOkdDDW7Pw "C (gcc) – Try It Online") At the program's core is the following permutation generator which loops through `S_n`. All Hafnian computation is simply build upon it -- and further golfed. ``` j,i,p;Sn(A,l,o,k)int*A;{ // compute every element in S_n if(o-l) // o!=l, the permutation has not fully been generated for(k=0;k<l;k++) // loop through the integers [0, n) A[o]=k,Sn(A,l,o+1); // modify permutation, call recursively else{ // possible permutation has been generated for(p=-l,j=0;j<l;j++) // look at the entire possible permutation for(i=0;i<l;i++)p+=A[j]==A[i]; // check that all elements appear uniquely if(!p) // no duplicat elements, it is indeed a permutation for(printf("["),j=0;j<l // print ||printf("]\n")*0;) // the printf("%d, ",A[j++]);}} // permutation main(){int l=4,A[l];Sn(A,l,0);} // all permutations in S_4 ``` [Try it online!](https://tio.run/##fZLBTuMwEIbvfYqh0koxcUWRuGVz6DNw7EbIJJN2Esf22g5SVXj2Mm4JFCj4kEv@@TTfzNSLTV0fDp0k6Yp7k62kllb2gky8XhV7eH83N1DbwY0RAZ/Q7wA1DmgikIH7BzMDajO70AJ@fEywV6WWELcIDv0wRhXJGtiqAMZGaEetd/CIaGCDBr2K2MwAWuuzvlwW/V9d9HkuLnC1tY6x3o6b7RHP7eMGfYD1UoIRTIHV2lZlLyfH/FYUXyiDbajdnbcmoVZag8d69IGeUO9m7B1wD/Crp7Mh0KP@rnlRzpULLTs27Niw@2x4kutBxaMXD5w8XuQnx0QjBhGDiEEuL1frrir5S1Vx3OEW655RzEtmb0sMoJxD5WE09H88aqZ9Xrnf12ksNKPTVDNtIkkgvonAG2gQG1CXWnSe99Nm8/VcTN7nw0t/U/T5eQpW/8xcXC8L8aWBNJOUhCn4p5Ewl@yc55UoXl4@kp/6GBSZTOy5BnR5x3ldTce/5LJTSZrPWVE4Xfrd4fAK "C (gcc) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes ``` LHµ2*×! LŒ!s€2;@€€Wị@/€€P€S÷Ç ``` [Try it online!](https://tio.run/##y0rNyan8/9/H49BWI63D0xW5fI5OUix@1LTGyNoBSAJR@MPd3Q76EHYAEAcf3n64/f///9HRhjpGOsY6JjqmOmY65joWsTrkiShQyaBYAA "Jelly – Try It Online") I think the `;@€€Wị@/€€P€` part can likely be golfed down. Need to come back later to check and add an explanation. [Answer] # [Haskell](https://www.haskell.org/), 136 bytes *-14 bytes thanks to ovs.* ``` import Data.List f m|n<-length m`div`2=sum[product[m!!(s!!(2*j-2)-1)!!(s!!(2*j-1)-1)/realToFrac(2*j)|j<-[1..n]]|s<-permutations[1..n*2]] ``` [Try it online!](https://tio.run/##3ZBBboMwEEX3nGKyCxG42JDQSGRXddXuukOWYiWkIcWAwHSVu9MZh0QQblAsLM@fr/fHPqv2JyuKvs91XTUG3pRR7CNvjXMCfS0Tv8jKb3MGvT/mv3uxazud1k117A4m1YvFssVfrC6@cH3ujmpO9UuTqeKrem/UgUT3ekn8lDNWSnltE7/OGt0ZZfKqbK28ElL2WuUl7ECr@hOWdZOXBhicXAfwS2kFHkRsLa0A4EGKlQeBBOk4gwJpiAqLR6aATOHUZEkxbZs5E3XsC8aJFE1am7vuAWdiNgmLrD6bibOQYvi9ywLatqRN@ZwkQSHxw2uZ4wvxhyO6MewJkeHTvYOBYR2CTiENwtnrxLYdUgaGfcD1fLbbHDbFMqyDSvF0WcxCGdseIAafDP3jxH9tAFz9Hw "Haskell – Try It Online") Ugh... [Answer] # [MATL](https://github.com/lmendo/MATL), ~~29~~ ~~24~~ 22 bytes ``` Zy:Y@!"G@2eZ{)tn:E/pvs ``` [Try it online!](https://tio.run/##y00syfn/P6rSKtJBUcndwSg1qlqzJM/KVb@grPj//2hjBQM9c2sgYapgHAsA) Or verify all test cases: [1](https://tio.run/##y00syfn/P6rSKtJBUcndwSg1qlqzJM/KVb@grPj//2hjBQM9c2sgYapgHAsA), [2](https://tio.run/##y00syfn/P6rSKtJBUcndwSg1qlqzJM/KVb@grPj//2gDHQUTPXMQYQYiTK0hXKCwkZ4hkNYzsYbIQbg6CoZ6RiARU7AcmAtkxQIA), [3](https://tio.run/##y00syfn/P6rSKtJBUcndwSg1qlqzJM/KVb@grPj//2hDPWMdBRM9Qx0FQz0jHQUDPQMQYQkSM7GGSJiAJIz0zOFKTEAsc2sIFyxhAtEBZgENMAbJgo0CKwFLGIFYxiDbDPUsrCF2gI2C6jAGcU3h9kLsABsF1qEDETPWM4oFAA). ### How it works ``` Zy % Size of (implicit) input: pushes [2*n 2*n], where the % input is a 2*n × 2*n matrix. : % Range: gives row vector [1 2 ... 2*n] Y@ % All permutation of that vector as rows of a matrix !" % For each permutation G % Push input matrix @ % Push current permutation 2e % Reshape as a 2-row array Z{ % Split rows into a cell array of size 2 ) % Reference indexing. With a cell array as index this % applies element-wise indexing (similar to sub2ind). % Gives a row vector with the n matrix entries selected % by the current permutation t % Duplicate n: % Number of elements, range: this gives [1 2 ... n] E % Double, element-wise: gives [2 4 ... 2*n] / % Divide, element-wise p % Product vs % Vertically concatenate and sum % End (implicit). Display (implicit) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~121~~ ~~119~~ ~~117~~ ~~115~~ 101 bytes ``` A=>(F=(a,t,r)=>{a--?A[t].map((x,i)=>F[i]=F[i]||F(F[i]=a,i,a%2?r:r*x/(a+2))):s+=r})(A.length,s=0,1)||s ``` [Try it online!](https://tio.run/##bY/LboMwEEX3@Qo2lezGDNi8QiQnYsNPIBZWShNX1CCDqkil305tQx5SuxnP3DtzD3yILzGctOxHX3VvzdxrqUZ@6tTQtQ203XlzEe9KCsXngh9QyZEgI9GYH76F7x@LaqzhU/QIXYk0YlnJmtsyTSVygyCSiBd21Hv9eg2Q2DKM8X7Ycv2DUQFto87jhQw8JBRP07B8AFqhqKpC4sWQ1MSrzEO8sK4x3gSBGTb/rma2pE9HRjAGA2peiBctvQnEo8Ae4RA74YGhKeTRHxCFyALobRlCW3KrrQBqe2Yp2X3JZWfWp3crXq5cZ0KixXeBbslZzHaRZVLYLX6@Bq5XkR2TJ/7CcoHuyll2ZOuPsZRBnOzmXw "JavaScript (Node.js) – Try It Online") ## Explanation & Ungolfed ``` function hafnian(A) { // Main function taking an array return ( F = function( // Helper function, and also a temporary storage a, // how many numbers left t, // previous number r // the product ) { // The braces are to avoid returning value a-- ? // If a > 0: A[t].map((x, i) => // Loop from i = 2n - 1 downto 0: F[i] = F[i] || F( // Skip if F[i] is truthy, i.e. i used in the permutation F[i] = a, // Otherwise: Set F[i] to truthy* & start a new recursion i, // with i as the previous number a % 2 // If a - 1 is odd: ? r // r does not change : r * x / (a + 2) // Otherwise: multiply A[t][i] to r, divide by a + 1 ) // Set back F[i] to undefined after the recursion ) : s += r; // Otherwise: add r to s. The factor 1/(n!*2^n) = 1/(2n)!! } // has been included in the recursion )( A.length, // 2n = size of the array s = 0, // Initial sum s = 0 1 // Initial product r = 1 ) || s; // Return s } /* Note that when a = 1 F[i] will be falsy, but the next recursion will just skip this part anyway. */ ``` [Answer] # [Coconut](http://coconut-lang.org/), ~~165~~ ~~145~~ ~~128~~ 127 bytes -1 byte thanks to Mr. Xcoder ``` m->sum(reduce((o,j)->o*m[p[2*j]][p[j-~j]]/-~j/2,range(len(m)//2),1)for p in permutations(range(len(m)))) from itertools import* ``` [Try it online!](https://tio.run/##rU7NDsIgGLvvKTjC8m3sR50X9yLIYZnMsAw@wuBmfHXEm/Fo7KFtmqbpjDPaGNJyuSZTjXs01KtbnBWlCCurRiyNcKIrVymzrtUzG56Zd@Ane1d0U5YaxnnHoGULeuKItsQpb2KYgka7089iRrF4NEQH5QPithNtHPpQJiF6aOpBgmjqI/RSksdIljc5r20oCiFa6KCHAxzhBAOcc/WnhPxp6OthegE "Coconut – Try It Online") [Answer] ## Perl 6, 86 bytes ``` {my \n=$^m/2;^$m .permutations.map({[*] .map(->\a,\b{$m[a][b]})}).sum/(2**n*[*] 1..n)} ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~87~~ 86 bytes ``` f=A=>A[0]?A[0].reduce((y,x,i)=>i&&y+x*f((g=B=>B.filter((_,j)=>j&&i-j))(A).map(g)),0):1 ``` [Try it online!](https://tio.run/##bY/dboMwDIXveQquULKlLgl/ZVKY6GsgNCEKLIgBomxqn57Fgf5I241jn2OfT2mLn@JcTmqcd/1wqpZxUv0sy6E/D10F3dBYn0Xdq6KXSy1TmaSZm79jgak6fZcVIVd2YYrKRDnO9fXyUhPSyKNMjlCrbq4mQj5Yq@3WcdSupZSkFL6KkTSUMpe@8ZVINgrJMpfZPgQ5szP9MNvNc0qt/V4P1r@rEZbw6UgL2hDA9Qv@qoU3gdkcxCMcfCM8MDyE2PsD4uAhgN@WwcUSo7YBOPYCKdF9yWRH6PO75a9XptMh3uqbQLNkLIGdh0wOh9WPt8DtysMxeOKvLBNoroyFo9g@JkIBfnBYfgE "JavaScript (Node.js) – Try It Online") This is a port of Kirill's algorithm, and this turns out to be shorter than the naive approach! However I'm retaining my original answer and posting this as a separate one. ### Explanation ``` f = A => // A function receiving an array as input A[0] // If A is not empty: ? A[0].reduce((y, x, i) => // Calculate the sum i // for i = 1 to 2n - 1: && y + x * f( // A[0][i] * the hafnian of (g = B => B.filter((_, j) => j && i - j) // array A removing rows 0 and i )(A).map(g) // as well as columns 0 and i ), 0 ) : 1 // If A is empty: return 1 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 84 bytes ``` aTr[1##&@@(a[[##]]&@@@#~Partition~2)&/@Permutations@Range[n=Tr[1^a]]]/(n/=2)!/2^n ``` [Try it online!](https://tio.run/##TY1NasMwEIX3OcUUgUlAlSzZiZOFi45gSnfCAVGc1gsr4KoroxyiN@gJewRXIzk/m/l5b943g3Gf3WBc/27mE9Sz@fv5fRu1ICRTam20JqRtw6jIpTGj611/the5ybhqunH4dgaFL/Vq7EenbY3Ro2nblq8tr@XmicujnZuxt04TeH6Bkw48yICr1TRNOYWSbT2FKTQKufd0BYtcYdk9HAQhGJKJ0FmZtN1VoCCYvINYGYU7UrACUeIqsxzLAbUFJXCWyKtuR5FSoS9uVplScQqQIvkRGI@iJXEq8Kdg@@QfFuCSKnDdPvxPvyIwpqKFq/Tez/8 "Wolfram Language (Mathematica) – Try It Online") --- # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 68 bytes ``` If[#=={},1,Sum[d=Rest@*Delete[i];#[[1,i]]#0@d[d/@#],{i,2,Tr[1^#]}]]& ``` [Try it online!](https://tio.run/##TY09T8MwEIb3/oqTLHVAh5tz0oYKBWVgYUPAZrlSRFxhiTAUM1n@7cFnpx/Lfbzvvc9Ng/@y0@Dd5zAfoZtfjlp0XYhI@P436bF7s7@@v3u239Zb7cyj0JrQGSOqftTjphcGg0OFHydNB2GiMev59eR@vBZw/wQJZwysYdOvQggVQiO3ESGkhlDFiCtY5JbL7uYgCclQklKXTdF2ZwGBpLqCZJOFK5JkzSg6y7LismdtQRHPinnt5ShTWvbpYjUllacEqYufgfkoW4qnmn@SfCj@fgEuqZrX7c3/8isDcypbvKoY4/wP "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 51 bytes ``` h(m)=if(#m,sum(n=2,#m,m[1,n]*h(m[^n,^n][^1,^1])),1) ``` [Try it online!](https://tio.run/##PY7dDsIgDIVfhcybYbpmhek0y3wRwhJv1CVCiD8XPv2kRXdTes6hX5vOj7m5pmW51UGP86XeBHi@Qx1HA7kNjiD6bQ7dFGGK3k0EE3mtgfRyTun@qYNqTio95vjKbcWiUkzToJxrQXW4G7iAan22xOm57Ncsy2wbpPxiN5SsSFCE5j@PncgfidAygf4etlyO7AmDuDMM6tcvAuiHIk2547helAGWU0HJFwkMd5a3ER6GskNQvwnLcrfuLTsEJRNQPIvGe718AQ "Pari/GP – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~185~~ 181 bytes ``` def f(m): a=0;n=len(m)//2 for x in itertools.permutations(range(n*2)):p=1;[p:=p*m[x[2*j]][x[2*j+1]]for j in range(n)];a+=p return a/(math.factorial(n)*2**n) import math,itertools ``` [Try it online!](https://tio.run/##ZY7NbsMgEITvfoo9GgcRg8m//CSIA2rtxlEMiBApfXp3107Tqj3AwMzsB/Ezn4Nv9jFN03vXQ1@O7FiAa@uTb6@dx@t6rQroQ4IHDB6G3KUcwvUmYpfGe3Z5CP5WJuc/utJXirFjbOXJxGMbq9E8jKou1i66ktYS6EKg5wSzJ7dqYwGpy/fkwa3L0eWz6N1bDmlwV6xUqqo8K4YxhpSBYv76xhTT4HPZl8bUHLTYWA4GhUNtLWPFn3hH2/ZXEQ0MlJCoQi/e9tvgIIX6AQo9G//RUjRc4wSFtahxHfCONEOuRlfhQ0uqUXeYyKer5y5pzZs5IQKl5CrUBulS7OfkMBOWboPnzeudmUsE6pKLZ0X/nL4A "Python 3.8 (pre-release) – Try It Online") Golfed reference implementation provided in the question. ]
[Question] [ Given a non-empty string consisting of only lower and upper case alphabetical characters and spaces (`[a-zA-Z ]`), reduce it to a snippet of the alphabet, starting with the first character. To reduce a string, begin with the first alphabetical character, then remove every character after it that is not the next letter of the alphabet. Continue doing this until you reach the end of the string. For example `codegolf`: Begin with `c`, remove `o` as it is not the next letter of the alphabet. Keep `d` as it *is* the next letter of the alphabet, and keep `e` as it is the next letter too. Remove `g`, `o`, and `l`, and keep `f`. Your final snippet would then be `cdef` ## Rules * Capitalisation should be maintained, so `CodEgolF` would result in `CdEF` * Space is not a letter of the alphabet, and thus should always be removed, even if it is the start of the string * Due to the nature of the reduction, the first alphabetical character of the input will *always* be the first character of the output. * `zZ` is the last letter of the alphabet. There are no letters after it, the alphabet does not loop. ## Test Cases ``` codegolf -> cdef CodEgolf -> CdEf codeolfg -> cdefg ProgrammingPuzzles -> P Stack Exchange -> St The quick red fox jumped over the lazy brown dog -> Tuvw Zebra -> Z Abcdegfhijkl -> Abcdef ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes **in each language** wins! [Answer] # JavaScript (ES6), ~~66~~ ~~79~~ ~~68~~ 67 bytes ``` f=([c,...s],p)=>c?(p?~parseInt(c+p,36)%37:c<'!')?f(s,p):c+f(s,c):'' ``` ### How? **Testing consecutive letters** Because converting two characters to their ASCII codes would be a rather lengthy operation in JS, we use the following formula instead: ``` ~parseInt(b + a, 36) % 37 ``` Provided that both ***a*** and ***b*** are in `[a-zA-Z ]`, the above expression equals `0` if and only if ***a*** and ***b*** are consecutive letters (i.e. consecutive digits in base 36), no matter the case of the characters. For instance: ``` ~parseInt("Y" + "x", 36) = ~(36 * parseInt("Y", 36) + parseInt("x", 36)) = ~(36 * 34 + 33) = -(36 * 34 + 33 + 1) = -(37 * 34) ``` **Formatted and commented** ``` f = ([c, // c = current character ...s], // s = array of remaining characters p) => // p = previous matching letter c ? ( // if there's still at least 1 character to process: p ? // if p was already defined: ~parseInt(c + p, 36) % 37 // test if p and c are NON-consecutive letters : // else: c < '!' // test if c is a space character ) ? // if the above test passes: f(s, p) // ignore c and keep the current value of p : // else: c + f(s, c) // append c to the final result and update p to c : // else: '' // stop recursion ``` ### Test cases ``` f=([c,...s],p)=>c?(p?~parseInt(c+p,36)%37:c<'!')?f(s,p):c+f(s,c):'' console.log(f("codegolf")) // -> cdef console.log(f("CodEgolf")) // -> CdEf console.log(f(" codeolfg")) // -> cdefg console.log(f("ProgrammingPuzzles")) // -> P console.log(f("Stack Exchange")) // -> St console.log(f("The quick red fox jumped over the lazy brown dog")) // -> Tuvw console.log(f("Zebra")) // -> Z console.log(f("Abcdegfhijkl")) // -> Abcdef ``` [Answer] # [Python 2](https://docs.python.org/2/), 69 bytes ``` lambda s:reduce(lambda x,y:x+y*((ord(y)-ord(x[~0]))%32==1),s.strip()) ``` [Try it online!](https://tio.run/##LY/LTsMwEEXX8BWzqWzTtIJ2FylICHVfCVaULhw/EreJJzgOJKnKr4cJ6ureOSONzjRDLNFvJpt9TpWscy2hTYPRnTL8NvfJkPbL4YFzDJoPYjVHf/h9PAqx2G6y7Ekk7bqNwTVciMliACVbA87DgSnUpsDKsoS9ot7dKsyYakF9H7AIsq6dL/bdOFamJfgWpTrDrlel9IUh8F4a@OocQZIDiz2curqhit8mQKRtJccB8oA/HjTOhz9MHiTlS67IwZbudK7YMb2/a4LzEdjlCqtnuFzZmpRrGflsndj/oD/@AA "Python 2 – Try It Online") A simple reduction of the string. We simply concatenate the next character if and only if `(ord(y)-ord(x[~0]))%32==1`. Very ugly check - I am sure it can be improved, but I'm not sure how! [Answer] # [Python 3](https://docs.python.org/3/), ~~75 85 84 91 81 77~~ 75 bytes I think this is as short as it can get in [Python 3](https://docs.python.org/3/). It can be shortened by a few bytes in Python 2, as shown in [Sisyphus' submission](https://codegolf.stackexchange.com/a/139416/59487). * **EDIT:** +10 for fixing a bug * **EDIT:** -1 by fixing another bug * **EDIT:** +7 for fixing another bug * **EDIT:** -10 bytes with help from [@Ruud](https://codegolf.stackexchange.com/users/55844/ruud) * **EDIT:** -4 bytes since the OP allowed us to output the letters separated by a newline * **EDIT:** -2 bytes thanks to [@Ruud](https://codegolf.stackexchange.com/users/55844/ruud), back to the original byte count! ``` s=input().strip();k=0 for i in s: if(ord(i)-ord(s[0]))%32==k:k+=1;print(i) ``` [Try it online!](https://tio.run/##FcmxCoAgEADQva@4JfCIonIzbmroI6KtpMPwRG3o662mN7zw5FO8LiUR@3BnhV3KkYPCyVFfWYnAwB6SqYCtkrgrxvYnrf2GWOuRyBnX0DCFyD5/XQrMsh@LXPYF "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` áćsv¤yìuÇÆiy« ``` [Try it online!](https://tio.run/##AScA2P8wNWFiMWX//8OhxIdzdsKkecOsdcOHw4ZpecKr//9BQiBBQyBHREU "05AB1E – Try It Online") -1 thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes ``` ;ṢxS⊇.ḷ~sẠ∧Sh~h ``` [Try it online!](https://tio.run/##ATQAy/9icmFjaHlsb2cy//874bmieFPiiocu4bi3fnPhuqDiiKdTaH5o//8iIENvRGVvbGZnIv9a "Brachylog – Try It Online") This would be 10 bytes: `⊇.ḷ~sẠ&h~h`, if it weren't for the fairly uninteresting "strings can start with spaces" constraint. ### Explanation ``` ;ṢxS S is the Input with all spaces removed S⊇. The Output is an ordered subset of the Input .ḷ The Output lowercased… ~sẠ …is a substring of "abcdefghijklmnopqrstuvwxyz" ∧ Sh The first char of S… ~h …is the first char of the Output ``` Since this is fairly declarative, this is also really slow. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~18~~ ~~16~~ 15 bytes *Thanks to [Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) for pointing out a mistake, now corrected* ``` Xz1&)"t@hkd1=?@ ``` Letters in the output are separated by newlines. [Try it online!](https://tio.run/##y00syfn/P6LKUE1TqcQhIzvF0Nbe4f9/9ZCMVIXC0szkbIWi1BSFtPwKhazS3AIgM78stUihBCibk1hVqZBUlF@ep5CSn64OAA) Or [verify all test cases](https://tio.run/##LY5BCsIwFET3nuLjwuCyBxAr2n2hXYhQME3SpG3SrzHVmsvHX3A1jzcwjOPBpnu6xmy334bcjDI7HPNkmuZSJyZQKo22Yxt2Rln8EVZNqIlLj9pz5/pJl3OMVr1IVoGLEYpFGD5pRaI2Cp5zT9IrCR0uMMzuQYhv5SFQa3n8QuvxM4HEdfimWs8pT62gD53ph9GyHw) (the footer code displays all output letters on the same line for clarity). ### Explanation ``` Xz % Implicitly input a string. Remove spaces 1&) % Push first character and then the remaining substring " % For each t % Duplicate previous character @ % Push current character h % Concatenate both characters k % Convert to lowercase d % Consecutive difference. Gives a number 1= % Is it 1? ? % If so @ % Push current char % End (implicit) % End (implicit) % Display stack (implicit) ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~102~~ ~~101~~ 74 bytes ``` s->{char c=0;for(char x:s)if(c<1&x>32|~-x%32==c%32)System.out.print(c=x);} ``` [Try it online!](https://tio.run/##nZPJTsMwEIbvfYpRJVAiUYfl1pBKqOoRqBROIA6ul9SpYwcvJS2UVy9uKCARDpQ5ePen3zP@S7zEA10zVdLFtvYzKQgQia2FaywUvPQghHXYhXUuFJZQhhvIOyER94o4oRUaa2V9xcwlmWPz8DiCG8i2djB62c2BZKcp1yZqJ83QxoJH5PLsuBldnL@@DZqji/MsI6GN85V1rELaO1QboVxEsiZON9u018rYy9urWWpBoQoio9yFw8XDI2BT2HiveRffUq0zDFco/@g0j77OfEafaMoKLXn/BA6JJCGU8S5urOnkX7gxnfyCg528gCsO432oK7q8qdGFwVUVEjf167Vk9k/gJJl2WbnDZAGTJhRYFezPApMkd13Y3ZzBkxcBaBgFrhsofVWHoV4yAy7sSrxewczoZwVUf@YjSe788rmLu2czgw@sQYu777KuZiGZBZ@LciH7h7Dai99FjVGF6/2vHQ6dHgdjXBmDVzEKPplgMr81lIXnRzsP3SBMCKtdZOP0p0GkioI/4rRFb3qb7Ts "Java (OpenJDK 8) – Try It Online") -27 bytes thanks to @Olivier Grégoire [Answer] # PHP, 64+1 bytes ``` while($c=$argn[$i++])$c<A||$n&&($c&_)!=$n||(print$c)&$n=++$c&__; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/008e175f745bc3de2c439e17917ace212eab378f). --- Apart from the usual tricks: When `$c` reaches `Z`, `++$c` results in `AA`, and `&__` keeps that length untouched; so `$n` will match no further `$c`. [Answer] # [Pyth](https://pyth.readthedocs.io), ~~23 22 21~~ 20 bytes -1 byte indirectly thanks to [@Erik the Outgolfer's trick (`-Qd`)](https://codegolf.stackexchange.com/a/139418/59487). -1 byte thanks to @Erik the Outgolfer. ``` VQIqZ%-CNCh-Qd32N=hZ ``` **[Try it here.](https://pyth.herokuapp.com/?code=VQIqZ%25-CNCh-Qd32N%3DhZ&input=%22+CodeGolf%22&debug=0)** [Answer] # Haskell, ~~106 105~~ 97 bytes ``` import Data.Char import Data.List z=ord.toUpper a%b|z a+1==z b=b|0<3=a nub.scanl1(%).filter(>' ') ``` *I tried to use `fromEnum` + char arithmetic instead of importing `Data.Char`, but that ended up being longer...* Saved 8 bytes thanks to H.PWiz! [Try it online.](https://tio.run/##ZZBdS8MwFIbv8ytegmLLdCjeDTPQOUEcOJjeeOVJm364tKlp6rTsv884ta7uXITDeZ@85yOjeqm03mzyojLW4ZocDScZWbZbmOW1Y60wNh4681hVyjI6lOsWNDgTooUUcn16cS6IJaJs5LCOqNRnwWE4THLtlA3GRzgKN3VmGh1fKYxGCKavoGMsMrMChRBjEE5@ntt7BCEjPP9@eIbEGiSExDYEqsYtnJ2V4Pd3nKEfaxiXKbvKa7WLHoDfXN7ORuAYDBDUP619zvHdCVLtijJkrKC89CaxYdsuCXhkYpUanfDd@XgUq4T/IhMTT/eRSTz9Q/Bl45F03ybtoLk1qaWiyMt03rStVnWfnnfkwlG0xPQ9yqhMVZ9auA57yBRem9yjVsVIzDtemqLyqXlTFv5o0NR@QFqzKv3O/4Z7aN5WndWTkpb6@lMnXkq/SJpk@ctS95mt4s@w@QQ) [Answer] # Pyth, ~~21~~ ~~20~~ 18 bytes ``` ef&qhThQhxGrT0tyr6 ``` [Try it here.](http://pyth.herokuapp.com/?code=ef%26qhThQhxGrT0tyr6&input=%22codegolf%22&debug=0) Way more efficient 20-byte version: ``` .U+b?t-CrZ1Creb1kZr6 ``` [Try it here.](http://pyth.herokuapp.com/?code=.U%2Bb%3Ft-CrZ1Creb1kZr6&input=%22The+quick+red+fox+jumped+over+the+lazy+brown+dog%22&debug=0) -1 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) (indirectly). [Answer] # [C# (Mono)](http://www.mono-project.com/), ~~129~~ ~~107~~ ~~93~~ ~~91~~ ~~87~~ 86 bytes ``` s=>{var r=s.Trim()[0]+"";foreach(var c in s)if(r[r.Length-1]%32==~-c%32)r+=c;return r;} ``` *Saved 2 bytes thanks to @Mr. Xcoder.* *Saved 4 bytes thanks to @jkelm.* [Try it online!](https://tio.run/##fdDBasJAEAbge55iyKEkWKXSW2MsRezJgqBQqHjYbCbJarLTzm6sRtJXT1d7bTztsP@3y8xIM6xIU1cbpXNYnYzFKvI8WQpjYOmdPWOFVRIOpFJ4E0oHobt8rbWcGMvuzT38nVPIIO5MPD0fBAPHZrRmVQXh5mE78P0oI0Yhi@ASSlAaTMhx8MMbHi1Q57YYjrcDefc4DifjZx7IJ44Ybc0aOGo719GMtKESR@@sLC6UxiALfEkp5lRmfhhG/4sZpfPbAi6fOJH3kyVTzqKq3JjLumlKNP12ZYXcw/woC6Fz7HfrAuGrVs4yppDREXZ19elKOiCDdWkpmhMkTN8aUrrR3QcmLPrjl0S6JWWF2u3Lq/Jar@1@AQ "C# (Mono C# compiler) – Try It Online") [Answer] # [Perl 6](https://perl6.org), 51 bytes ``` {S:i:g/\s|(\w){}<([<!before "{chr $0.ord+1}">.]+//} ``` [Test it](https://tio.run/##VY7NbsIwEITvfopthNpEQGgvHAigVog7EpwoPST2xjEkcWo7/KV5st76YqkDpWpvuzPfzmyBKh02pUbYD30akOwE9wpZSbGvjRI5h0lTLUdixAcb/eFuDl5Vj93X8V2EsVQITkUTBZ1HXyrWfaqdqf/WHQzqxuY8G9QGJpCKHLXrfX36ukiFcR@gP4UHLyBt68oyASnSMIfu5SAgNvfn1nIudERelKYHHTwWSA0y8KAiAELDv0fdK@j9IXvgXMU26Vd1SN1QyZDLNG4NyjAmM8nmN2HG5jGBFrECvyGcLJTkKswyW7Yoz@cUdestyNKEdAfzI03CnGOrLQ1ZJQjvpbCG/RJieYRtmRV2lHtUYKybhucTREoecmDyUrMq9weyxkiF7bYmL5Et5nEitru0VS57/A0 "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter $_ S # substitute implicitly on $_, not in-place :ignorecase :global / | \s # match any space | (\w) # match a word character {} # make sure $/ is updated (which $0 uses) <( # ignore everything before this [ <!before "{ # make sure this won't match after this point chr $0.ord + 1 # the next ASCII character }"> . # any character ]+ # match it at least once // # remove what matched } ``` Note that `<!before …>` is a zero width assertion [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` ḟ⁶;ð,ŒuṪ€O_/⁼-ð¡/ ``` [Try it online!](https://tio.run/##y0rNyan8///hjvmPGrdZH96gc3RS6cOdqx41rfGP13/UuEf38IZDC/X///8fkpGqUFiamZytUJSaopCWX6GQVZpbAGTml6UWKZQAZXMSqyoVkoryy/MUUvLTAQ "Jelly – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~18~~ ~~17~~ 16 bytes *Saved 1 byte thanks to @Shaggy* ``` x c Çc %H¥V%H©V° ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=eApjCsdjICVIpVYlSKlWsA==&input=IiBjb2Rlb2xmZyI=) Was thinking this would be a good bit shorter, but... Such is life... ### Explanation ``` x First line: set U to the result. x Trim all spaces off of the input. Only necessary to remove leading spaces. c Second line: set V to the result. c Take the charcode of the first character in U. Ç c %H¥ V%H© V° UoZ{Zc %H==V%H&&V++} Final line: output the result. UoZ{ } Filter to only the chars in Z where Zc the charcode of Z %H mod 32 ==V%H equals V mod 32. &&V++ If true, increment V for the next letter. ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~70~~ 60 + 18 bytes *-10 bytes thanks to [TheLethalCoder](https://codegolf.stackexchange.com/users/38550/thelethalcoder)* ``` a=>{var c=a.Trim()[0];return a.Where(x=>x%32==c%32&&++c>0);} ``` Byte count also includes: ``` using System.Linq; ``` [Try it online!](https://tio.run/##XVDBThsxED3jrxgORbagK9Qew66EolBVohIqkZCKODizs7sGrx3GdghB@fbUm4Wg9h1GT2/seW8Gw1f0TLsUjGvh9jVE6otr454nQjjdU1hqpA996q0ljMa7UPwgR2xQvAnIQKtDgMs9H5UBIepoEFbe1PBLGyfVofX5aMBVcngRIucMZ/Bz5lJPrBeWLrDTXFXQQLnTZfW20gxY6mLOppfq/vxhwhQTO9DFXUdMcl1W6y/fv5Ul5npycnqK1bmabHcTcTQGGizAuGWK79JLZyxJuZeghGnezVsqfpOu8xlIKgXHJbhkrfov9IBm/KiKub82IUpVXHmeaewkQlkdpt2xiSRRqWx69I84erxn2R7mj2wrtjv0NbXeNmLq69mewCBl0oob9i3rvs873aTNxlIQt1HjE8zW@XCuJTHvCJ6TyRJTDY1fw2Pql5n6FTHE3LV68woL9i8Oat@KP7RgLS4XmF2bzjw@2b8 "C# (.NET Core) – Try It Online") 1 byte longer ~~(currently)~~ (not anymore) than TheLethalCoder's so posting for the sake of fun. Different approach, with LINQ. This takes advantage of two C-like features in C# - a character `char` variable is implicitly behaving the same as an integer `int`, and boolean AND operator `&&` doesn't execute right operation if left returns a `false`. Code explanation: ``` a => // Take string as input { var c = a.Trim()[0]; // Delete leading spaces and take first letter return a.Where( // Filter out characters from the string, leaving those that: x => x % 32 == c % 32 // it's the next character in alphabet case-insensitive (thanks to modulo 32 - credits to previous answers) && ++c > 0 // If it is, go to the subsequent character in alphabet (and this always has to return true) ); } ``` [Answer] # q/kdb+, ~~47~~ 45 bytes **Solution:** ``` {10h$({(x;x,y)1=mod[y-last x;32]}/)7h$trim x} ``` **Examples:** ``` q){"c"$({(x;x,y)1=mod[y-last x;32]}/)7h$trim x}"CodEgolf" "CdEf" q){"c"$({(x;x,y)1=mod[y-last x;32]}/)7h$trim x}" codeolfg" "cdefg" q){"c"$({(x;x,y)1=mod[y-last x;32]}/)7h$trim x}"ProgrammingPuzzles" "P" q){"c"$({(x;x,y)1=mod[y-last x;32]}/)7h$trim x}"The quick red fox jumped over the lazy brown dog" "Tuvw" ``` **Explanation:** Leveraging the `mod 32` trick from existing solutions along with [converge](http://code.kx.com/wiki/Reference/Slash) function. Iterate over the string, if the difference between the last element of the result (e.g. starts with `T` for "The quick red fox...") and the current character is 1 (after being `mod`'d with 32), then we add this to the result (hence taking why we take `last x`), then cast everything back to a string. ``` {10h$({(x;x,y)1=mod[y-last x;32]}/)7h$trim x} / the solution { } / lambda function trim x / trim whitespace (leading/trailing) 7h$ / cast string to ASCII (a -> 97) ({ }/) / converge y-last x / y is the next item in the list, x contains results so far 1=mod[ ;32] / is the result mod 32 equal to 1 (x;x,y) / if false, return x, if true return x concatenated with y 10h$ / cast back to characters ``` [Answer] # [Perl 5](https://www.perl.org/), 30 + 1 (-n) = 31 bytes ``` /$b/i&&(print,$b=++$_)for/\S/g ``` [Try it online!](https://tio.run/##K0gtyjH9/19fJUk/U01No6AoM69ERyXJVltbJV4zLb9IPyZYP/3//@R8l9T0fB@3f/kFJZn5ecX/dX1N9QwMDf7r5gEA "Perl 5 – Try It Online") **How?** ``` /$b/i # check if this letter equals the one in $b, ignore case &&(print, # output it if so $b=++$_) # store the next character to find for/\S/g # Looping over all non-whitespace characters ``` [Answer] # [Retina](https://github.com/m-ender/retina), 76 bytes ``` ^. $&$&$&¶ {T`@@L@l`@l@l@`..¶ T`l`L`.¶ (.)(.)((¶).*?(\1|\2)|¶.*) $5$5$5$4 ``` [Try it online!](https://tio.run/##HY29DoIwFEb3@xR3QAMMTTQ6izHExcFEJmNMC5TyU6hW8Ad5Lh6AF8Nizh1OzjdczeusYuPM3tMRAa4ErPnE0MM3oJ538CT1pIESYlpAJT3QyWziTGcPvUPcjX1ZdJel0w09cR2w1n9W4xipmAslE9ip2P8LTsmIgKNWQrOyzCpxbNpW8gecahYV6L@jlFWCQ5ByvDeZSZrHmKg35k15M6qeXGNtVsnaD4ZavSqMlYAzDzWDbRiZr0ma5YX8AQ "Retina – Try It Online") Link includes test cases. Explanation: ``` ``` Delete spaces. ``` ^. $&$&$&¶ ``` Triplicate the first character and insert a separator. ``` {T`@@L@l`@l@l@`..¶ T`l`L`.¶ ``` Convert the second and third characters to lower case and increment them. Convert the latter to upper case. These are now the search characters. ``` (.)(.)((¶).*?(\1|\2)|¶.*) $5$5$5$4 ``` Try to match either of the search characters. If found, then triplicate the match, which restarts the loop for the next search. Otherwise, just delete the search characters and the rest of the input. [Answer] # [8th](http://8th-dev.com/), 114 bytes **Code** ``` : z dup n:1+ 32 bor >r "" swap s:+ . ; : f s:trim 0 s:@ z ( nip dup 32 bor r@ n:= if rdrop z then ) s:each rdrop ; ``` **Explanation** ``` : z \ n -- (r: x) \ print letter and save on r-stack OR-bitwised ASCII code of following letter dup \ duplicate item on TOS n:1+ \ get ASCII code of the following letter 32 bor \ bitwise OR of ASCII code and 32 >r \ save result on r-stack "" swap s:+ . \ print letter ; : f \ s -- s:trim \ remove trailing whitespace 0 s:@ \ get 1st letter z \ print 1st letter and save on r-stack OR-bitwised ASCII code of following letter ( nip \ get rid of index dup \ duplicate item on TOS 32 bor \ bitwise OR of current ASCII code and 32 r@ \ get value stored on r-stack n:= \ compare values to see if letter is printable or not if rdrop \ clean r-stack z \ print letter and save on r-stack OR-bitwised ASCII code of following letter then ) s:each \ handle each character in string rdrop \ clean r-stack ; ``` **Example** ``` ok> " The quick red fox jumped over the lazy brown dog" f Tuvw ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~79~~ ~~78~~ ~~75~~ 70 bytes ``` c;f(char*s){for(c=0;*s;s++)*s^32&&!c|c==(*s|32)-1?c=32|putchar(*s):0;} ``` [Try it online!](https://tio.run/##lZFPa4MwGIfv/RSZh6IWodPbxI1RvAvtqYyB5p@2alyibWftZ3eJEFGKh@WUvL88T5I30KEQ9j30iQnTmNvCuhPGTRhsfVv4YrOxbPHtuev1C@xgEJi26DzXcl4/YOC5XdXUipJV623rP/oizkrTWt1XQI6KZ2VNTAMyhCnLCXDeAUSYfNWG5U/qciU9wjTkRHEzeMdQqOEdCkdY16fwDARKLzdQfSzV6JgsshFnlMdFkZU0ato2x0JJIi14jhdN@zqGZxDeZJdKipVlX2vNkC2ShxSDnyaTNMcIEHYDp6ao5JRdMAe1TPO4/QUJZ9cSIDY889Bcrtr@X37xIkec8FjZj1o9VBb3fyay25Sk2emcK2xYj/82TWeKR/8H "C (gcc) – Try It Online") [Answer] # [Proton](https://github.com/alexander-liao/proton), 59 bytes Port of the [Python 2 submission](https://codegolf.stackexchange.com/a/139416/59487). ``` s=>reduce((x,y)=>x+y*((ord(y)-ord(x[-1]))%32==1),s.strip()) ``` [Try it online!](https://tio.run/##FchJCoAwDADAr0hBSNygeo4fEU9dRBBT0grt66ueBiYIJ76rpxppFWcf4wDyUJDW3JcOgMVCwfEnb6PeEdtlJtI4xCkmOQMg1iDnncCDagxbx5c/1Lcv "Proton – Try It Online") [Answer] # Pyth, 15 bytes ``` eo,}r0NG_xQhNty ``` [Test suite](https://pyth.herokuapp.com/?code=eo%2C%7Dr0NG_xQhNty&test_suite=1&test_suite_input=%22codegolf%22%0A%22CodEgolf%22%0A%22+codeolfg%22%0A%22Stack+Exchange%22%0A%22Zebra%22%0A%22Abcdegfhijkl%22&debug=0) Unlike all of the other answers, this doesn't stick together the output, it generates all subsequences of the input, and then orders them to put the desired string at the end, and outputs it. [Answer] # J, partial solution I'm posting this for feedback and ideas for improvement more than anything else. It works, but doesn't handle the capitalization and space edge cases, and is already long for J. First a dyadic helper verb that tells you if the left and right args are alphabetically adjacent: ``` g=.(= <:)&(a.&i.) NB. could save one char with u: ``` Next a verb that removes the first element which is *not* part of an alphabetic streak starting from the first element: ``` f=.({~<^:3@>:@i.&0@(0,~2&(g/\))) ::] ``` Note we use Adverse `::` to return the entire argument unchanged if there is no non-streak element found (ie, if the entire argument is a valid alphabetic streak). Finally, the solution is given by applying `f` until convergence: ``` f^:_ 'codegolf' NB. => 'cdef' ``` [Try it online!](https://tio.run/##y/r/P91WT8NWwcZKU00jUU8tU0@TKw0oUl1nE2dl7GBn5ZCpp2bgoGGgU2ekppGuH6OpqalgZRXLlZqcka@QFmcVr6CenJ@Smp6fk6b@/z8A "J – Try It Online") --- And here is a parsed version of `f` for easier reading: ``` ┌─ ~ ─── { │ ┌─ < │ ┌─ ^: ─┴─ 3 │ ┌─ @ ─┴─ >: ┌───┤ ┌─ @ ─┴─ i. │ │ ┌─ & ─┴─ 0 │ │ │ │ └─ @ ─┤ ┌─ 0 ── :: ─┤ │ ├─ ~ ─── , │ └─────┤ │ │ ┌─ 2 │ └─ & ─┴─ \ ─── / ──── g └─ ] ``` **Side Question**: why do the box characters not align perfectly when display on SO (they work in my console): ![](https://i.stack.imgur.com/sSINT.png) ]
[Question] [ ## Background An **L-shape** is defined as a polyomino which can be made by extending two rectangular legs in orthogonal directions from a full square (called a pivot). The size of the square should be at least 1, and the lengths of the two legs should also be at least 1. These are some examples of L-shapes: ``` Pivot size 1, two leg lengths 2 and 4 # # ##### Pivot size 2, two leg lengths 1 and 3 ##### ##### ## ``` These are not: ``` Does not have two orthogonal nonempty legs #### The pivot is not a square ## #### One of the legs is not rectangular ##### #### ## ## Has three legs instead of two ##### ##### ## Has four legs instead of two # ####### # # Cannot identify a pivot and two legs ## ## Contains one or more holes ##### # ### ##### # # ### Is not a polyomino (the shape is disconnected) ## # # ## ``` ## Challenge Given a zero-one matrix, determine if the ones form a single L-shape. You should handle inputs containing any amount of margins on all four sides (including no-margin cases), and detect L-shapes in any of the four orientations. For example, the output must be True if the input is any of these: ``` 0 0 1 1 1 1 0 0 0 1 1 1 1 0 0 0 1 1 0 0 0 1 1 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` and False if given any of these: ``` 1 0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0 1 0 1 0 0 0 1 0 0 0 0 0 1 0 1 1 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 1 1 ``` You can choose any reasonable representation of a matrix, and you can assume that the input is always rectangular. You can also choose the two values to represent 0 and 1 respectively. For output, you can choose to 1. output truthy/falsy using your language's convention (swapping is allowed), or 2. use two distinct, fixed values to represent true (affirmative) or false (negative) respectively. Shortest code in bytes wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~31~~ ~~30~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ø‚O0δÚDWδåsεÔg<}Q ``` [Try it online](https://tio.run/##yy9OTMpM/f//8I5HDbP8Dc5tOTzLJRxILi0@t/XwlHSb2sD//6OjDXQMQTBWB4NlgMYCw9hYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDVel1aLcOl5J/aQlMzOX/4R2PGmb5G5zbcniWSziQXFp8buvhKek2tYH/dQ5ts/8fHR1tqGMAgbE6aGwojI3VUYhG4uqgsCEa4MqgHDA0gEpj40NsgWpBmIXKMkBjIWnCcBuKo3E7GaYI2ZeYxmL1JUQ7ki@xhBWKcoQ8Kh/hZpj/sFlugNUhhjCT4OKoJoKk4RGJEisGGMGJNWARJiDFL8wLMIsMUKQMccclvhiE6gBTsbEA). **Explanation:** ``` ø # Zip/transpose the (implicit) input-matrix, swapping rows/columns ‚ # Pair it together with the (implicit) input-matrix O # Take the sum of each row of both matrices # Remove any leading/trailing rows/columns of 0s: δ # Map over both the inner lists of row-sums: 0 Ú # And trim all leading/trailing 0s D # Duplicate it # Check if the pivot is a square: W # Get the flattened minimum (without popping) δ # Map over both lists of row-sums: å # And check if this minimum is present in the row-sums # (this will result in [1,1] if the minimum sum is present in both the # row-sums and column-sums, which means the pivot is a square) # Check if the matrix forms an L-shape: s # Swap so the duplicated pair of row-sums is at the top again ε # Map over both inner lists: Ô # Connected uniquify the sums g # Pop and push the length < # And decrease this by 1 } # Close the map # (this will result in [1,1] if the matrix forms an L-shape, which means # the lengths were 2 for both the row-sums and column-sums after the # connected uniquify) # Check that all four values are truthy: Q # Check if both pairs are equal # (after which the result is output implicitly) ``` NOTE: the `Q` would also incorrectly result in truthy if both pairs are \$[1,0]\$ for example, but there isn't any test case where both pairs would be the same apart from the truthy \$[1,1]\$ test cases. (If there were, we could have used `«P` - merge; check if all four are truthy - instead.) The reason why the pairs can never be the same except for the truthy test cases: 1. We check if the flattened minimum of the sums is present in both inner lists. Since we took the minimum from the lists, this can only ever result in \$[1,1]\$, \$[0,1]\$, or \$[1,0]\$ (this will also result in \$[1,1]\$ if the input-matrix is empty). 2. The `εÔg<}` will however not result in \$[1,1]\$ for empty matrices, nor will it ever result in \$[0,1]\$ or \$[1,0]\$. For either the sums of rows or columns to result in \$0\$, it would mean all values in those rows/columns are equal, but this implicitly means the same applies vice-versa and it's a rectangle matrix of the same values. The `εÔg<}` can only result in: * \$[-1,-1]\$: which meant the input was empty, or only contained \$0\$s ([try it online](https://tio.run/##yy9OTMpM/f//8I5HDbP8Dc5tOTzLJRxILi0@t/XwlHSbWqDw///RsQA)); * \$[0,0]\$: which meant the input-matrix was a rectangle of \$1\$s, after we've trimmed all leading/trailing \$0\$s ([try it online](https://tio.run/##yy9OTMpM/f//8I5HDbP8Dc5tOTzLJRxILi0@t/XwlHSbWqDw///R0QY6YBirA2QZAiE6CyIbCwA)); * \$[1,1]\$: our expected truthy result for L-shaped matrices ([try it online](https://tio.run/##yy9OTMpM/f//8I5HDbP8Dc5tOTzLJRxILi0@t/XwlHSbWqDw///R0QY6BjqGUGgQq4OTD6INYmMB)); * or larger than \$[1,1]\$ - i.e. \$[1,3]\$, \$[2,4]\$, etc.: if the input-matrix contained gaps in one or multiple of the rows/columns ([try it online](https://tio.run/##yy9OTMpM/f//8I5HDbP8Dc5tOTzLJRxILi0@t/XwlHSbWqDw///R0QY6BjqGsTrRhjqGYBrEN4DShrGxAA)). [Answer] # [J](http://jsoftware.com/), 51 48 79 bytes ``` (1-'10+1'rxin'012'{~2,@,.],|:)*1&#.(,~&{:-:,&(0{#/.~)+0{,)&(|.^:({.>{:)@-.&0)+/ ``` [Try it online!](https://tio.run/##hZBRS8MwFIXf8ysuXkhybXqX9jG1YyD45JOvojJkxY2hYvcgZPSv12aNa9F1C8mB5Hz3niSb9opVBaUDBQYsuG6lDLcP93etzlKV2SRTX9/rd2WzXPkmNwvDT2bv6DqTyNo00rvUGamtxxk3lFhvSOo9Pzvtee4dLVKWlpJZS0JUy/W25C7GCuyGOB4FhQKic8o0cHOsi0A/L2EoACaxzuqhHjusqYYg4FIcDKHYd57uFvwzN8PDbSAwgfhc1vXo5/DfA08pxbKgw@@O6@AvNcTH8KCIU1jwMeovtlvVu5L1owNdVARaoZIlFfySk@S5WL2@fUBgIHQabcPz2x8 "J – Try It Online") *+31 thanks to Bubbler for catching a bug not revealed by the original cases* **NOTE: All test cases are passing again when I run locally on j902, but this now fails on TIO due to a [J regex bug on linux/TIO](https://www.mail-archive.com/[email protected]/msg02071.html).** Consider the column and row sums of: ``` 11111 = 5 11111 = 5 00011 = 2 (count of 2s is 1) ----- 22233 (count of 2s is 3) ``` as well as the count of the smallest number in each: 2 in this case. The insight is: ``` 2 + (column count of 2s) = 5 2 + (row count of 2s) = 3 ``` and this fact is basically all you need to solve it. The rest is mechanics and likely the J could be golfed a bit more. I'll try to do that and improve this explanation tomorrow. [Answer] # [JavaScript (V8)](https://v8.dev/), 500 bytes Lots of golfing possible. ``` M=>{R=M.map(m=>m.join``);if(R.find(r=>r.match(/10+1/)))return;o = [];for(i=n=0;i<R[L="length"];i++)if((r=R[i]).includes`1`){if(n)return;n=0;o.push([r.indexOf`1`,r.lastIndexOf`1`])}else{if(o[L])n=1;else continue}if(o.every(r=>r[0]==o[0][0])){}else if(o.every(r=>r[1]==o[0][1]))o=o.map(r=>[R[0][L]-r[1],R[1][L]-r[0]]);else return;d=[];for(i=0;i<o[L];i++){if(o[i][1]!=(d[0]||0)[0])d.unshift([o[i][1],1]);else d[0][1]++}return d[L]== 2&&(d[0][1]==o[0][1]-o[0][0]+1||d[1][1]==o[o[L]-1][1]-o[o[L]-1][0]+1)} ``` [Try it online!](https://tio.run/##xVFda4MwFH3vr3B9KAl@1Oxp4NL3gWXgawgoNc4Um0jUslH727vEj66MMiwrm1wCOffcc06u22SfVBvFy9rdP50yfFrj1SHCa2@XlGCHVztvK7mIYxjwDERexkUKFF4p3a83OVgi30ZLCKFidaNEIC1sERpkUgGOBfYD/hyREM8LJt7qfE4DbttQK2mNiHAKPS42RZOyKkYxPOiGGJXMsPTKpsoBUZqWsvfXTLMc5RVJVb@cAQqPrKiYGZYkpFBgFBjA2khRc9Gwo@l4bM/URxed@BRjqU9dEB66aes7B40cpDkSy24fukMiA4bUNRQn0kd/8SmFve2QP8XnPZgtmGjd4/uc3Ag/YJDqwbb1oYmSeo2ocp7VgAwEB42iaR/Fto@9vAZCndB6XCzA0DvndYe32ahtUxOw75kELhoI48Ww4PFUKi5qkAEys/RHfMf6KuqcQXQL2NcleKE501udzX5pi/7CFv3Da9E124ngvW0n/o672vrXNv8DeLvtdIcpSz59Ag "JavaScript (V8) – Try It Online") Outputs truthy/falsy. Inputs as a multidimensional array of `0` and `1`. **Explanation:** 1. Join into rows, and do a regex to check for lines that have two vertical parts (`10+1`, which can't be `L` shapes) 2. Create a list of the first and last index of each `1` for every line containing a `1`, and return a falsy value immediately if there's a line with no `1`s between two that have ones (which can't be `L` shapes) 3. If the "stem" of the `L` is on the right, flip it horizontally 4. Make a list of each group of lines where the width of the `1`s is the same, and note its height 5. Check if there are two of these sections (i.e., ensure it's not a rectangle or an `E`/`F`/jagged thingy) 6. Check if the width of the stroke is the same horizontally and vertically **Ungolfed:** ``` f = (matrix) => { var rows = matrix.map(m => m.join("")); if (rows.find(r => r.match(/10+1/))) return false; var o = []; var n; for (var r, i = 0; i < rows.length; i++) { r = rows[i]; if (r.includes("1")) { if (n) return false; n = false; o.push([r.indexOf("1"), r.lastIndexOf("1")]); } else { if (o.length) n = true; else continue; } } if (o.every(r => r[0] == o[0][0])) { } else if (o.every(r => r[1] == o[0][1])) { o = o.map(r => [rows[0].length - r[1], rows[1].length - r[0]]); } else { return false; } var d = []; for (i = 0; i < o.length; i++) { if (o[i][1] != (d[0]||0)[0]) d.unshift([o[i][1], 1]); else d[0][1]++; } return d.length == 2 && (d[0][1] == o[0][1] - o[0][0] + 1 || d[1][1] == o[o.length - 1][1] - o[o.length - 1][0] + 1); } ``` ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 48 [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 tacit prefix function. Takes Boolean (0/1) matrix with 0s indicating the shape. Requires 0-based indexing. ``` {(=/⍵-⍥⍴e)∧i≡,e←(⊂∘⊃+∘⍳∘|1+⊃∘⌽-⊃)i←⍸⍵}1⍉⍤⌂deb⍣2⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXOlAsjrNFigAZDxqm/iod2vt/2oNW30gQ/dR79JHvVtSNR91LM981LlQJxWoRuNRV9OjjhmPupq1QVTvZiBZY6gN5IO4PXt1gSzNTJBhvTtAhhk@6u181LvkUU9TSmrSo97FRo@6Fv1PA8v3gTT1rgFacWi9McjuvqnBQc5AMsTDM/h/uoK6sjoUg4A6VzqMhaAVFBTgMlBhDHXqcEkcRkAlgAyYMEwCSsLNV0A3QwHVLGWYEVBVUCMxrYA4HWE8mKsAsQGZAgkCAA "APL (Dyalog Extended) – Try It Online") `0`…`⊢`⁠ with 0 as left argument and the unmodified argument as right argument:  …`⍣2` repeat twice   …`⍤⌂deb` **d**elete **e**nding (leading and trailing) **b**lanks (1s), then:    `⍉` transpose (so we end up deleting the top and bottom blank rows too) `{`…`}` apply the following lambda, with `⍵` representing its argument:  `⍸⍵` **i**ndices where there are 1s  `i←` save as `i`  `(`…`)` apply the following tacit function to that:   `⊃` the [index of the] first [blank]   …`-` subtract that from:    `⊃∘` the [index of the] first of the:     `⌽` reversed [indices of blanks, i.e. the index of the last blank]   `1+` increment that [to get inclusive range]   `∘|` take the absolute value of that [getting the absolute range], then:    `∘⍳` get the indices of that range, then:     …`+` add that to:      `⊂∘` the whole of…       `⊃` [index of the] first [blank, giving a matrix of indices of the entire supposed blank area]  `e←` save as `e`  `,` ravel into a list of indices  `i≡` identical to the actual list of indices of blanks?  `(`…`)∧` and…   `⍵`…`e` considering the argument and the matrix of supposed blanks…    `-⍥` are the differences in…     `⍴` shapes [between heights and widths]   `=/` equal? [i.e. does the height-difference match the width-difference?] [Answer] # JavaScript (ES6), ~~175~~ 166 bytes Expects a list of binary strings. ``` m=>m.map(M=r=>(M|=v='0b'+r|0,m&=v||~0,v),m=~0).map(v=>v?(b=v+(v&-v))&b-1?3:v^m?2^v<M:1:0).join``.match(`^0*(1+${s=(g=m=>m?2+g(m&m-1):'')(m)}|${s}1+)0*$`)&&M*2&M/2&m^m ``` [Try it online!](https://tio.run/##jVHBcoIwEL37FU7GCYmA3aU3ppFbb9x6szKgVdQh4IDNTKfor1NKK8Qpave0Sd6@t@9lF6moWObb/cFOs7dVtRaVFFM5kdGe@SIXU@aXQgkDFoaZl2BJKlRZnsBS3JLiBLxBKjFVHlsIZTJFbcU5XdjoPboqkJ4TqCffRbeG7rJtGob1xGG5YWEAY4bm6LMQLBbfop5jxkxSaSN3DYMzyY9l/XxEk8N4FHJK/bFD/QeHykBWyywtsmQ1SbKYkdlL/n7YfMwJH@j3azYbDIcEAOsCYvUeAIAM5rx3ska2wHNzHQ1NtTitR73HfgzcoW6XRs0AXpjpp7vgI6/p7DlKimtZ4U13v@Sd5IX49Rj19H72vuO1pe/y/48Q/I292xTx5k@DFmkDq74A "JavaScript (Node.js) – Try It Online") ## How? ### Step 1 We first convert the input matrix \$m[\:]\$ into a list of integers. At the same time, we compute the bit mask \$M\$ of all rows OR'd together and the bit mask \$m\$ of all non-empty rows AND'd together. ``` m.map(M = // start with M zero'ish r => // for each row r in m[]: ( M |= v = '0b' + r | 0, // turn r into an integer v by parsing it as binary // and update M by doing M = M OR v m &= v || ~0, // if v is not equal to 0, update m by doing m = m AND v v // yield v as the actual value for the map() ), // m = ~0 // start with all bits set in m ) // end of map() ``` If the shape is valid: * \$m\$ is the pattern for the vertical leg * \$M\$ is the pattern for the horizontal leg * the list returned by `map()` contains only \$m\$, \$M\$ and optional \$0\$'s **Example:** ``` input | bin -> dec | M | m -----------+------------+----+----- "0000000" | 0 | 0 | ~0 "0100000" | 32 | 32 | 32 "0100000" | 32 | 32 | 32 "0111110" | 62 | 62 | 32 "0000000" | 0 | 62 | 32 ``` ### Step 2 We convert the list into a string of digits, using \$0\$ for empty rows, \$1\$ for rows equal to \$m\$, \$2\$ for rows equal to \$M\$, or \$3\$ for invalid rows. ``` .map(v => // for each value v in the list: v ? // if v is not equal to 0: (b = v + (v & -v)) // if adding to v the least significant bit set in v & b - 1 ? // results in more than one bit set: 3 // this is an invalid row where at least one 0 // breaks a pattern of consecutive 1's : // else: v ^ m ? // if v is not equal to m: 2 ^ // yield 2 if v = M v < M // or yield 3 if v != M (invalid) : // else (v = m): 1 // yield 1 : // else (empty row): 0 // yield 0 ) // end of map() .join`` // join all digits ``` ### Step 3 We build a regular expression to test whether the string is valid. ``` .match( // test the resulting string: "^0*(" + // optional leading 0's // followed by either: "1+" + // one or several 1's ( s = // followed by as many 2's as the number of bits set ( g = m => // in m m ? // 2 + g(m & m - 1) // this string of 2's is computed with the recursive : // function g and saved in s '' // )(m) // ) + // "|" + // or: s + "1+" + // as many 2's as the number of bits set // in m, followed by one or several 1's ")0*$" // followed by optional trailing 0's ) // end of match() ``` ### Step 4 Finally, we make sure that \$m\$ and \$M\$ form a right angle. Either \$m\text{ AND }(M\times 2)\$ or \$m\text{ AND }\lfloor M/2\rfloor\$ must be different from \$m\$: ``` M * 2 & M / 2 & m ^ m ``` [Answer] # [Julia](http://julialang.org/), ~~175~~ 170 bytes ``` a->try r=rotr90 for _=1:4 while sum(a[1,:])<1 a=a[2:end,:]end a=r(a)end for _=1:4 a=r(a,a[end])end a[a[1]] while sum(a)>0 a[a[a[:,1],:]] a=a[2:end,2:end]end a[1]catch end ``` [Try it online!](https://tio.run/##jVLBboQgEL3zFUQPq4k1a9NLTdl7v4GShmy10ljcINttP6Cn/mV/xA6ggu5uUoKEefPmDePM27EVvPgcajLwm51WX0gR1Wl1v0V1p/AzKco7dGpEW@H@@J5wWmQlSx8KxAmnt2UlX8CGE2yV8NTcfJzFMk4BZdbFKQgwFgqmu62FOS2zgoEYC6Tt6eQhbs/1vkFgDbrqdY8JpiiKIhT//nzPe22ZBaTMMkOX58AX/xcza7yf7zmPpY3n7B2RiTc9KI6X8t7pVVwlYVXLnFeSnidbl@XoPmBd7xoLs4XPvvQQV09o@ZzX1OKpffY/IIbQa2KanUKzP6D/CX2UmgpCNvEGm0ETWEjcClkxZ5urgfpDK7QLZXmep8iOpbGN184PwrAOSkjdSsdcIGNiB/ZNd0rqGVsyoycZpXYu/wA "Julia 1.0 – Try It Online") returns `0` if L-shaped and `nothing` otherwise It's probably not the most efficient approch but I'm glad I could match the javascript answer **Ungolfed version** ``` function f(a) try # remove margins for _=1:4 while sum(a[1,:])<1 a=a[2:end,:] end a=rotr90(a) end # rotate `a[end]` times, meaning until a[end]==0 for _=1:4 a=rotr90(a,a[end]) end a[a[1]] # check that a[1]!=0, by erroring if a[1]==0 while sum(a)>0 a[a[1,:]] # check that first line and col are all ones a[a[:,1]] a=a[2:end,2:end] # remove first line an col end a[1] # check that a is not empty (errors if empty) catch nothing end end ``` [Try it online!](https://tio.run/##jVNLbuMwDN3rFKy9qA0YQVx002Dcfc/gMVqNK8easaVAYtrJAbrqLXuRjD7xR06CDuGfHp/4SIr@ve84zf8ej81e1MilgCahKQFjqA7ubS0GxXr5xqCnasuFHh2NVPBc5Jv7EbH23vKOgd73CS3zbFOlP/LAb40WtLzbMPFq/IHTQCQkKonqYT3kNXDmyUmkyOCFlsZRvQDynukMekYFF1vYC@QdeGdRrL9JftLL/JZQdqSVpraqMup1y@o/gC1FsNBNsc7g1wGYUlJZed44fK5MLnQqfVyHeZS@eQuJhiuN0HHBgIpXqKWpTJnvrgMpmD4LsclMluRy592zmk43iG1DX6k8X5YNXIOQCKzf4QESV7q2hTvAN7CmWLdjEMNuTXPIENzcR2QaNRRQkiiKSPz1@TFey5U1Q8occ@6aOOaO/xezdvo@v0YdRzs9R@8JGXhDQnEchp@cUxRfybyqUPOK6LnYsixPnzYs611ic7V52pcS8fXMV5PmtWjxcHyuD6QiZJvYw07NYb@ZuUjKJ4ElL4rb@Nb9lRy4cHNY@bUbSQPpXcfRb61Wq1VKiPXatfW6@XETtTM/HnbCMwPkJOxB3cr3pBmxkBn9FFHq5vIf "Julia 1.0 – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 44 bytes thanks @Adám [for the `⍸⍣¯1` trick](https://chat.stackexchange.com/transcript/message/56895801#56895801) ``` (⊂a)∊(⍉¨⊢,⌽¨)⍣2≥∘i¨⍳⌈/,i←⌊/↑⍳⍴a←⍸⍣¯1(⊢-⌊/)⍸⎕ ``` [Try it online!](https://tio.run/##VU/BSsNQELznK95tE0zpW48evPcbxEOwRILBlJBLKb2oxCT2BYsUvAhaEXrzoAUReumn7I/E3aSp6YNk2ZnZ2VlvFPaGYy@MLisqF0FE6aO2KLv3K5uKG8@hrLDJ5NsVFUuXZpvtyiHzfkz5B2XPAcPmi2ZZ3w14kGZFn9K5QObbE8D8sHj7iey17AntCFQuKt5g@bWiRHaF6QRcYEK@GMisgRcjpU/cX8TggyLzksTe0L/unfLP4kHY2zdT9sCRqf@Jhzs14B2TWI7iSGRWeETFrQTmFczHZ1zPmUZpprJkb6pGUTj2gzCsEjEh80v5m1j5fExzXcn3p3NQYFP@SkXKBB@4PoHoCtgQfC8IwVPx1MIEtEZ@WnWr1hqEY0B61fa6fmpfcFewC@qOWgyx8cXW/kCmExdQCjRwLWl1NY7NfoW7XteBdsk6On2QqnbBdqYOKD38AQ "APL (Dyalog Unicode) – Try It Online") `⍸⍣¯1(⊢-⌊/)⍸` trim surrounding 0s `≥∘i¨⍳⌈/,i←⌊/↑⍳⍴a` generate L-shapes `(⍉¨⊢,⌽¨)⍣2` add reflections `(⊂a)∊` test if the (trimmed) input is among them [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 104 bytes ``` {i←0⋄{(~×/1=,⍵)∧(⍴⍵)≡+/¨1⌷¨(⍉⍵)⍵}⌽∘⍉⍣{(~⊃⌽⊖⍺)∨i=4⊣i+←1}{×≢⍵:⍵⋄,0}p∧⌿⍵∧/⍨p←⌊/0~⍨+/⍵}{(¯1+⌊⌿c)↓⍵↑⍨⌈⌿c←↑⍸⍵} ``` [Try it online!](https://tio.run/##dU7NSsNAEL77FAs9bEIakqAnIScverW@QFEaAgVzlSW9tIQkZosiWq/aQ3MQerEoggjpm8yLxJnNJqLFhd2d72e@mWE0ti@uhuPLoK5FCMmNC9czYUy2C8fz@yA3JqQrA@SrKrMny6lKD4q3qkQyU6TcxFB8QvqoiCU2Qz4lJn8A@YH9ZegfQL4MLYz3YrFdQPaMXYd4cVjfjSOcAcUX4XTlgCwjdEKRO@4EgeXQCGFUa89CEo3nJiR35E5uUYciJY5aCL@Tux4RlHPaRL7g@tV6n9T5/eD0CN@z45NBHaBHIGg7aZsGco6lwW3b5rh4w414j/uNz2TxXsAQ60uHK0ZVPz9jrFM0vePjnfhPhBawaOlW0G@Xz/5msN9ZvTZCu3Tk7ohmdR3/DQ "APL (Dyalog Unicode) – Try It Online") A train of two dfns which takes a matrix of 0's and 1's as argument. Can be simplified a lot using Jonah's idea. It simplifies the matrix like so: ``` ##### ##### → #### ## # ``` rotates it to put the corner at the top left: ``` ## # # # ``` and then checks if the first row and first column match its shape. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 112 bytes ``` ^\s+¶|¶\s+$ /^( .*¶)+ .*$/+m`^ /^(.* ¶)+.* $/+m` $ /^#* /&G^` /(?m)^ /&V` /^##+(¶#.*)+/+`^#+¶#|(¶)# $1 ^\s+$ ``` [Try it online!](https://tio.run/##bVDBTuMwEL3PV4zkCCUNalTYExcOIAGn5bDiskuIRaZNpMRTYhdUxHflA/JjZWw3WrRLInuSp/fezLyBXGv06lCkl31W/kY1jY@5lMekeErvq2V@KP/YfBo/plFqAlCUKS4X05jlUpIi76sSA7pcoEelBBQDVy2wOLkpK4j@8vNQeVjl6TSq5SLLi7wqlTRQH4JkCpIV@I7J4XDfvrJD274Trk7RvTF2tJFjNq6xeIba1PgDlH/9A/BFcPa/YBUE50dyvBHRC381ZAn1QGjYXQBcM1n/iY1@pWDEg2t4w0Z3ghvqt27vzS3EzmKA29C9jUKN9mUnhnBsBfDTEPIanTC9cCYO9Oy02ew6PXyZLMoAbrUVxUCzxlhHug4@b/zPJjN/zbvhW7pQIjnSw4ErbfwYbU3Gteu9DB738FkdE/RLQrC/YuO0uCL7ZQbsWSJruCM7z4J/J1KxHcDdHMmWuz33rWFMfQy20VvyOdStfWZjJAmqM9GEQf1Cnw "Retina – Try It Online") Link includes test suite with header that extracts the `#`-based test cases from the input and automatically right-pads them. Explanation: ``` ^\s+¶|¶\s+$ /^( .*¶)+ .*$/+m`^ /^(.* ¶)+.* $/+m` $ ``` Remove any margins. Annoyingly, this costs almost 50% of the code size. ``` /^#* /&G^` ``` If the first line contains a space then reverse the rows. ``` /(?m)^ /&V` ``` If the first column contains a space then reverse each line. ``` /^##+(¶#.*)+/+` ``` Repeat while the there are at least two rows and columns of which the first of each only contains `#`s... ``` ^#+¶#|(¶)# $1 ``` ... completely delete the first row and column. ``` ^\s+$ ``` Check that the entire `L` was deleted. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~107~~ ~~105~~ ~~101~~ 100 bytes ``` FreeQ[#|r/@#,#|r@#&@{z={y=0...}...,d:{a:y,o=1..,b:o,y}..,{a:y,b:o,y}..,z}/;+b==Length@!d]& r=Reverse ``` [Try it online!](https://tio.run/##fVA9D4IwEN35FRoSFi/YrpgmXXRy8GMkDBWrMAhJJSZQy1/HgshXDbk01/fucvfuPVgW8QfL4pBVN1LtBOdH336LNbVBJ2o7VBZE5gS5rqv0g6snmZdDSrAGFy@FXNPQcB0q1HqzuhCy58k9i@jyGjiWICf@4uLJq4OIk4ze/G0YpXpP4JTnkCWltKREgAC3gRRYixmmzkhpSsqm3Be7X1tG0EVfmmBsYDzbj8BY0EvEE8n4zwkzA@uLRsrbpuEAY9jPifH93@1ToYMZeOiAYZdp0EjAzyRlqeoD "Wolfram Language (Mathematica) – Try It Online") The pattern identifies a vertically reflected L shape. Reversing it checks for another vertical reflection (upright); `#|r/@#` checks for horizontal reflection. ``` { (* L pattern: *) z={y=0...}..., (* zero or more leading zero-lines, followed by *) d:{a:y,o=1..,b:o,y}.., (* a column of 1s, wider than *) {a:y,b:o,y}.., (* another column of 1s, left-aligned with the first column, *) z (* and zero or more trailing zero-lines, *) }/;+b==Length@!d (* such that the width of the second column is equal to the height of the first. *) ``` [Answer] # [Python 3.9](https://www.python.org/downloads/release/python-391/) + [NumPy](https://numpy.org/), 167 bytes ``` lambda a:min(c:=(a:=a[[slice(min(i),max(i)+1)for i in a.nonzero()]]).sum(0))-min(r:=a.sum(1))|len(c)-max(r)|sum((a[:-1]^a[1:]).any(1))*sum((a[:,:-1]^a[:,1:]).any(0))-1 ``` Expected input is a 2D numpy array of 0/1 (or False/True) values. Returns falsey for L shape, truthy for not L shape. Explanation: First remove the "margin" / 0 column and row vectors around the input if there is any. Then for both axes: * Check that the row/column vector only changes once when going along that axis (this ensures that there are only 2 unique ones (one for the leg parallel, and one for the leg perpendicular), and these are all next to each other) * Take the sum along the axis. There should only be 2 unique values. The smaller one is the width of the leg perpendicular to the axis. Check that the two widths are the same Then check that the width of both legs is the same And then check that the length of one of the legs is the entire length of the array Ungolfed + test runner (since TIO doesn't have numpy): ``` def is_L_shape(a): # Remove zero vectors surrounding a a = a[tuple(slice(min(i), max(i)+1) for i in a.nonzero())] # Check columns have L-like sums col_sums = a.sum(0) col_width = min(col_sums) cols_in_order = sum(~(a[:,:-1]==a[:,1:]).all(0)) == 1 # Only one column should be different from the next # Check rows have L-like sums row_sums = a.sum(1) row_width = min(row_sums) rows_in_order = sum(~(a[:-1]==a[1:]).all(1)) == 1 # Only one row should be different from the next # Check that the legs span the entire column/row col_correct_length = col_sums.max() == len(row_sums) # row_correct_length = row_sums.max() == len(col_sums) return col_width == row_width and col_correct_length and cols_in_order and rows_in_order # Test runner f = \ lambda a:... def run_test(s): import numpy as np s = s.strip('\n') if s.endswith('!'): s = s[:-1] a = np.row_stack([np.array(list(map(ord, line))) for line in s.split('!\n')]) == ord('#') is_L = not f(a) print(np.array(a, dtype=int), 'is an L' if is_L else 'is not an L', 'as expected' if bool(is_L) == bool(expected) else '(failure)' + '!\n'*20, end='\n\n') expected = True run_test(''' # ! # ! #####! ''') run_test(''' #####! #####! ##! ''') run_test(''' #### ! #### ! ## ! ''') run_test(''' ###! #! ! ''') run_test(''' ! ! # ! ## ! ! ! ''') run_test(''' ## ! ##### ! ##### ! ! ! ''') expected = False run_test(''' ####! ''') run_test(''' ## ! ####! ''') run_test(''' #####! #### ! ## ! ## ! ''') run_test(''' #####! #####! ## ! ''') run_test(''' # ! #######! # ! # ! ''') run_test(''' ## ! ##! ''') run_test(''' #####! # ###! #####! # # ! ### ! ''') run_test(''' ## #! # ##! ''') run_test(''' ! ## ! ## ! ! ''') run_test(''' # #! ! # ! ''') run_test(''' ! # ! #### ! ''') run_test(''' ###! # #! ## ! ''') run_test(''' ###! ! ###! ## ! ## ! ''') run_test(''' ### ! ### ! ### ! #! #! ''') run_test(''' ## ! ## ! #! ''') run_test(''' ## ! ## ! #! #! ''') run_test(''' #########! #########! ''') run_test(''' #! ''') run_test(''' ###! ''') ``` [Answer] # [Perl 5 (cperl)](http://perl11.org/cperl/), 338 bytes ``` sub L{($w,$h,$v,$m)=@_;join$/,map{$x=$_;join'',map$_<=$w|($m?$x>$h-$w:$x<=$w)|0,1..$v}1..$h} sub r{my($i,@r);map/\n/?($i=0):$r[$i++]=~s/^/$_/,pop()=~/./gs;join$/,@r} sub d{my$_=pop;/.*/;length$&,0+split$/} sub f{$s=pop;map$s=r($s)=~s,^(0+\n)+,,r,1..4;@m=map{$m=$_;map$m=r($m),1..4}map{L(@L=($_,d($s))),L(@L,1)}1..min(d($s))-1;grep/$s/,@m} ``` [Try it online!](https://tio.run/##bVHBctsgEL3zFTSzUwsLG5hpL5ZJdMmpbnNJT3HicRvZppWQBpTYHcf59LoLisZJWw7Avn379i00hSs/jr43eBxtTbdLZ41dezoodoiZqrDtshxkJG/dQ6F9U5pWzO3cCj6dXmZESoVLvjmllIRgFAISAxnX6VAvh3oNyp4adFQnp3rVvzjqddd/Lr26OhXh5ZKQfLUs/X@mUOg3bmiadK2iWN8bMy@jqN5jSMYJe4Z8M10sjvORuIcgOmgL3@qE0qRaNvQGFvpc3XIaX5dxQvt1SsuQjr4ZpSwjq9olUYXtkZ6AsQ0H/Cymc1hkCMG6bvUqJliIG2dsS9MUDEc6JumudjSW0At6RofD4Zera3r16d3cntEJIvVPvGXkcPQP3@hsn8CWw4bDI4cKuyyyH7WxIDha3MNOQwcMBgGAxVTD9imB6gJ257AZwXYCu4CxJ8nVeAyPh7BvDiSIu331C53y3LEMq/FPxAXGWrIJuBswaXqrn724E7AQvKmbhOlnMRZr33vIXSd0j0L4WkjJxHgosrKw63YD77lM42@D6HirPfjICl69dgl4lPT8LpHp3LKUcxdcfsjySsf5qjBfIFeBXLGYPYTULMlnOoEFvw8ijPEAcMXCfJWxSQePVLZ2RSPAo9nqcDz@rpvW1NYfR59nxreTydfWlBoL/gA "Perl 5 (cperl) – Try It Online") Creates all possible L's with all possible rotations and mirrors up to the dimensions of the input (with all 0-margins shaved off). Sees if any of those L's is equal to the shaved input. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 69 bytes ``` FLθFL§θ⁰F⌊⟦ικ⟧F⁻ιλF⁻κλF²F²⁼θEθEρ¬∨∨∨‹ςμ›ςι∨‹τν›τκ‹λ⌊⟦⎇π⁻ςμ⁻ις⎇ξ⁻τν⁻κτ ``` [Try it online!](https://tio.run/##jZA/D8IgEMV3P8WNR4JJdXVyMMbEf4Nbw0AUlZRSe6WNfnqkKhU3ySXw3g9e7jheJR0rabw/VwS4VvbirlgzBqmeu5U9qTvWHDIW2UZbXbYl5ppDIRK3bTBY5tcpEmf63fekrcNF3UrT9PEbeYsbcdhWDnf0qbVqGuw4lIzDkpR0inqpWdAROw42wUEWrOcvaEJu7PmgyEp64O3ltUPw0H7XP4u37hF88oeRHGNh8veaeZ/neRa@iMMkqUzwEcB/4H3OhBB@3Jkn "Charcoal – Try It Online") Link is to verbose version of code. Works by enumerating all possible `L` shapes on the original grid looking for a match. So many nested loops, I've actually used the `t` variable for the first time ever. This is an important milestone, since there are no trivial loop variables left. Outputs a Charcoal boolean, i.e. `-` if the shape was an `L`, nothing if not. Explanation: ``` FLθFL§θ⁰ ``` Loop over all potential bottom right corners of the rectangle enclosing the `L` shape. (Zero values will be trivially excluded as there won't be room for a pivot.) ``` F⌊⟦ικ⟧ ``` Loop over all potential pivot sizes. (Obviously there must be room for the pivot in both dimensions as it is square.) ``` F⁻ιλF⁻κλ ``` Loop over all potential top left corners of the enclosing rectangle. ``` F²F² ``` Loop over all orientations of the `L` within the rectangle. ``` ⁼θEθEρ¬∨∨∨‹ςμ›ςι∨‹τν›τκ‹λ⌊⟦⎇π⁻ςμ⁻ις⎇ξ⁻τν⁻κτ ``` Recreate the `L` based on the specification, eliminating all points `(v, t)` outside the rectangle `(m, n) - (i, k)` (inclusive) but also all points which are more than `l` away from at least one of the appropriate adjacent edges for the given orientation, and see if that equals the original input. Here is an example of an enumerated `L` shape. In this figure, `i` is `5`, `k` is `11`, `l` is `3`, `m` is `2`, `n` is `5`, and `p` is `1` (for top) and `x` is `0` (for right) for the position of the pivot. ``` +-----n-----k | | m ----+++ | ----+++ | ----+++ i ||| ``` [Answer] # Scala, ~~249~~ ~~185~~ 180 bytes ``` Seq.iterate(_,8)(_.transpose.map(_.reverse)dropWhile(!_.toSet(1)))drop 4 exists{m=>Set(m,m.transpose).flatMap(_.dropWhile(!_.toSet(0)).map(_.reverse.dropWhile(_<1)).toSet).size==1} ``` [Try it online!](https://scastie.scala-lang.org/Z9gMhLMEQ42mufvdLTTTyA) This is shamefully long. It takes a `List[List[Int]]` as input (even though the type is `Seq[Seq[Int]] => Boolean`). The result is a `Boolean`. ## Explanation Then we make a `Seq` of length 8 by repeatedly rotating the matrix clockwise (`t(_)map(_.reverse)`) and then dropping empty rows at the beginning (`dropWhile(!_.toSet(1))`). ``` Seq.iterate(_, 8)(t(_)map(_.reverse)dropWhile(!_.toSet(1))) ``` Just applying it 4 times would be enough to trim on all sides, but we also want all orientations. We first `drop 4` so only trimmed matrices remain. Then we use `exists` to check if any of them meet a certain condition. However, this function won't work for all orientations, it'll only work for upside-down L's (that's why all 4 orientations were generated): ``` ##### ##### ## ``` First, we make a `Set` out of `m` and its transpose, and for both of them, we drop the rows at the start that only contain `#`'s. For the rest of the rows in both, we reverse them and strip leading zeroes, then deduplicate them using `toSet`. The results for both `m` and its transpose are combined because we used `flatMap`, and then we make sure there is exactly one element. Thus, we eliminate legless shapes (less than one element) and shapes with extraneous `#`'s (more than one element). ]
[Question] [ The [Xerox Alto](https://history-computer.com/ModernComputer/Personal/Alto.html), originally released in 1973, was the [first](https://arstechnica.com/features/2005/05/gui/3/) computer to feature the now-familiar angled mouse pointer. The Alto's bitmapped pointer looked like this (redrawn from Fig. 2 [here](http://bitsavers.trailing-edge.com/pdf/xerox/parc/techReports/VLSI-81-1_The_Optical_Mouse.pdf)): [![enter image description here](https://i.stack.imgur.com/sEyuYm.png)](https://i.stack.imgur.com/sEyuYm.png) Your task in this [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge is to write a program/function that generates an ASCII art representation of the mouse pointer pictured above. Rules: 1. Input is a positive integer \$n\$, which is a scaling factor for the output. 2. Represent each black pixel as an \$n\times{}n\$ block of any single printable character. (The test cases use `@`, which vaguely resembles a mouse viewed from above.) 3. Similarly, represent each empty pixel to the bottom/left of the pointer as an \$n\times{}n\$ block of a second printable character. (Spaces are used in the test cases.) 4. Optionally, your output may also include the empty pixels to the top/right of the pointer, represented by the same character chosen under Rule 3. 5. Any sensible output format (e.g. multi-line string, array of strings, matrix of characters) is acceptable. 6. A single trailing newline at the end of the output is permitted. ### Test cases \$n = 1\$ ``` @ @@ @@@ @@@@ @@@@@ @@@@@@ @@@@@@@ @@@@ @@ @@ @ @@ @@ @@ @@ @@ @@ @@ ``` \$n = 2\$ ``` @@ @@ @@@@ @@@@ @@@@@@ @@@@@@ @@@@@@@@ @@@@@@@@ @@@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@ @@@@@@@@ @@@@ @@@@ @@@@ @@@@ @@ @@@@ @@ @@@@ @@@@ @@@@ @@@@ @@@@ @@@@ @@@@ @@@@ @@@@ @@@@ @@@@ @@@@ @@@@ ``` \$n = 3\$ ``` @@@ @@@ @@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@@@@ @@@@@@@@@ @@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@ @@@@@@ @@@ @@@@@@ @@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ @@@@@@ ``` [Answer] # JavaScript (ES6), ~~92 91~~ 90 bytes *Saved 1 byte thanks to @Neil* Returns a string with \$0\$'s for transparent pixels and \$1\$'s for black pixels. ``` n=>(g=k=>--k?(x=k/n%8,y=k/n/n/8,(~1<<(y>9?y-9:13-y)|3<<y/2)>>x&1)+[` `[x]]+g(k):1)(n*n<<7) ``` [Try it online!](https://tio.run/##FcVLDoIwEADQPaeYjTJjqaSyELUtB0ESiAJRyNSIMTR@ro6Yt3jX6lkNp/vl9pDszvXUmImNxdZ0xkrZZTiaLuZFGvn/szTCr9Iavd1lXu72KpGe3onWPt6QteNSkcjLoMzHohAtdrRXhLxirbc0Ne6ODAbUARi0gWReCIJXAHByPLi@XveuxQaZQEB45JAOwWf6AQ "JavaScript (Node.js) – Try It Online") or [Try it with the characters used in the challenge](https://tio.run/##FcrLDoIwEEDRPV8xG2XGUkhl4aut/geSSBCIQqYGjaHx8euIuYuzudfiWdzL/nJ7SHbnaqzNyMZiY1pjpWz3OJg24dk68n@n1hF@ldbo7Wbv5WarUunpnWrtkyVZO8wViewUnLIhz0WDLW0VIS9Y6xWNteuRwYDaAYM2kE4KQfAKAErHd9dVcecarJEp7qtbV5QVJnHSRNNvLIRwCDPOCQSERw5pF3zGHw) for easier comparison ### How? Given the scaling factor \$n\$ as input, we output the bit \$\lfloor x\rfloor\bmod 8\$ of the bitmask corresponding to the row \$\lfloor y\rfloor\$ for each \$k\$, \$0\le k <128\times n^2\$, with \$x=k/n\$ and \$y=k/(8\times n^2)\$. To generate the bitmask of a given row, we use two small expressions whose results are OR'd together. Only the 8 least significant bits are shown below. The other ones are ignored anyway. ``` floor(y) -> A(y) OR B(y) = result 15 10000000 10000000 10000000 with: 14 11000000 10000000 11000000 13 11100000 11000000 11100000 A(y) = ~1 << (y > 9 ? y - 9 : 13 - y) 12 11110000 11000000 11110000 B(y) = 3 << y / 2 11 11111000 01100000 11111000 10 11111100 01100000 11111100 9 11111110 00110000 11111110 8 11100000 00110000 11110000 7 11000000 00011000 11011000 6 10000000 00011000 10011000 5 00000000 00001100 00001100 4 00000000 00001100 00001100 3 00000000 00000110 00000110 2 00000000 00000110 00000110 1 00000000 00000011 00000011 0 00000000 00000011 00000011 ``` A linefeed is appended to the output whenever \$k/n\$ is a multiple of \$8\$. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~33~~ 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •4CîιZ›ÚAôçè~]ß4ÿ•Ƶāвε2в¦I×JIF= ``` Outputs with `1` for `@` and `0` for spaces. -1 byte by not outputting trailing `0`/spaces. [Try it online](https://tio.run/##AUkAtv9vc2FiaWX//@KAojRDw67OuVrigLrDmkHDtMOnw6h@XcOfNMO/4oCixrXEgdCyzrUy0LLCpknDl0pJRj3//zP/LS1uby1sYXp5) or [verify all test cases](https://tio.run/##yy9OTMpM/W/iquSZV1BaYqWgZO93aKUOl5J/aQmEr/P/UcMiE@fD687tjHrUsOvwLMfDWw4vP7yiLvbwfJPD@4GSx7Yeabyw6dxWowubDi07tO7wdK9D69xs/9fWHtpm//@/rm5evm5OYlUlAA). **Explanation:** ``` •4CîιZ›ÚAôçè~]ß4ÿ• # Push compressed integer 5077310163681960509504474007720499199 Ƶā # Push compressed integer 260 в # Convert the larger integer to base-260 as list: # [3,7,15,31,63,127,255,31,59,51,67,67,131,131,259,259] ε # Foreach over the integers in this list: 2в # Convert it to a binary-list ¦ # Remove the leading 1 I× # Repeat each character the input amount of times J # Join it together to a single string IF # Inner loop the input amount of times: = # Print the line with trailing newline (without popping the string) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•4CîιZ›ÚAôçè~]ß4ÿ•` is `5077310163681960509504474007720499199`; `Ƶā` is `260`; and `•4CîιZ›ÚAôçè~]ß4ÿ•Ƶāв` is `[3,7,15,31,63,127,255,31,59,51,67,67,131,131,259,259]`. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 31 bytes ``` {⍵/⍵⌿⌽⍉⊤⎕AV⍳'⍞§):┼|¨:┴│⍫⍫⍀⍀¢¢'} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/6sf9W7VB@JHPfsf9ex91Nv5qGsJUNYx7FHvZvVHvfMOLde0ejRlT82hFUBqy6MpTY96V4NRAxAdWnRokXrt/zSgSY96@x51NR9ab/yobSJQf3CQM5AM8fAM/p@mYMQFAA "APL (Dyalog Extended) – Try It Online") I guess this is the best APLers can do for now. Outputs a numeric matrix of zeros and ones, as per the [clarification](https://codegolf.stackexchange.com/questions/211641/cat-a-mouse-ascii-art-pointers#comment498312_211641). Basically the same approach as [Razetime's answer](https://codegolf.stackexchange.com/a/211644/78410), using `⎕IO←0` to avoid unprintables. ~~Hey, it tied with Jelly AND 05AB1E!~~ Almost... [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 41 bytes ``` {⎕A[1+⍵/⍵⌿⍉⊤(⎕AV⍳'⌷⊤└¶⍝ ⎕¶"í'),2/12 6 3]} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR31THaEPtR71b9YH4Uc/@R72dj7qWaIDEwx71blZ/1LMdyH80ZcqhbY965x5aAJQ4tE3p8Fp1TR0jfUMjBTMF49ja/2mP2iY86u171NX8qHfNo94th9YbP2qbCFQbHOQMJEM8PIP/pykYcQEA "APL (Dyalog Extended) – Try It Online") Letter `B` for colored pixels, `A` for transparent pixels. Uses an [APL tip from Andriy Makukha](https://codegolf.stackexchange.com/a/206779/80214) to compress integers. ## Explanation ``` {⎕A[1+⍵/⍵⌿⍉⊤(⎕AV⍳'⌷⊤└¶⍝ ⎕¶"í'),2/12 6 3]} ⍵ → n 2/12 6 3 12, 6 and 3 repeated in place '⌷⊤└¶⍝ ⎕¶"í' String of compressed values (⎕AV⍳ ) The SBCS codepoints of the string , Join them ⍉⊤ convert to binary & transpose ⍵/⍵⌿ replicate each element n times along both axes 1+ Add 1 to each for getting 1-based indices ⎕A[ ] Index the grid into the alphabet ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes White pixels are represented by `0`, black pixels by `1`. ``` •ˆ‰₃%ʒ„úVð“£Xfóó”•b8ôεSI×JIF= ``` [Try it online!](https://tio.run/##AUoAtf9vc2FiaWX//@KAosuG4oCw4oKDJcqS4oCew7pWw7DigJzCo1hmw7PDs@KAneKAomI4w7TOtVNJw5dKSUY9//8z/y0tbm8tbGF6eQ "05AB1E – Try It Online") **Commented**: The `IF=` part is taken from [Kevin's answer](https://codegolf.stackexchange.com/a/211642/64121). ``` •ˆ‰₃%ʒ„úVð“£Xfóó”• # long compressed integer, encodes the 16x8 cursor b # convert to binary 8ô # split into chunks of 8 digits (rows) ε # map over the rows ... S # split into characters I× # multiply each with the input J # join into a single string I # push the input F # for loop in the range [0, input) = # print row without popping ``` --- # [05AB1E](https://github.com/Adriandmen/05AB1E), 27 bytes This generates the first seven lines more manually but has some inconsistent spacing. If `X7L×` is replace by `₁7LRo-b`, the spacing is consistent again at 30 bytes. ``` X7LוùΛh‡Wgÿ™Œ•b8ô«εSI×JIF= ``` [Try it online!](https://tio.run/##AUMAvP9vc2FiaWX//1g3TMOX4oCiw7nOm2jigKFXZ8O/4oSixZLigKJiOMO0wqvOtVNJw5dKSUY9/8K7/zL/LS1uby1sYXp5 "05AB1E – Try It Online") --- # [05AB1E](https://github.com/Adriandmen/05AB1E), 31 bytes Same output format, uses run length encoding. ``` TÞ•€¶àĆαL0šDž¬тq•8вÅΓ8ôεSI×JIF= ``` [Try it online!](https://tio.run/##AUkAtv9vc2FiaWX//1TDnuKAouKCrMK2w6DEhs6xTDDFoUTFvsKs0YJx4oCiONCyw4XOkzjDtM61U0nDl0pJRj3//zL/LS1uby1sYXp5 "05AB1E – Try It Online") **Commented**: ``` T # push 10 Þ # cycle indefinitely # produces 10101..., the characters used for RLE •€...q•8в # compressed list of lengths [1,7,2,6,3,5,4,4,5,3,6,2,7,1,4,4,2,1,2,3,1,2,2,7,2,6,2,7,2,6,2,7,2,6,2] ÅΓ # run length decode 8ô # split into chunks of 8 εSI×JIF= # the same as above ``` [Answer] # [Perl 5](https://www.perl.org/) + `-a -M5.10.0`, 66 bytes Outputs `1` for black and `0` for empty pixels. **Note**: This script utilises unprintables, which are represented using escapes below. [Verification for 66 bytes.](https://tio.run/##jc7BTsMwDAbg@57iV4QQoDVznczJ2IQQB248RJclMDHWqt1gPH1JoRcEh/lg2Y79Keuqe@n702mDooXe7pvjQR@2Ne7wVh@7WDT1dn@IrW52y8lHQBH@mTex3aGoUDzNdUma/qxgtVqhPHeRl31PY9zCGU7gOCTLAueZYckKmPNMnMzBISd0Mz27uDyp@0c1e47TOPkRysEQKSEhXzqTK7cw63zufE6WYCU/iEgC3qud6qrPpfpmUj0aPBjMBDeXCEeDZmQw2MOyydCCq6ENQIvjvqnCq7p68Nc3ajoaJht5nRAoEhIljxRSzNXGY@EpgAIJSMgASv@O0bDZIJN/e05o9QU) ``` s/./$&x"@F"/ge,eval"say;"x"@F"for unpack"(B8)*","................" ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX09fRa1CycFNST89VSe1LDFHqTix0loJLJSWX6RQmleQmJytpOFkoamlpKMUU2FhEFORDMSpQJwGwhZAnAzEqRB@CpBvCcQGyVBsBsXGIKz0/78hlxGX8b/8gpLM/Lzi/7qJ/3V9TfUMDfQMAA "Perl 5 – Try It Online") ## Explanation Using `-a` the input number is stored (as the only index) in `@F`, which can be interpolated into a string (`"@F"`) saving one byte over using `$F[0]` notation, to control the repetition of characters and lines, as using `-n` would only store the number in `$_`, which is overwritten in the body of the `for`. The string at the end represents the binary data for black or empty pixels which is `unpack`ed in lengths of `8`. In the body of the postfix `for` loop, each block of 8 bits, represented as a string of `0`s and `1`s, is stored in `$_`. First each char in the string is replicated `"@F"` times (`s/./$&x"@F"/ge`) then `eval` is called on a string that contains `"@F"` repetitions of `"say;"` outputting `$_` the number of desired times. [Answer] # [J](http://jsoftware.com/), ~~55~~ ~~50~~ 49 bytes -1 byte thanks to xash! ``` ##"1&(16 8$#:96x#._32+3 u:'#dppv6SI=Hz`rW~|%1rc') ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/lZWVDNU0DM0ULFSUrSzNKpT14o2NtI0VSq3UlVMKCsrMgj1tPaoSisLralQNi5LVNf9rcilwpSZn5CukKRhCGOrqMAEjdAHj/wA "J – Try It Online") Ouptus a matrix of 1's and 0s. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 7Żx2r‘$Ṭ 3Ėr7,1FRoÇṠz0xɗ⁺ ``` A monadic Link accepting the scaling factor which yields a list of lists of pixel bits (1s are the arrow, 0s are the background) **[Try it online!](https://tio.run/##ATMAzP9qZWxsef//N8W7eDJy4oCYJOG5rAozxJZyNywxRlJvw4fhuaB6MHjJl@KBuv/Dh1n//zM "Jelly – Try It Online")** (footer calls the link, joins with newlines and prints a smashed version of the resulting list) ### How? ``` 3Ėr7,1FRoÇṠz0xɗ⁺ - Link: positive integer, n 3 - three Ė - enumerate -> [1,3] 7,1 - [7,1] r - inclusive range (vectorises) -> [[1,2,3,4,5,6,7],[3,2,1]] F - flatten -> [1,2,3,4,5,6,7,3,2,1] R - range -> [[1],[1,2],...,[1,2,3,4,5,6,7],[3,2,1],[2,1],[1]] Ç - call Link 1 as a monad - f(n) o - logical OR (vectorises) Ṡ - sign (i.e. convert all the positive integers to 1s) ⁺ - do this twice: ɗ - last three links as a dyad - f(matrix, n) 0 - zero z - transpose (matirix) with filler (0) x - repeat elements (n) times 7Żx2r‘$Ṭ - Link 1: positive integer, n 7 - seven Ż - zero-range -> [0,1,2,3,4,5,6,7] 2 - two x - repeat elements -> [0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7] $ - last two links as a monad - f(that): ‘ - increment -> [1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8] r - inclusive range -> [[0,1],[0,1],[1,2],[1,2],[2,3],[2,3]...,[7,8]] Ṭ - un-truth -> [[1],[1],[1,1],[1,1],[0,1,1],[0,1,1],...,[0,0,0,0,0,0,1,1] ``` --- Also 25 bytes: ``` “ṚẒỴġị!=gEḃĖT⁴ċṪ ’Bs8Zx¥⁺ - Link: positive integer, n “ṚẒỴġị!=gEḃĖT⁴ċṪ ’ - base 250 number = 171142666808876275700130073576311489283 B - to binary s8 - split into slices of length (8) ⁺ - do this twice: ¥ - last two links as a dyad - f(matrix, n) Z - transpose x - repeat element (n) times ``` [Try it online!](https://tio.run/##AT8AwP9qZWxsef//4oCc4bma4bqS4bu0xKHhu4shPWdF4biDxJZU4oG0xIvhuaog4oCZQnM4WnjCpeKBuv/Dh1n//zM "Jelly – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes ``` NθF⪪“∨:[¿θ≡↥χ№pTξ⟧M~▶§×¬‴↥”¶Eθ⭆ι×θμ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orLb9IQSO4ICezRENJLyZPD4whBJSEUXAaSVYBTCmAKQUFTBoLA4WlpKOgFJOnpKmpEFCUmVei4ZtYoFGooxBcAuSlgziZOgohmbmpxSDRXE0gsP7/3@i/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs using `.`s and spaces (newlines, spaces and `.`s are the golfiest characters for Charcoal compression). Explanation: ``` Nθ ``` Input `n`. ``` F⪪“∨:[¿θ≡↥χ№pTξ⟧M~▶§×¬‴↥”¶ ``` Split a compressed representation of the arrow into lines and loop over each line. ``` Eθ⭆ι×θμ ``` Expand each line `n` times vertically and horizontally. Alternative approach, also 35 bytes: ``` NθFχEθ×.×⎇‹ι⁷⊕ι⁻χιθJ⁰⊗θF⁷«UO⊗θ.Mθ⊗θ ``` [Try it online!](https://tio.run/##VU47DsIwDJ3pKaxOjhQQsHToylJEgaEXSIuBSPm0SVMJIc4e0qFCeHrPfh93T@E6K1SMlenDeA66JYcDK7O7dYC7LYOrk2bEWvQ4cGikJo/5Jl9gQ84I98ITeY@SQ8E4VKZzpMmMdEOZeC1N8CmLw8wGlqbMjkH3jcW0PNjQqiQd2FJbMHhnq0urrHng78whFSfNqrYTzd/8OT8x7uN6Ul8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs using `.` and spaces although any non-space printable ASCII could be used. Explanation: ``` Nθ ``` Input `n`. ``` Fχ ``` Start by printing the first 10 rows of the arrow. ``` Eθ×.×⎇‹ι⁷⊕ι⁻χιθ ``` Print a staircase from `1` to `7`, then down from `3` to `1`, all expanded `n` times. ``` J⁰⊗θ ``` Jump to the beginning of the second row. ``` F⁷« ``` Loop 7 times. ``` UO⊗θ. ``` Draw a square of size `2n`. ``` Mθ⊗θ ``` Move `n` across and `2n` down. [Answer] # [Octave](https://www.gnu.org/software/octave/), 69 bytes ``` @(n)kron([1:8<=(1:7)';dec2bin(['pX'+128 156 ',,&&##'-32])-48],e(n))>0 ``` Anonymous function that inputs a positive integer and outputs a zero-one matrix. [**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999BI08zuyg/TyPa0MrCxlbD0MpcU906JTXZKCkTKKheEKGubWhkoWBoaqagrqOjpqasrK5rbBSrqWtiEauTCtStaWfwPyWzuEAjTcNQU5MLzFRXUIey0jSMNDX/AwA "Octave – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 97 chars, 107 bytes ``` n=>{for(int i=0,j;i<n*16;Write("\n"),i++)for(j=n*8;j>0;)Write("€ÀàðøüþðØ˜ "[i/n]>>--j/n&1);} ``` [Try it online!](https://tio.run/##Sy7WTS7O/O@YXJKZn2eTmVdil2b7P8/Wrjotv0gDyFXItDXQybLOtMnTMjSzDi/KLEnVUIrJU9LUydTW1gQpyrLN07KwzrIzsNaESh9qONxweMHhDYd3HN5zeB@QnnFoBg8PGxszs1J0pn5erJ2drm6Wfp6aoaZ17X9rLrhNCrYKhtZAykbB0ABIA82v5uJM08jUtObiBBvtk5mXqoHBq/0PAA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~167~~ 145 bytes ``` i=input() m='@'*i*2 s=' '*i for z in[c*i*'@'for c in range(1,8)]+[m*2,m+s+m,m[:i]+s*2+m]+sum([[s*d+m]*2for d in(4,5,6)],[]):print'\n'.join([z]*i) ``` [Try it online!](https://tio.run/##FYvNCsMgEITvPoU3dZVCpS0lEOh7bD2UpD9bWCMxOTQvbzenmW8@pvyWz5Rja9RTLutineLe3AwQRFV7o6Wp1zTrTVPGQWaROw/Cen7k99Mew9UljwwxsK@eA2NHyVeIniVWtogVRgGI@3WUqz2Fc7i4FDC5rsyUF3PP5vCdROGWgFxr8Q8 "Python 2 – Try It Online") Down to 145 with some great help from @ovs. Many thanks! [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 1892 bytes ``` >++++[>+++++<-]>[<<+>++>--]>++++++++[>++++++++<-]>[<<++>+>--]>+[[-]>[-],[+[-----------[>[-]++++++[<------>-]<--<<[->>++++++++++<<]>>[-<<+>>]<+>]]]<]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<.>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<..>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<...>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<....>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<.....>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<......>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<.......>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<....>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<..>>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<.>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<<..>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<.>>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<..>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<<..>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<....>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<<..>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<....>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<<..>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<.....>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<<..>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<.....>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<<..>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<......>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<<..>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<......>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<<..>>>>>-]<<<<<<<.>>>>>-] ``` [Try it online!](https://tio.run/##5VLLCsJADPygNT14DvmRIQcVBBE8CH7/Ovtq9VaQIKU5LMnMZGbZ9vw83R7X1@WesyUW6plU3KCaOJmwT70wd0NBSVMABRE/IEGWQsH6sjbIxNmpQmy2o6G6UVtCzXm4u7oy0EhJ4SrFXRC1hjemcpXtfKnJ@qjf4w@OEZYhnjGmQa5Rtpt52cUSQ/7p05amNaKQX3Td9f51v/FN9he92@wNh@d8fAM "brainfuck – Try It Online") Not a short answer by any means - it could probably be shortened by a good bit. [Answer] # [Python 3](https://docs.python.org/3/), ~~124~~ ~~145~~ 136 bytes *+21 bytes because I didn't realise we had to scale it vertically as well* *-9 bytes by using `.` for padding* ``` lambda n,s='@\n.X'*27,J=''.join:J(n*(l+'\n')for l in J(n*s[m>>4]+n*s[m>>2]+n*s[m]for m in b'DDA@D@D@A@@D@P`R`ZhFjAjhFj`Zj`Zj`').split()) ``` [Try it online!](https://tio.run/##LY7BCoMwEER/JbfdqORgC4WCoiA9eCo9FasQpYiRuAZjD/36NCnuLMPbZQ5jvvu00smZTdGOiE73y/DuGSU2g6Il8YQovSR1BiDmVdG1RopQx9AS8HHdmGaKWHja15Ln5y4@KD2oC6ElhAaoqrKovMrC210@ZDPd5nL2Jpv/AhfWaLUj545jaKTIfMLpx6U/ "Python 3 – Try It Online") ### Explanation of the `b'DDA@D@D@A@@D@P`R`ZhFjAjhFj`Zj`Zj`'` string (the code does this in reverse) take the string, and: * replace "on" pixel with 0 * replace new-line with 1 * replace space ("off" pixel) with 2 ``` 010010001000010000010000001000000010000100200102200122220012222001222220012222200122222200122222200 ``` convert to binary, two bits per decimal digit: ``` 000100000100000001000000000100000000000100000000000001000000000000000100000000010000100000010010100000011010101000000110101010000001101010101000000110101010100000011010101010100000011010101010100000 ``` split into groups of 6: ``` 000100 000100 000001 000000 000100 000000 000100 000000 000001 000000 000000 000100 000000 010000 100000 010010 100000 011010 101000 000110 101010 000001 101010 101000 000110 101010 100000 011010 101010 100000 011010 101010 100000 ``` logical-OR each group with 01000000 (so it's all printable ASCII, to avoid escape characters): ``` 01000100 01000100 01000001 01000000 01000100 01000000 01000100 01000000 01000001 01000000 01000000 01000100 01000000 01010000 01100000 01010010 01100000 01011010 01101000 01000110 01101010 01000001 01101010 01101000 01000110 01101010 01100000 01011010 01101010 01100000 01011010 01101010 01100000 ``` convert to ASCII for a Python bytestring: ``` b'DDA@D@D@A@@D@P`R`ZhFjAjhFj`Zj`Zj`' ``` [Answer] # [Python 2](https://docs.python.org/2/), 102 bytes ``` n=input() for k in range(16*n):print''.join(n*' @'[j<=k/n<max(7,10-j)or-1<k/n/2-j<2]for j in range(8)) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERDkystv0ghWyEzT6EoMS89VcPQTCtP06qgKDOvRF1dLys/M08jT0tdwUE9OsvGNls/zyY3sULDXMfQQDdLM79I19AGKKZvpJtlYxQLMikLYZKFpub//0YA "Python 2 – Try It Online") Computes whether the given coordinate is on of off by a formula that bounds the arrow shape via linear inequalities. To check if the cell is in the tail, which is made of 2\*2 blocks (unscaled), we floor-divide the row index by 2 and check whether it either equals the column index or is one greater than it. As a function outputting a list of lines: **97 bytes** ``` lambda n:[''.join(n*' @'[j<=k/n<max(7,10-j)or-1<k/n/2-j<2]for j in range(8))for k in range(16*n)] ``` [Try it online!](https://tio.run/##RckxDsIgFADQWU/BBr8RKwzWNDTxHrUDxqLQ9kMITerpUVxc3wvv9PIos@luedbL/aEJtj2lR@ctMqwoudLeqW6qUS16Y81BnLgDH7lQX6sld0oOxkfiiEUSNT5HdgEoMv1FnCuEIRedLY4lDLMY1sQA2v0uRIvpV1l@AA "Python 2 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~106 105 103~~ 102 bytes *Saved 1 byte thanks to @Neil* Prints the pointer with spaces and exclamation points. Essentially the same method as in [my JS answer](https://codegolf.stackexchange.com/a/211643/58563). ``` x,y;f(n){for(y=n*16;y--;)for(x=n*8;~x;)putchar(x--?32^(~1<<(y/n>8?y/n-9:12-y/n)|3<<y/n/2)>>x/n&1:13);} ``` [Try it online!](https://tio.run/##LYpBCsIwFET3PUVWki9@QlKQ2h/TmwghkFrQKFoxobZHN0ZxM2/eMA5753KOm0SeB5j85cbTPqzllhIiwddj8YaWSHB9jO5oy4LY1erAF6k1TyKYpiuJu1YqLAVetdaFQoExUYSVbGUNNOchjOxsh8CBTRVjnkugH9Wf5VXN@e38yfb3jM8P "C (gcc) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~31~~ 30 bytes ``` 5r8ṬƝż`Ẏ 1ẋⱮ7;“ÐñŒ‘B;¢xẎ¥€z0ɗ⁺ ``` [Try it online!](https://tio.run/##AUYAuf9qZWxsef//NXI44bmsxp3FvGDhuo4KMeG6i@Kxrjc74oCcw5DDscWS4oCYQjvConjhuo7CpeKCrHowyZfigbr/w4dZ//8y "Jelly – Try It Online") *-1 from Jonathan Allan's answer reminding me of `⁺`. Now to figure out why his `z0xɗ` won't work for me...* Outputs a 2D array of 1 for for on and 0 for off. Integers, rather than characters, though, so +2 for a full program (`µY`) if that's a problem. ``` Dyadic helper link: € Map x repeat left right times Ẏ¥ and dump internal lists. z0 Zip with filler 0. Main link: 1ẋ Repeat 1 Ɱ7 1, 2, 3, 4, 5, 6, and 7 times. ; Concatenate with “ÐñŒ‘ [15, 27, 19]. B Vectorized convert to binary (applies to first bit too, but leaves it unharmed). ; Concatenate with Ṭ ¤ a list with 1s at the given indices Ɲ for each pair of adjacent numbers in 5r8¤ the range from 5 to 8 inclusive, ż` zipped with itself Ẏ and with each zipped pair dumped. ç Apply the helper link with input as right argument. ç Apply the helper link with input as right argument. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~162~~ \$\cdots\$ ~~126~~ 104 bytes Saved a whopping 26 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! Saved another whopping 22 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!! Note: code contains unprintables. ``` j;i;f(n){for(i=16*n;i--;puts("")) for(j=8*n;j--;)putchar(32|L" ˜ØðþüøðàÀ€"[i/n]>>j/n&1);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/LOtM6TSNPszotv0gj09bQTCvPOlNX17qgtKRYQ0lJU5MLJJFlawEUzwKKawIlkjMSizSMjWp8lJiZ2dh4eA7NODzj8IbD@w7vObwDSC843HCoQSk6Uz8v1s4uSz9PzVDTuvZ/Zl6JQm5iZp6GJlc1lwIQAM1V0ACJ5inYKhhaAykbWwVjawVt7TxNBYgSsDKg46zhvIIioI40DSVdQiAmTwmqrZar9j8A "C (gcc) – Try It Online") Uses `!` for black pixels (since it's the ascii for space plus \$1\$) and spaces for empty pixels (only if preceded by a black pixel, otherwise nothing). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 90 bytes ``` Normal@SparseArray[a_:>36^^4iam2h6stciyoj9kt5169kwfgn4~BitGet~Tr[{8,1}⌈a/#⌉],{16,8}#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@98vvyg3McchuCCxqDjVsagosTI6Md7KztgsLs4kMzHXKMOsuCQ5szI/yzK7xNTQzDK7PC09z6TOKbPEPbWkLqQoutpCx7D2UU9Hor7yo57OWJ1qQzMdi1rlWLX/AUWZeSXRadFGsToKSjF5SrHWXBCh4BIglR6UmZaWkwqWj421/g8A "Wolfram Language (Mathematica) – Try It Online") Pure function. Takes an integer as input and returns a matrix with 0 and 1 entries. [Answer] # [Canvas](https://github.com/dzaima/Canvas), 32 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` “┌Wwz‼GZE⁸↘4BUH<U„2┬8n{{⁴+c]]╶╶* ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyMDFDJXUyNTBDVyV1RkY1NyV1RkY1QSV1MjAzQ0daRSV1MjA3OCV1MjE5OCV1RkYxNCV1RkYyMlUldUZGMjgldUZGMUMldUZGMzUldTIwMUUldUZGMTIldTI1MkMldUZGMTgldUZGNEUldUZGNUIldUZGNUIldTIwNzQldUZGMEIldUZGNDMldUZGM0QldUZGM0QldTI1NzYldTI1NzYldUZGMEE_,i=Mw__,v=8) A better compression method would reduce this by a lot. ]
[Question] [ We've all seen those online "maths hax" that look like this: ``` Think of a number, divide by 2, multiply by 0, add 8. ``` And, by magic, everyone ends up with the number 8! --- ## Language Let's define a programming language which uses the syntax of the text above, called "WordMath". WordMath scripts follow this template: ``` Think of a number, <commandlist>. ``` Which basically means: Take a number (as input from STDIN) as the initial accumulator, perform all commands on it, and output the result. The commands are seperated by the delimiter `,` (comma + space). The valid commands are *(note that `#` represents a non-negative integer:)*: * `add #` / `subtract #` - Add/subtract the value from the accumulator. * `divide by #` / `multiply by #` - **floordiv** / multiply the accumulator by the given value. * `subtract from #` - Similar to `subtract`, but does `acc = # - acc` instead of `acc = acc - #` * `repeat` - do last command again. This cannot be the 1st command, but **you must support multiple consecutive repeats.** --- ## The Challenge Your task is to create a program or function which takes a valid WordMath script as input and [transpiles](https://en.wikipedia.org/wiki/Source-to-source_compiler) it into a valid full program - in the same language your code is in. For example, if my code is in Python 2 and the script is: ``` Think of a number, subtract from 10, add 10, multiply by 2. ``` The outputted program can be: ``` a = input() a = 10 - a a += 10 a *= 2 print(a) ``` Or alternatively: ``` print(((10-input())+10)*2) ``` As long as it is a **full program** which takes input from `STDIN` and prints to `STDOUT`, or the language's nearest equivalents. --- ## Rules * Your original program may assume that the input is always a valid WordMath script. * The transpiled programs do not have to handle mathematical errors such as division by 0. * The transpiled programs may assume that the input represents a valid signed integer, within your language's standard integer range. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution (in bytes) wins. * Only the byte count of your original program matters - the outputted code can be as long as you want! --- ## Example Scripts **Example 1:** ``` Think of a number. ``` Take input, do nothing, display it: WordMath's cat program. **Example 2:** ``` Think of a number, divide by 5, subtract from 9. ``` Remember that "divide" is floor division, so for this program `6 -> 8`, and `29 -> 4`. **Example 3:** ``` Think of a number, add 5, add 10, multiply by 2, subtract 15, repeat, divide by 2. ``` The extended cat program! **Example 4:** ``` Think of a number, subtract 1, repeat, repeat. ``` Takes a number and subtracts 3. [Answer] # C Preprocessor, 362 Bytes I ALMOST got this working in JUST the C preprocessor, but the repeat command turns out to be far too difficult to implement. So instead I used the preprocessor to turn the input into an array that is then interpreted by some additional code. ``` main(){int c[]={ #define Think #define of #define a #define number 0 #define add 1, #define subtract 2, #define from 0,3, #define multiply 4, #define divide 5, #define by #define repeat 6, 0 #include "input.wm" ,'$'};int _,l,v;scanf("%d", &_);for(int i=1;c[i]-'$';++i){c[i]!=6?l=c[i],v=c[++i]:++i;l==1?_+=v:l==2?_-=v:l==3?_=v-_:l==4?_*=v:_/=v;}printf("%d",_);} ``` The input must be provided in "input.wm" or just dumped in the source at that line. I included its bytes in my count because I figure its a bit hacky and slightly against the rules of the challenge, so it is only fitting. Anyways, once you dump your WordMath source into input.wm where a compiler can find it, you should be able to just compile this, as is, with warnings to produce an executable that does what the WordMath source says. [Answer] # Retina, 170 bytes **Because who wouldn't want to see this?!** I thought of how awesome it'd be to see a Retina solution, and I decided to create it quick. It only took an hour. As usual, byte count assumes ISO 8859-1 encoding. ``` S`, \. T.* .*¶$$* \;+`(.*)¶rep.*(¶?) $1¶$1$2 \d+ $* .*f.* (1*) 1¶x¶$¶$1¶+`x1¶ m.* 1¶ di.* (1*) ^¶$1 ¶^(1+) (\1)+1*$¶x$$#+¶1+ 1*¶x0¶x\d+¶$$* s.* (1*) ^$1¶ a.* ^¶ \z ¶1 ``` [**Try it online**](http://retina.tryitonline.net/#code=U2AsIApcLgoKVC4qCi4qwrYkJCoKXDsrYCguKinCtnJlcC4qKMK2PykKJDHCtiQxJDIKXGQrCiQqCi4qZi4qICgxKikKMcK2eMK2JMK2JDHCtitgeDHCtgptLiogCjHCtgpkaS4qICgxKikKXsK2JDEgwrZeKDErKSAoXDEpKzEqJMK2eCQkIyvCtjErIDEqwrZ4MMK2eFxkK8K2JCQqCnMuKiAoMSopCl4kMcK2CmEuKiAKXsK2Clx6CsK2MQ&input=VGhpbmsgb2YgYSBudW1iZXIsIGFkZCA1LCBhZGQgMTAsIG11bHRpcGx5IGJ5IDIsIHN1YnRyYWN0IDE1LCByZXBlYXQsIGRpdmlkZSBieSAyLg) Output has a trailing newline that should not be copied when testing the resulting program. The program does not support negatives, because Retina's *standard integer range* (in unary) does not. **Explanation:** ``` S`, # Split input on ", " putting each command on its own line \. # Remove the period T.* # Think of a number -> .*\n$* (replaces input with unary) .*¶$$* \;+`(.*)¶rep.*(¶?) # Loop, replacing "repeat" with the line before it $1¶$1$2 \d+ # Replace all numbers with their unary representation $* .*f.* (1*) # Replace "subtract from " with a subtract from program 1¶x¶$¶$1¶+`x1¶ m.* # Replace "multiply by " with a multiply program 1¶ di.* (1*) # Replace "divide by " by my integer division program ^¶$1 ¶^(1+) (\1)+1*$¶x$$#+¶1+ 1*¶x0¶x\d+¶$$* s.* (1*) # Replace "subtract " with a subtraction program ^$1¶ a.* # Replace "add " with an addition program ^¶ \z # At the end, add a stage to change unary into decimal ¶1 ``` --- ### Math programs: **Add:** Add the number of ones to the beginning. Add 5: ``` ^ 1111 ``` **Subtract:** Remove the number of ones from the beginning. Subtract 5: ``` ^11111 ``` **Subtract from:** Replace input `1`s with `x`s. Put next to the fixed number. Repeatedly remove `x1`. Subtract from 10: ``` 1 x $ 1111111111 +`x1 ``` **Multiply by:** Replace every `1` with a certain number of them. Multiply by 3: ``` 1 111 ``` **Divide by:** This uses my Retina program for [Integer Division](https://codegolf.stackexchange.com/questions/487/implement-division/75203#75203). Divide by 2: ``` ^ # Place the fixed divisor before the dividend 11 ^(.+) (\1)+.*$ # Match the divisor, followed by each occurrence in the dividend. x$#+ # Replace with the number of matches. Trailing ones are dropped .+ .* # If there are still two numbers, the result is zero x0 x\d+ # Replace result (marked with an 'x') with unary $* ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~59~~ ~~56~~ ~~54~~ 52 bytes ``` „, ¡¦vyDþs.AJá'bK"dmas""/*+-"‡„-f„s-.:«D'rQi®}©}J'rK ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oCeLCDCocKmdnlEw75zLkFKw6EnYksiZG1hcyIiLyorLSLigKHigJ4tZuKAnnMtLjrCq0QnclFpwq59wql9SidySw&input=VGhpbmsgb2YgYSBudW1iZXIsIGRpdmlkZSBieSAyLCBtdWx0aXBseSBieSAxMCwgYWRkIDgsIHN1YnRyYWN0IDYsIHN1YnRyYWN0IGZyb20gOSwgcmVwZWF0LCByZXBlYXQsIHN1YnRyYWN0IDQxLgoxMA) My brain hurts like hell after that... It outputs in 05AB1E code as follows: * `Think of a Number` is removed, due to implicit input. * `Subtract From #` coverts to `#s-` (swap `a` and `b` and perform operation). * `Subtract #` converts to `#-`. * `Add #` converts to `#+`. * `Multiply by #` converts to `#*`. * `Divide by #` converts to `#/`. * `Repeat` grabs whatever was last stored in the register and concatenates it. **Explained:** ``` „, ¡ # Split on ', '. ¦ # Remove the 'Think of a number'. vy } # Loop through chunks. Dþs # Dupe, push only digits, swap. .AJá # Acronymify without digits. 'bK # Remove the `b`. "dmas""/*+-"‡ # Replace letters with OPs. „-f„s-.: # Replace '-f' with 's-'. « # Concat # with OP. D'rQ # Dupe, push 1 if OP='r'. i®} # If 'r', push last #OP. © # Store current OP. J'rK # Join, remove remaining r's. ``` **Example:** Input: ``` Think of a number, divide by 2, multiply by 10, add 8, subtract 6, subtract from 9, repeat, repeat, subtract 41. ``` Output: ``` 2/10*8+6-9s-9s-9s-41- ``` Try solution with input of 10: [Try it online!](http://05ab1e.tryitonline.net/#code=Mi8xMCo4KzYtOXMtOXMtOXMtNDEt&input=MTA) See it on google: [Here's a link to the same equation typed into google.](https://www.google.com/search?q=9-(9-(9-(10%2F2*10%2B8-6)))-41) [Answer] # GNU awk, 139 bytes ``` BEGIN{RS="[,.]";c="{}{";ORS=";"} /ad/{c="+="$2} /c/{c="-="$2} /om/{c="="$3"-$0"} /l/{c="*="$3} /v/{c="=int($0/"$3")"} !NF{c="}1"} $0="$0"c ``` Invocation: ``` $> awk `awk -f wordmath <<< "Think of a number, add 1, repeat, repeat."` <<< 0 $> 3 ``` Test cases: ``` $> awk -f wordmath <<< "Think of a number." $> $0{}{;$0}1; $> awk -f wordmath <<< "Think of a number, divide by 5, subtract from 9." $> $0{}{;$0=int($0/5);$0=9-$0;$0}1; $> awk -f wordmath <<< "Think of a number, add 5, add 10, multiply by 2, subtract 15, repeat, divide by 2." $> $0{}{;$0+=5;$0+=10;$0*=2;$0-=15;$0-=15;$0=int($0/2);$0}1; ``` [Answer] ## Haskell, ~~232~~ 231 bytes Of course a functional programmer would prefer to return a function rather than a string representing a program, but here we go: ``` t l="main=getLine>>=print."++""%words l++"(0+).read" x%((o:_):f:n:r)|o=='m'=h"*"n r|o=='d'=h"`div`"n r|f=="from"=h"(-)"n r x%(s:n:r)|s=="add"=h"+"n r|s!!0=='s'=h s(' ':n)r x%(_:r)=x%r++x _%_="" h s n r|x<-'(':s++init n++")."=x%r++x ``` Remarks: We always start with adding zero, otherwise the transpilation of the trivial WordMath program wouldn't give enough information to infer the type at which `read` is used. `subtract from n` could be implemented as `(n-)`, but I use `((-)n)` for more uniformity. In the case of `subtract n` I copy the `subtract` from the input so I don't have to write it, but I need to compensate for the missing space at the end. `repeat` is used as default operation; together with an empty initial previous operation this allows for easy ignoring of the first four words. Usage example: ``` *Main> t "Think of a number. " "main=getLine>>=print.(0+).read" ``` The other examples give the following results: ``` "main=getLine>>=print.((-)9).(`div`5).(0+).read" "main=getLine>>=print.(`div`2).(subtract 15).(subtract 15).(*2).(+10).(+5).(0+).read" "main=getLine>>=print.(subtract 1).(subtract 1).(subtract 1).(0+).read" ``` [Answer] # Python 2, ~~263~~ ~~258~~ ~~260~~ 221 bytes This could probably *still* be much shorter. ``` def r(s,o="",p=""):c=s.pop(0);c=[c,p]['re'in c];n=c.split()[-1];o=[[o+[['+-'['s'in c],'//']['v'in c],'*']['m'in c]+n,n+'-'+o]['f'in c],'input()']['T'in c];return s and r(s,"(%s)"%o,c)or o lambda s:"print "+r(s.split(',')) ``` [**Try it online**](https://repl.it/Egsk/8) I use `//` instead of `/`, because the last instruction will have a `.` at the end, making any number a float. So in order to keep division consistent, I use integer division. **Test cases output:** ``` print input() print 9.-((input())//5) print ((((((input())+5)+10)+10)-15)-15)//2. print (((input())-1)-1)-1 ``` [Answer] # Befunge, ~~342~~ 305 bytes ``` >~$1 +:89+`#v_801p v_^#`+85~$< 1+>~:5+88+/3-!#v_$ v`"/":~p8p10+1<>>:"/"`!| "+"\5+8p4+:1+^:p11:g10< >:"+"\2+8p:"*"\3+8p: _$7%:01g\!#v_\2-7g\:1+:01v^p8+1\"5":p8\"5":g10 #8\"\"$#:0#<^v<p8p8\<g80p<>\#+$#12#p -/+* >:#,_@ #^p8g10< ".@"<^"&" 10<v0<\g8-\g11:<:p1>#1+g11:p10+g -:^>1g\-8p1-::#^_$8g^ >$$01g11g ``` [Try it online!](http://befunge.tryitonline.net/#code=Pn4kMSArOjg5K2Ajdl84MDFwCiAgdl9eI2ArODV-JDwKMSs-fjo1Kzg4Ky8zLSEjdl8kCnZgIi8iOn5wOHAxMCsxPD4-OiIvImAhfAogIisiXDUrOHA0KzoxK146cDExOmcxMDwgID46IisiXDIrOHA6IioiXDMrOHA6Cl8kNyU6MDFnXCEjdl9cMi03Z1w6MSs6MDF2XnA4KzFcIjUiOnA4XCI1IjpnMTAKIzhcIlwiJCM6MCM8XnY8cDhwOFw8ZzgwcDw-XCMrJCMxMiNwCi0vKyogPjojLF9AICAjXnA4ZzEwPAoiLkAiPF4iJiIKMTA8djA8XGc4LVxnMTE6PDpwMT4jMStnMTE6cDEwK2cKLTpePjFnXC04cDEtOjojXl8kOGdeICA-JCQwMWcxMWc&input=VGhpbmsgb2YgYSBudW1iZXIsIGRpdmlkZSBieSA1LCBzdWJ0cmFjdCBmcm9tIDku) **Output** The code it generates starts with a `&` (input value) command, and finishes with `.` (output value) and `@` (exit) commands. In between we have the various calculations in the form `<number><operation>`, where the *operation* can be `+` (add), `-` (subtract), `/` (divide by), `*` (multiply by), and `\-` (subtract from). The *number* itself is a bit complicated, because Befunge only supports numeric literals in the range 0 to 9, so anything larger than that needs to be manually calculated. Since we are already reading the numbers in character by character, we simply build up the number as each digit is read, so for example, 123 becomes `155+*2+55+*3+`, i.e. `(((1 * 10) + 2) * 10) + 3`. **Examples** ``` Input: Think of a number. Output: &.@ Input: Think of a number, divide by 5, subtract from 9. Output: &5/9\-.@ Input: Think of a number, add 5, add 10, multiply by 2, subtract 15, repeat, divide by 2. Output: &5+155+*0++2*155+*5+-155+*5+-2/.@ Input: Think of a number, subtract 1, repeat, repeat. Output: &1-1-1-.@ ``` **Explanation** Befunge doesn't have the ability to manipulate strings as such, so most of the parsing is handled by counting characters. We start just by skipping the first 18 characters, which gets us past the *Think of a number* phrase (plus either a comma or period). Then if the next character is some form of newline or EOF we go straight to the output routine, otherwise we continue looking for a command list. To parse a command, we just keep counting characters until we reach a digit or separator. If it's a separator, it must have been the repeat command which we handle as a special case. If it's a digit we add it to our output buffer, and continue looking for more digits. Each time a digit is output, we prefix it with `55+*` (to multiply the total so far by 10) and suffix it with `+` (to add it to the total). Once the digits are finished we add the command character. As for how the command is determined, we take the count of characters up to the first digit modulo 7. For *add* this is 4 (including the following space), for *subtract* it's 2, for *divide by* it's 3, for *multiply by* it's 5, and for *subtract from* it's 0. The *subtract from* requires a little additional handling since it needs the `\-` command combo, but the others just use their value to lookup the appropriate command character in a table. This process is repeated for each command, building up the output into a preconstructed string on line 8. Each time an additional command is added, we also add a closing quote to the string to make sure it's always properly terminated. Then when we eventually reach the end of our input, we simply "execute" this string to push it onto the stack, then follow that with a standard output sequence to write it all out. [Answer] # JavaScript (ES6), 163 bytes ``` w=>w.split`, `.map(l=>(o={a:'+',s:'-',m:'*',d:'/'}[a=l[0]])?p=(x=l.split` `.pop(),l[9]=='f'?x+`-n`:`n`+o+x+`|0`):a<'r'?'n=+prompt()':p).join` n=`+` console.log(n)` ``` Try it: ``` f=w=>w.split`, `.map(l=>(o={a:'+',s:'-',m:'*',d:'/'}[a=l[0]])?p=(x=l.split` `.pop(),l[9]=='f'?x+`-n`:`n`+o+x+`|0`):a<'r'?'n=+prompt()':p).join` n=`+` console.log(n)` const program = f('Think of a number, add 5, add 10, multiply by 2, subtract 15, repeat, divide by 2.') document.write('<pre>' + program + '</pre>' ) eval(program) /* Outputs: n=+prompt() n=n+5|0 n=n+10|0 n=n*2|0 n=n-15|0 n=n-15|0 n=n/2.|0 console.log(n) */ ``` [Answer] # Vim ~~208~~ ~~171~~ 168 bytes Added the ability to do multiple repeats in a row as per @Flp.Tkc but golfed off enough bytes that I could still lower the byte count. ``` :map s :s;\v c4wcw="s, s\w* \w+ (\d+); *-1+\1);g s, ([adms]).{-}(\d+); \1\2);g qws(\S+), r\w+;\1 \1 @wq@ws.*;\=tr(submatch(0),'adms','+/*-') qq])T=i(@qq@qx$xA ``` [TryItOnline](http://v.tryitonline.net/#code=Om1hcCBzIDpzO1x2CmM0d2N3FhI9FhIiG3MsIHNcdyogXHcrIChcZCspOyAqLTErXDEpO2cKcywgKFthZG1zXSkuey19KFxkKyk7IFwxXDIpO2cKcXdzKFxTKyksIHJcdys7XDEgXDEKQHdxQHdzLio7XD10cihzdWJtYXRjaCgwKSwnYWRtcycsJysvKi0nKQpxcV0pVD1pKBtAcXFAcXgkeEEKFhsb&input=VGhpbmsgb2YgYSBudW1iZXIsIGFkZCA1LCBhZGQgMTAsIG11bHRpcGx5IGJ5IDIsIHN1YnRyYWN0IDE1LCByZXBlYXQsIHJlcGVhdCwgcmVwZWF0LCBkaXZpZGUgYnkgMiwgc3VidHJhY3QgZnJvbSA3LCByZXBlYXQu) Unprintable characters: ``` :map s :s;\v c4wcw^V^R=^V^R"^[s, s\w* \w+ (\d+); *-1+\1);g s, ([adms]).{-}(\d+); \1\2);g qws(\S+), r\w+;\1 \1 @wq@ws.*;\=tr(submatch(0),'adms','+/*-') qq])T=i(^[@qq@qx$xA ^V^[^[ ``` Test cases output: 1. `cw^R=^R" ^[` [TryItOnline](http://v.tryitonline.net/#code=Y3cSPRIiChs&input=MTM) 2. `cw^R=((^R" /5) *-1+9) ^[` [TryItOnline](http://v.tryitonline.net/#code=Y3cSPSgoEiIgLzUpICotMSs5KQob&input=Ng) 3. `cw^R=((((((^R" +5) +10) *2) -15) -15) /2) ^[` [TryItOnline](http://v.tryitonline.net/#code=Y3cSPSgoKCgoKBIiICs1KSArMTApICoyKSAtMTUpIC0xNSkgLzIpChs&input=NQ) [Answer] # lex, 246 bytes ``` %{ #define P printf #define O P("n%s%d;",c,v); int v;char*c; %} %% T {P("%%%%\n.* {int n=atoi(yytext);");} ad {c="+=";} fr {c="=-n+";} s {c="-=";} v {c="/=";} l {c="*=";} re {O} [0-9]+ {v=atoi(yytext);O} \. P("printf(\"%%d\",n);}\n%%%%"); . ; %% ``` lex targets to C, so a C compiler would need to compile it into something executable. The lexer library (`ll`) would also need to be linked. This may add a byte-penalty, but I'm not sure how many bytes if so. The program outputs a lex program (per specification) that evaluates the transpiled wordmath expression. The code between `%{` and `%}` is for the "transpiler" only: ``` #define P printf /* for brevity */ #define O P("n%s%d;",c,v) /* expression builder, calls P = printf */ int v;char*c; /* v=most recent integer read */ /* c=the expression infix */ ``` Between the two `%%` lines is the regex/action portion. The first rule to be matched would be `T` ("Think...") which builds the preamble (lex programs must start contain the rule section at the least, and `yytext` is last matching text, so the rule essentially seeds the accumulator with the user's input). The program discards all input except for that which is matched, and the other rules (`ad`, `fr`, up to `re`) handle the wordmath expression clauses with as minimal a match as possible to be unique. In most of these, it sets `c` to an expression infix, which gets concatenated between `n` and the last integer read when `O` gets called (so for example, reading "add 9" will set the infix to `+=`, v to `9`, and the call to `O` will output `n+=9;`). (An interesting aside is that "subtract from 8" will cause both the `s` and the `fr` rules to get matched, but since `O` is called only at the number, the proper rule `n=-n+8;` is the only expression that gets output). The `re` rule for "repeat" just calls `O` again, which outputs the last created expression (and since subsequent matches will clobber `yytext`, supporting "repeat" is why the integer conversion in the `[0-9]+` rule was required). Finally, a period causes the program trailer to be output, which just outputs the accumulator and closes with the `%%` pair denoting the end of the output lex program. **Note:** Neither the main transpiler program or the output program will terminate. Piping input in would work, or providing EOF (ctrl-D). If termination is required after the first input, exit()s can be added. To build/run: ``` Build the main program: % lex -o wordmath.yy.c wordmath.l % cc -o wordmath wordmath.yy.c -ll Execute to create a specific transpiled program: % echo "This is a number, add 8, subtract 5, repeat." | ./wordmath > program.l Build the transpiled program: % lex -o program.yy.c program.l % cc -o program program.yy.c -ll Execute the transpiled program (with input 3, called via a pipe or inline): % echo 3 | ./program 1 % ./program 3 1 ^D % ``` Test 1: ``` %% .* {int n=atoi(yytext);printf("%d",n);} %% ``` Test 2: ``` %% .* {int n=atoi(yytext);n/=5;n=-n+9;printf("%d",n);} %% ``` Test 3: ``` %% .* {int n=atoi(yytext);n+=5;n+=10;n*=2;n-=15;n-=15;n/=2;printf("%d",n);} %% ``` Test 4: ``` %% .* {int n=atoi(yytext);n-=1;n-=1;n-=1;printf("%d",n);} %% ``` [Answer] # Pyth, ~~69~~ 67 bytes ``` J\QVtcQ\,Iq@N1\r=NZ)=Jjd+@"+-/*"x"asdm"@N1.>,J-ecN)\.qh@cN)1\f=ZN)J ``` A program that takes input of a `"quoted string"` and prints the result. [Test suite](http://pyth.herokuapp.com/?code=J%5CQVtcQ%5C%2CIq%40N1%5Cr%3DNZ%29%3DJjd%2B%40%22%2B-%2F%2a%22x%22asdm%22%40N1.%3E%2CJ-ecN%29%5C.qh%40cN%291%5Cf%3DZN%29J&test_suite=1&test_suite_input=%22Think+of+a+number%2C+divide+by+2%2C+multiply+by+0%2C+add+8.%22%0A%22Think+of+a+number%2C+subtract+from+10%2C+add+10%2C+multiply+by+2.%22%0A%22Think+of+a+number.%22%0A%22Think+of+a+number%2C+divide+by+5%2C+subtract+from+9.%22%0A%22Think+of+a+number%2C+add+5%2C+add+10%2C+multiply+by+2%2C+subtract+15%2C+repeat%2C+divide+by+2.%22%0A%22Think+of+a+number%2C+subtract+1%2C+repeat%2C+repeat.%22&debug=0) **How it works** Pyth has prefix operators, so the basic arithmetical operations are performed using `(operator)(operand1)(operand2)`, while the pre-initialised variable `Q` gives the input. Hence, a transpiled WordMath program is constructed by starting with the string `'Q'`, and at each stage, prepending the operator, and then prepending or appending the operand as neccessary. `J\Q` Set `J`, the transpiled program string, to the string `'Q'` `tcQ\,` Split the input on commas, and discard the first element (which is '`Think of a number'`) `V` For `N` in that: * `Iq@N1\r` If the character at `N[1]` is `'r'` (repeat): + `=NZ` Set `N`to `Z` (previous value of `N`, set at end of for loop) * `x"asdm"@N1` Find the index of `N[1]` in `"asdm"` (add, subtract, divide, multiply) * `@"+-/*"` Index with that into `"+-/*"`, giving the required operator * `,J-eCN)\.` Yield the two-element list `[J, -eCN)\.]`, where the second element is the last element of `N` split on whitespace with any `'.'` characters removed (operand) * `qh@cN)1\f` If the first character of the second element of `N` split on whitespace is `'f'` (subtract from): + `.>` Swap the elements of the two-element list * `+` Merge the operator and two-element list into one list * `=Jjd` Set `J` to that joined on spaces * `=ZN` Set `Z` to `N` `J` Print `J` [Answer] # [Pip](https://github.com/dloscutoff/pip), 58 bytes Too bad I haven't implemented that reverse-subtraction operator yet. ``` {p:a:sNa?ap['Y("-y+ y- y// y+ y* "^sa@?Y`\d`)|'qa@y]}Mq^k ``` The program takes a WordMath script from stdin and outputs Pip code to stdout. The code that is output, similarly, takes a number from stdin and outputs the result to stdout. [Try it online!](https://tio.run/nexus/pip#@19dYJVoVeyXaJ9YEK0eqaGkW6mtoFCpq1Cpr68AZFZqKSjFFSc62EcmxKQkaNaoFyY6VMbW@hbGZf//H5KRmZetkJ@mkKiQV5qblFqko1BcmlRSlJhcomCoo1CUWpCaWAKj9QA "Pip – TIO Nexus") ### Strategy For input like this: ``` Think of a number, multiply by 3, add 1. ``` we want output like this: ``` YqYy*3Yy+1 ``` which works as follows: ``` Yq Yank a line of stdin into y Yy*3 Compute y*3 and yank result into y Yy+1 Compute y+1 and yank result into y Last expression is autoprinted ``` ### Ungolfed + explanation ``` { p : a : sNa ? a p [ 'Y ("-y+ y- y// y+ y* "^s a@?Y`\d`) | 'q a@y ] } M q^k ``` The basic structure of the program is `{...}Mq^k`, which splits `q` (a line of stdin) on `k` (comma-space) and `M`aps a function to each element. Inside the function, we start by handling the `repeat` case. The shortest test in Pip seems to be `sNa` (is there a space in the command). If so, we want to use `a`; if not, use `p`, which stores the previous command. Assign that value back to `a` and also to `p` (for next time). For our return value, we use a list, which is fine because the default output format for lists is to concatenate everything together. The result always starts with `Y`. Next, we need a lookup table for the operations. Observe that the lengths of `add` (4), `subtract` (9), `divide by` (10), `multiply by` (12), and `subtract from` (14) are all distinct. Further observe that they are still distinct when taken mod 7. Thus, we can use them to index into a seven-element list (containing five code snippets and two placeholders) to map each WordMath command to the appropriate Pip code (designed so the number can simply be concatenated to the end): * 0: `-y+` (`subtract from`) * 1: placeholder * 2: `y-` (`subtract`) * 3: `y//` (`divide by`) * 4: `y+` (`add`) * 5: `y*` (`multiply by`) * 6: placeholder For the indices, we use regex to get the index of the first digit in the command: `a@?`\d``. We also yank the regex into `y` for future use. The lookup table is generated by splitting the string `"-y+ y- y// y+ y* "` on `s` (space). We still have to handle the first entry, which should translate into the code `Yq`. Since `Think of a number` does not contain any digits, the `@?` operator returns nil. Using nil as an index into the lookup table also returns nil. Nil is falsy, so all we need to do is add `|'q` to use `q` instead of an operation for this case. The final element of the returned list is the number itself. We obtain this via `a@y` (find all matches in the command of the digit regex we yanked earlier). This returns a list of digits, but again, it's not a problem because all lists will be concatenated when output. For the first entry, `a@y` matches no digits and gives empty list, which doesn't add anything to the output. ### For example With input ``` Think of a number, subtract from 20, add 2, repeat. ``` the map expression gives the list ``` [["Y";"q";[]]; ["Y";"-y+";[2;0]]; ["Y";"y+";[2]]; ["Y";"y+";[2]]] ``` which, when concatenated, outputs ``` YqY-y+20Yy+2Yy+2 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~154~~ ~~153~~ 146 bytes Fixed, and even saved several bytes in the process. ^\_\_^ ``` for c in input()[9:-1].split(","):s=c.rfind(" ");p=o=s and"x="+"-x+ input() x- x// x+ x*".split()[s%7]+c[s:]*(c[0]<"a")or p;print o print"print x" ``` [Try it online!](https://tio.run/nexus/python2#PY3NboMwEITvfYrRSpVwMKTppYKEt@gNcTA2qFbAtmwTOU9Pya800jez2t1ZR@shoc0mt8SMtVVdHLoyuEnHjDixOjSy9KM2KiMQO7rGNgHCKEoN5VSk/HWKVCDt99gmaUfPF6wNnz9dLttQd7tMtl/diQSxrdUdndcmwn7cSY@UaF3p90@bM@wIAbPM/eA5hFI4cISlj17IePPzMkXtpiv6K745lL5oNTzDe2/0dkbF4Qc3iPhiSf8 "Python 2 – TIO Nexus") Based on the same strategy as my [Pip answer](https://codegolf.stackexchange.com/a/104722/16766). Python-specific features: * `Think of` and the closing `.` are removed from the string before splitting (`input()[9:-1]`). The period was too pesky to handle in the main loop. Removing the first nine characters helps for a different reason (see below). * Instead of getting each command's length by regex-searching for a digit (expensive in Python because `import re`), we use `rfind(" ")` to find the last space in the command. We can also use this to check for the `repeat` case. * Python doesn't have Pip's cyclical indexing, so we have to take the index mod 7 explicitly. On the other hand, this means that we can remove the last dummy value in the lookup table, since the index mod 7 is never 6. * The "command" the first time through is `a number`, in which the index of the space is `1`. This index conveniently fills the other hole in the lookup table. The other problem with processing the input stage in the main loop was the `+c[s:]` part, which would result in `x=input() number`. To resolve that problem, we string-multiply by `c[0]<"a"`: `1` for all regular commands, in which `c` starts with a space, but `0` for the initial `a number`. [Answer] # WinDbg, ~~449~~ 388 bytes ``` as, }@$t1 as. }0;?@$t0 asThink n10;ed8<<22;r$t0=dwo(8<<22);r$t1=0;.do{ aSa " " asQ .printf";r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0 as/c add Q +" aSby " " as/c divide Q /" asfrom 0;r$t0=-@$t0+ as/c multiply Q *" aSnumber " " aSof " " asrepeat +1 as/c subtract Q -" .for(r$t9=1;by(@$t0);r$t0=@$t0+1){j44!=by(@$t0) .printf"%c",by(@$t0);.if116!=by(@$t0-1){.printf" , "}};.printf"\b ." ``` *-61 bytes by defining alias for repeated code* Inspired by [LambdaBeta's](https://codegolf.stackexchange.com/a/102264/58106) use of `#define`. This approach modifies the WordMath syntax slightly (`,` and `.` must be space-delimited like the other words, and `,` does not follow `repeat`), and creates alias such that the modified WordMath syntax is valid WinDbg code. The last line does what the question asks and transpiles by converting the input into the modified syntax. Input is taken by setting a string at a memory address and setting the pseudo-register `$t0` to that address. Note: this will overwrite the `int` at `0x2000000`, so if you start your string there, it'll be partly overwritten. `$t0` will also be overwritten. Because it creates aliases, depending on whether this code has run before or after setting teh string, the output code will be different (either aliased or not). Unfortunately, I didn't find a way to get the aliases to properly expand without being whitespace delimited (meaning the WordMath script could not just be executed directly without being transformed first). How it works: ``` * $t1 is used for repeating and $t0 is used to read the input and hold the accumulator * Alias , to }@$t1 -- closing do-while loop and allowing repeat as , }@$t1 * Alias . to }0;?@$t0 -- close do-while loop and evaluate $t0 (accumulator) as . }0;?@$t0 * Alias Think to (note this is one line) as Think n10; * Set base 10 ed 8<<22; * Read ints to address 0x2000000. Enter nothing to exit input mode r$t0 = dwo(8<<22); * Set $t0 = first int r$t1=0;.do{ * Open do-while * Alias a to nothing aS a " " * Alias add to (note one line): as add ; * Close previous statement r$t1=1;.do{r$t1=@$t1-1; * Open do-while (once) loop r$t0=@$t0+ * Add number to $t0 * Alias by to nothing aS by " " * Alias divide to (note one line): as divide ; * Close previous statement r$t1=1;.do{r$t1=@$t1-1; * Open do-while (once) loop r$t0=@$t0/ * Divide next number from $t0 * Alias from to (note one line): as from 0; * Preceding subtract statement subtracts 0 r$t0=-@$t0+ * Subtract $t0 from next number * Alias multiply to (note one line): as multiply ; * Close previous statement r$t1=1;.do{r$t1=@$t1-1; * Open do-while (once) loop r$t0=@$t0* * Multiply next number with $t0 * Alias number to nothing aS number " " * Alias of to nothing aS of " " * Alias repeat to +1 making do-while (once) loops into do-while (once)+1 as repeat +1 * Alias subtract to (note one line): as subtract ; * Close previous statement r$t1=1;.do{r$t1=@$t1-1; * Open do-while (once) loop r$t0=@$t0- * Subtract next number from $t0 .for (r$t9=1; by(@$t0); r$t0=@$t0+1) * Enumerate the string { j 44!=by(@$t0) * If not comma .printf "%c",by(@$t0); * Print the char * implicit else .if 116!=by(@$t0-1) * Else if the previous char is not t { .printf " , " * Print the comma with spaces around it } }; .printf "\b ." * Replacing ending "." with " ." ``` Sample output, entering the string before running this code once (the resulting program resembles WordMath): ``` 0:000> r$t0=8<<22 0:000> eza8<<22"Think of a number, add 5, add 10, multiply by 2, subtract 15, repeat, divide by 2." 0:000> as, }@$t1 0:000> as. }0;?@$t0 0:000> asThink n10;ed8<<22;r$t0=dwo(8<<22);r$t1=0;.do{ 0:000> aSa " " 0:000> asadd ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0+ 0:000> aSby " " 0:000> asdivide ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0/ 0:000> asfrom 0;r$t0=-@$t0+ 0:000> asmultiply ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0* 0:000> aSnumber " " 0:000> aSof " " 0:000> asrepeat +1 0:000> assubtract ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0- 0:000> .for(r$t9=1;by(@$t0);r$t0=@$t0+1){j44!=by(@$t0) .printf"%c",by(@$t0);.if116!=by(@$t0-1){.printf" , "}};.printf"\b ." Think of a number , add 5 , add 10 , multiply by 2 , subtract 15 , repeat divide by 2 }0;?@$t0 0:000> Think of a number , add 5 , add 10 , multiply by 2 , subtract 15 , repeat divide by 2 }0;?@$t0 base is 10 02000000 6e696854 18 18 02000004 666f206b Evaluate expression: 18 = 00000012 ``` Sample output, entering the string after after this code has run once (the aliases are expanded when entering the string so the resulting program is not as pretty): ``` 0:000> r$t0=8<<22 0:000> eza8<<22"Think of a number, add 5, add 10, multiply by 2, subtract 15, repeat, divide by 2." 0:000> as, }@$t1 0:000> as. }0;?@$t0 0:000> asThink n10;ed8<<22;r$t0=dwo(8<<22);r$t1=0;.do{ 0:000> aSa " " 0:000> asadd ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0+ 0:000> aSby " " 0:000> asdivide ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0/ 0:000> asfrom 0;r$t0=-@$t0+ 0:000> asmultiply ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0* 0:000> aSnumber " " 0:000> aSof " " 0:000> asrepeat +1 0:000> assubtract ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0- 0:000> .for(r$t9=1;by(@$t0);r$t0=@$t0+1){j44!=by(@$t0) .printf"%c",by(@$t0);.if116!=by(@$t0-1){.printf" , "}};.printf"\b ." n10;ed8<<22;r$t0=dwo(8<<22);r$t1=0;.do{ number , ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0+ 5 , ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0+ 10 , ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0* 2 , ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0- 15 , repeat ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0/ 2 }0;?@$t0 0:000> n10;ed8<<22;r$t0=dwo(8<<22);r$t1=0;.do{ number , ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0+ 5 , ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0+ 10 , ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0* 2 , ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0- 15 , repeat ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0/ 2 }0;?@$t0 base is 10 02000000 3b30316e 26 26 02000004 3c386465 Evaluate expression: 26 = 0000001a ``` Some more sample output, just using the slightly modified WordMath syntax: ``` 0:000> Think of a number , add 1 , repeat repeat repeat divide by 3 . base is 10 02000000 0000001a 3 3 02000004 3c386465 Evaluate expression: 2 = 00000002 0:000> Think of a number , divide by 5 , subtract from 9 . base is 10 02000000 00000003 29 29 02000004 3c386465 Evaluate expression: 4 = 00000004 ``` [Answer] # Scala, 338 bytes ## [Try it yourself at ideone](https://ideone.com/UaI26X) ``` s=>{val n=(_:String)filter(_.isDigit)toInt;(Seq("").tail/:s.split(",").tail)((a,&)=> &match{case&if&contains "v"=>a:+"x/="+n(&) case&if&contains "d"=>a:+"x+="+n(&) case&if&contains "y"=>a:+"x*="+n(&) case&if&contains "f"=>a:+"x="+n(&)+"-x" case&if&contains "s"=>a:+"x-="+n(&) case p=>a:+a.last})mkString("var x=readInt;",";",";print(x)")} ``` ### Explanation: ``` // define a function with a parameter s s => { // define a function with a String parameter to extract a number from a string val n = // filter out the chars that arent't digits (_: String) filter (_.isDigit) // and parse the number toInt; // take the tail of a list with an empty string, // which is the empty list of type Seq[String]. // This is the start value for the fold... (Seq("").tail /: // ... of the tail of the sentence splitted at commas s.split(",").tail ) ( // This is the function for the fold. // a is the accumulator (the list), and the current element is called & (a, &) => & match { // if & contains a "v", append "x/=" + n(&) to a. case & if & contains "v" => a :+ "x/=" + n(&) // the other cases are similar case & if & contains "d" => a :+ "x+=" + n(&) case & if & contains "y" => a :+ "x*=" + n(&) case & if & contains "f" => a :+ "x=" + n(&) + "-x" case & if & contains "s" => a :+ "x-=" + n(&) // for the repeat, apppend the last value of a to a case p => a :+ a.last } ) // make a string out of the parts by joining them with semicolons, // prepending "var x=readInt;" and appending ";print(x)" mkString("var x=readInt;", ";", ";print(x)") } ``` ]
[Question] [ Write a function or a full program that applies an ASCII texture to a 2d shape. **Inputs:** shape, texture, dimensions(optionally). * Both Shape and Texture can be given by any convenient method (2d matrix, array of strings or string with newlines) * Shape data have a rectangular shape and contains 2 possible values: [truthy/falsey] binary/integer values (0/1 or n1/n2) or 2 different characters, just specify which one represent the shape parts [truthy] and which one represent the blank parts [falsey] and be consistent . * The texture has a square shape only (width ≡ height) and contains printable ASCII characters. * Optionally you can also pass dimensions of the matrices if needed. **Output:** the shape with each truthy value substituted with the corresponding texture value (coordinates/indices mod texture size), the blank parts must be substituted with spaces. * The ratio is always 1:1 * The entire shape must be covered and only the shape. * No offset, texturing must start at top-left corner (0,0) of the shape data with the origin of the texture also at the top-left corner. # Examples (using various shape formats in JSON) **Shape** ``` [[0,0,1,1,0,0], [0,1,1,1,1,0], [0,1,1,1,1,0], [0,0,1,1,0,0]] ``` **Texture** ``` ["/\\", "\\/"] ``` **Output** ``` [" /\ ", " /\/\ ", " \/\/ ", " \/ "] ``` --- **Shape** ``` [" xxxxxxxx ", " xxxxxxxxxxxxxxxx ", " xxxxxxxxxxxxxxxx ", " xxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxx"] ``` **Texture** ``` ["[__]", "_][_", "[__]", "_][_"] ``` **Output** ``` [" [__][__] ", " [__][__][__][__] ", " [__][__][__][__] ", " [__][__][__][__][__", "[__][__][__][__][__][", "_][__][__][__][__][__", "[__][__][__][__][__][", "_][__][__][__][__][__"] ``` --- **Shape** ``` [0,0,0,1] ``` **Texture** ``` ["ab", "ba"] ``` **Output** ``` [" b"] ``` --- **Shape** ``` ["11100001011010", "01111010101101", "01011011111101"] ``` **Texture** ``` [" ./]| | / /.", "_|_|[]|/|_/\\_|/", "_|_|[/|_|_\\/_|.", "./_./]|_|//\\/./", "_|_|[]|/|_/\\_|/", "_|_|[]/ | \\/_|.", " /_ /|_|//\\/3/", "_|_|[]|/|_/\\_|/", "_|_|/ |_|_\\/_|.", "./_$/]|_|//\\/./", " |_| |/|_/\\_|/", "_|_|[/|_|_\\$_|/", "_/ /]|_/ /\\///", "_|_/[]|/|/ \\_|/", "_|/|[/|_|_ /_||", " /_./]|_| \\/|/"] ``` **Output** (a surprise for you!) # Rules * Input/output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * You can print it to STDOUT or return it as a function result. * Either a full program or a function are acceptable. * Extraneous whitespace are forbidden. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. --- [Sandbox post](https://codegolf.meta.stackexchange.com/a/18249/84844) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~20~~ 12 [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") -6 bytes through dzaima Full program. Prompts stdin for: 1. texture as a list of strings 2. number of rows in shape matrix 3. number of columns in shape matrix 4. indices of falsies (to be blanks) in the shape matrix All the `⎕`s are supposed to be rectangles (they're not [tofu](https://english.stackexchange.com/a/233948/106629)). They symbolise a computer console which here means *prompt for array input via stdin*. ``` ' '@⎕↑⎕⍴¨⎕⍴⎕ ``` [Try it online!](https://tio.run/##fVIxTsRADOz3FS5OChTE691wHB0tFQ/IRquTkGhOIi3S1gcNCAr@wAN4AU/JR4LXTsIlUkgxa3tndmw5@/Zwcf@0Pzw@9N3b5@1dd3y3pnt5bvsCihsudcePjK/fP196MvZM6EG@1hQYmBqwMJXZmjML9hwYSbASvGQkqZPETmInsZfYC98L33PdTK/XMTb8fmzqyMdpZnbG0dLQCfqFuYWt4JUyNaEh2@lxrXo79ep4WJJMKKQUUso4Agk6Qa@xnU31NwljiU2CBICAZR4jxVQ3CVPEEBOOFc5TDBhT5pQYs4qvMWCJ66oG@eVRBRjZZVD5dRVr5l6buVe@BljpcDNUkK1YxUMFxIGD4oUwqXBQcWcpaYc6F3DTzDHeUGX@2d2wJl0z@cUvRbJbAl0RuZMVuelfc/niFw "APL (Dyalog Unicode) – Try It Online") `⎕` prompt for texture as a list of strings; `["/\\","\\/"]` `⎕⍴` prompt for number of rows in shape matrix (`4`) and use that to cyclically **r**eshape the texture (this gives us enough texture lines); `["/\\","\\/","/\\","\\/"]` `⎕⍴¨` prompt for number of columns in shape matrix (`6`) and use that to cyclically reshape *each* of the texture lines (this gives us enough characters in each texture line); `["/\\/\\/\\","\\//\\/\\","/\\/\\/\\","\\//\\/\\"]` `↑` combine the list of lines into a character matrix;   `["/\/\/\"`    `"\//\/\"`    `"/\/\/\"`    `"\//\/\"]` `' '@⎕` prompt for indices for blanks (`[[0,0],[0,1],[0,4],[0,5],[1,0],[1,5],[2,0],[2,5],[3,0],[3,1],[3,4],[3,5]]`) and then place blanks **at** those indices;    `/\`    `//\`    `//`    `/` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 9 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` m⤢m⤢;n← ╋ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjREJXUyOTIyJXVGRjREJXUyOTIyJXVGRjFCJXVGRjRFJXUyMTkwJTIwJXUyNTRC,i=MjElMEElNjAlNjAlNjAlMEElNUJfXyU1RCUwQV8lNUQlNUJfJTBBJTVCX18lNUQlMEFfJTVEJTVCXyUwQSU2MCU2MCU2MCUwQTglMEElNjAlNjAlNjAlMEEldTIxOTAldTIxOTAldTIxOTAldTIxOTAldTIxOTAldTIxOTAldTIxOTAldTIxOTAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAldTIxOTAldTIxOTAldTIxOTAldTIxOTAldTIxOTAlMEEldTIxOTAldTIxOTAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAldTIxOTAldTIxOTAldTIxOTAlMEEldTIxOTAldTIxOTAldTIxOTAldTIxOTAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAldTIxOTAlMEEldTIxOTAldTIxOTAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMEElNjAlNjAlNjA_,v=8) Abusing that the input will be ASCII and so won't contain `←`, but the shape is made of spaces and `←` for easy overlapping and replacement. Alternative [12 bytes](https://dzaima.github.io/Canvas/?u=JXVGRjREJXUyOTIyJXVGRjREJXUyOTIyJXVGRjFCJTIzJXUyMTkwJXUyNTRCJXVGRjRFJXUyMTkwJTIwJXUyNTRC,i=MjElMEElNjAlNjAlNjAlMEElNUJfXyU1RCUwQV8lNUQlNUJfJTBBJTVCX18lNUQlMEFfJTVEJTVCXyUwQSU2MCU2MCU2MCUwQTglMEElNjAlNjAlNjAlMEElMjMlMjMlMjMlMjMlMjMlMjMlMjMlMjMlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjMlMjMlMjMlMjMlMjMlMEElMjMlMjMlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjMlMjMlMjMlMEElMjMlMjMlMjMlMjMlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjMlMEElMjMlMjMlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMEElNjAlNjAlNjA_,v=8) taking shape as space and `#`. [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ËmÈ?VgEY:S ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=y23IP1ZnRVk6Uw&footer=bXEgcVI&input=W1swLDAsMSwxLDAsMF0sCiBbMCwxLDEsMSwxLDBdLAogWzAsMSwxLDEsMSwwXSwKIFswLDAsMSwxLDAsMF1dLApbIi9cIiwKICJcLyJd) ``` ËmÈ?VgEY:S U = shape as 2d array, V = texture as list of lines Ë Map each row, define E as row number mÈ Map each element in these rows, define Y as element number ? Is the value a 1? VgEY Get the character at texture[E,Y] :S Else return a space if the value is a 0 ``` [Answer] # [J](http://jsoftware.com/), 32 bytes ``` 4 :'y}'' '',:x({.@]$($"1~{:))$y' ``` [Try it online!](https://tio.run/##bZFNS8NAEIbv@yteysIkUGeybfAQCQiCJ09e3bAHsYgXD@nB0tG/Hicfli2GsGFe5snDG/Zj2DAd0DYgbFGhsXPDeHh@ehxqNHT6JgLRtvkqznzf@cJvws@5KUt/oqF07tjyDjtPEqOQ61tGjVt4s1QI9lSX6S/l84Vxb6/vnzjigN7NM5FzPcy3R6hNmH9UTVNY3tfS8G@bp3BFju1RdHecduX475UDwNIpFBAIu6RJXzoVTRKTypwtaYqSlB1LGnlbSRSWdb4T8808JJl54ffrvNG53@f@cQWs9vFTFtMbb@WjyLSXyS9YeFl4a6I69pn7wwravswuYvgF "J – Try It Online") Some notes: * This was a rare case where I got a shorter solution with an explicit, rather than tacit, verb. * I wanted a solution that didn't prompt for input (ie, didn't want to just translate Adam's excellent APL solution into J). [Answer] # [Haskell](https://www.haskell.org/), ~~51~~ 49 bytes * The texture and shape are provided in the format used by the first example. * This works even if the texture isn't square or contains unprintables. * Dimensions do not need to be passed. * -2 bytes by abbreviating `zipWith` to `z`. ``` f=z(z(%)).cycle.map cycle z=zipWith _%0=' ' x%_=x ``` [Try it online!](https://tio.run/##1VRNj4IwEL33V7wQjZCQjmTPnPa6e9rDHkrToMFo/IgRTJT0v7MDVT50V71uJtDy@ubNtNNhmebrbLOpiiwv3tM8yxFD@QLKoyTxQgF4SUKe5plS03AaRmw81gCU@2ygP4HORQdho6yM0U7aaGXc7Abr4vUturF2ZRjrkd3QX3J5Xb0xR4/C6D/SrzVKZ64as3RQi44AQJK2sACBJC7Fs8Yqbckavj7GUg9lzBq@S8ZKh0oytQKzmEuSnipo4mh9BZDh6FeFt6cK7H@fw@g@h5oGPNrFqEOJU2AFPgRWoI5LTQ6EgQJdFDhza9Huwp0D6s3Za7MNr3jU9tFvvdZ7mndH6Lz6PVCXUUALsU1XO@74bbr/NPDdsD8WX8XhYweJ425@PBzOWARofxDVIi790h8HgZyf55tMsheamSjjcrX/XhVLYcbTeIKJOI1NfKqqHw "Haskell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εNUεiXèNèëð ``` Port of [*@EmbodimentOfIgnorance*'s Japt answer](https://codegolf.stackexchange.com/a/195899/52210), so make sure to upvote him! Inputs as defined in the first format of the challenge. Output as a character-matrix. [Try it online](https://tio.run/##yy9OTMpM/f//3Fa/0HNbMyMOr/A7vOLw6sMb/sd6Hdr9PzraQMdAxxAIgXSsTjSEDeZj4SFUxnJFK@nHxCjpKMXE6CvFAgA) or [verify all test cases](https://tio.run/##1ZOxTsMwEIZ3nuIUdbRyjWBnY2DoBgI51imRGDoxsF7epxILS7t0a/a@UvgdO4mblqorOiWOz/93d47Pn19Vvf7oHp5eu@N29XLcrt/f2s2q3bTf7U/XNM3zYW8Ou8fOZlyWmcnKkjN3Z@3SLE0Bw@iMDd/9/MJsUoLMrIhDIHFWMKSzIW5qxczGlRj5XHGRGNU3ETfH7u1kx/9J7U@jqvH36yr598FPRDk7JSVi4twfkYpap6yCThDlwQWHCtpC1KtyFs9hHSrO@QroGNFHkFiQagDvr4DAZhkXs4xeQPRnqYvoYiQEiP0B5KjiPiPTBHIEUaFqqDRskXz1Gu7DaXcWY8@f3Yjk6d9xddKnnYuz@AU). (Footer will pretty-print the character-matrix, feel free to remove it to see the actual output.) **Explanation:** ``` ε # Map over the rows of the (implicit) integer-matrix: NU # Push the map-index, and then pop and store it in variable `X` ε # Inner map over the cells of the current row: i # If the value of the current cell is a 1: Xè # Use variable `X` to index into the (implicit) input-list of strings, # with automatic wraparound Nè # And then use the inner map index to index into this string ë # Else: ð # Push a space instead ``` [Answer] # [J](http://jsoftware.com/), 19 bytes ``` ]]&' '"+]g"1~g=:$~# ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Y2PV1BXUlbRj05UM69JtrVTqlP9r/i/OSCxIBWnQ1TMAKjYEQiCtA2GBeShsKyRFXCWpFSWlRWDd6vp66jpW6jH66nDRNAWI2dEKqckZ@Qo@bijqo3Vj1XXUY6N1Qdp0Y6Px6AMA "J – Try It Online") Dyadic train. Left argument is texture, right argument is shape, 1 is blank, 0 is fill. ### How it works I extended [the dyadic `&` trick](https://codegolf.stackexchange.com/a/195891/78410) to the "If" usage of `^:`, i.e. boolean repetition amount. Also, an assignment `=:` can group the part of the train on its right, saving a pair of parens. ``` ]]&' '"+]g"1~g=:$~# Left argument: texture, Right argument: shape $~# Repeat the texture's rows to fit the shape's rows g=: Assign this sub-function to g ]g"1~ Use g to do the same on columns ] "+ For each cell on the texture and shape, ]&' ' Replace the texture's cell with ' ' if shape's cell is 1 Keep the texture if shape's cell is 0 ``` [Answer] # [Julia 1.0](http://julialang.org/), 68 bytes ``` f(s,t,n,Y,X)=[t[y,x] ? s[mod1(y,n),mod1(x,n)] : ' ' for y=1:Y,x=1:X] ``` Takes the shape as a 2d array of characters, the pattern as a array of Bools, and the dimensions (because `length` is long). Returns a character array via array comprehension. [Try it online!](https://tio.run/##dY/RasMwDEXf@xUifYgNYo1D1odAN9hXtLgeuIlDXVw72O5Ixv49cwNZ@zJdEEdwdZEuN6MlG6apIwEjWjzgnu545CMOAt4h8KtrGRnRUpxpSCSghjypcx7GHasPOKS@F1OrQ09k2u@9ttFY0nvXEskHrAWls38AbYHVQX8rIpGlrPVshuYsvWyi8iC9lyO4r4TXm4m6NwqMtiqsOuJVOMteEZ5vcsyPx6VtcoEllhQ/nDMvJHppQ@@CeiwUWCBLKnChZXrmP49AssWKpkq5FW4p/LzB/b/V8lu2zj5fC/p0VOOMUU0kmTydZEYfB/EC7mICoUzx1b9h0y8 "Julia 1.0 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` Fθ«FΣιG→¹η¿›0ι⸿→ ``` [Try it online!](https://tio.run/##LYxBCsIwFETXeoohqwRqk2z1AK4E0WVTQpFoCzXBWAvi9@wxRv9mZh5/5tR38RS6MaVziOA3gddyUezxceWDENiH8XkJnq8Pw6WfKugKvdgsF8MZfBtdN7nImWIVynMc/MSZiUxs4Ma7wy7M7t/NrXdKDdNaq3xaZdXK@KzF/cA3F6N/OC8zALVsCQRIyBrGW7LUtCTJSmMsyT/Jmawx0lLN2rSaxw8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as newline-delimited strings. Explanation: ``` Fθ« ``` Loop over the shape. ``` FΣι ``` If the value is a `1`... ``` G→¹η ``` ... then draw a 1x1 polygon filled using the template. Conveniently in Charcoal the fill is always relative to the origin of the canvas. Unfortunately Charcoal can't draw zero-sized polygons or Oblongs of sides less than 2, otherwise I could save a couple of bytes here. ``` ¿›0ι ``` If this is a newline... ``` ⸿ ``` ... then move to the start of the next line of the canvas... ``` → ``` ... otherwise move forward on the current line. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` JṁJ}ị⁸ṁ"⁹a@o⁶ ``` [Try it online!](https://tio.run/##1VO9TsMwEN79FKcoG1GuFiNCYu4bVI5lpRJLVYkZ6ZAaFgZeAWYW5ogKiSF9kvpFwuXSOC4ttCu6wXefv8@ff86L2@Xyvm2n23U1fdh@Pvvqg9PEV@vy5s5XdTvzj@8Lv3pp6oum9qvXK8mv@3zzhrNUbZ6EU301dVO3rVEcCRZFkilIigITmyljJtkk0xw8cg2mrwT5pR75VjEkyxrnrKzrrHGS7CPBKg79I8JMxz5GOCoYyGcJzl1ZoiPrTP8v8vgm5Vzuf17Gtx8TACBHS0AACJhD/1zkyFhCctwqjnAEGSLHfeMoFzBH18mZw0zM8YTcIhtFckDHvoP88oScxQfu6YF7RwL4Y/NpAJHNWc4HZzkGJoo7QizHnZx3TATD5vuzQ3ck2v2l/TbW4aeExhsbV@8ThulREXe5PJqy3w "Jelly – Try It Online") A dyadic link taking a list of Jelly strings for the texture as its left argument and an integer matrix for the shape as its right argument. Returns a list of Jelly strings. [Answer] # [Icon](https://github.com/gtownsend/icon), ~~100~~ 97 bytes ``` procedure f(t,s) i:=0&r:=|!t\*s&i+:=1&j:=0&c:=|!r\*!s&s[i,j+:=1]:=[" ",c][s[i,j]]&\z return s end ``` [Try it online!](https://tio.run/##vVPBboMwDD3DV7hRhaBDeGQ3JL4kRFFLqUSl0SnQTZvy750T0pZ2dNppOeHnx7P9nLT1oTud3vShbrZH3cAuHtI@CduifI50UZrFUK36qH0qyjzaW7C2oK5Wiz7qRZvubUYWpWDA0loKh0kZVV@hboaj7qAPm247qfC6brs4CYFO897oT/jQ7dBAvNjFgmFVsZRVFTKZhkEgWJ5znueMAgiAUUChjX4EI08mSXgv7ZQDJpSSjhwwJYXyn/eoK@vqjof74wJPvKKT7CU3k334Hx2f4/y/cs6iWY/YekPmb9ZkgjOAP7aTEZahNGAAEDDzW1BGGSENGkWLVAanMIFG0WaVObMzVFaDeMTGDP8gIpEq3ogAKmrhLPLyBxGSmOlkOdOJJQL8Os5yAiM1QiLkB4nghI2uE4RbEfQiNIEx12lGS8BOaS7PwN9Abm/53QPgHr2ALhov3rhB@/6@AQ "Icon – Try It Online") Uses `1` for spaces and `2` for textured in shape data. ## Explanation: ``` procedure f(t,s) ; t - texture, s - shape data i:=0 & ; i is the row index r:=|!t\*s & ; repeats the rows of the texture as many times as the rows of the shape data i+:=1 & ; next row j:=0 & ; j is the column index; reset to start c:=|!r\*!s & ; repeats the characters of each row of the texture as many times as the row of the shape s[i,j+:=1]:=[" ",c][s[i,j]] & ; modify the shape data ot " " or to texture \z ; z is not declared and thus causes Icon to backtrack return s ; return the modified shape data end ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~97~~ ~~94~~ 86 bytes ``` lambda S,P,w:[''.join([' ',P[j%w][i%w]][v]for i,v in E(s))for j,s in E(S)] E=enumerate ``` [Try it online!](https://tio.run/##tVPBbqMwEL3zFSOrK0CyGAycVuLYuyWOxrJIN9EStaRKsm1W8r9nx2OasGo2Pa2RsOfNe57xM7z@Pv7cTdV50/bn5@Fl9WOATmr5/t2kabHdjVNmUkilNttv79aM9LLmzW52exjlG4wTPGaHPA/xVh5i3OU2eWzX06@X9X44rs@dghaMKWUpFT00W5mYGDBwM7ySbZJo3kJg3wsJou9RENhVvO84HbOntk1PKbfxFJo4WAhrbsgImMdpHhwImYC4YovcnLmR@4eGBmdOp/@fITc0n1sY5ywTnTWOF38jwaH64jzZGaQMiGEVbFwNzGmuLi4NXPinlCppqJJmVXIFWnIQsRnitYoZbrRp2fwCrQcPgIBF9NB554316B1dqfN4BQnyji7Y@YLBAl2QE4eYWOAXcotUaCEHdFT3Q15/ISfxp@oPn6oHEsCd5h8uIFJxktPBSY4XJnJ1hKUcZzl17D18NB/PDuFInj/61z3dFKT9NP@dm6xTUiv5vJ4yrfI8j4xbvErqKvKqu7xa6jry6ru8Ruom8poL7/wH "Python 2 – Try It Online") 3 bytes thx to [frank](https://codegolf.stackexchange.com/users/90146/frank) Takes the shape as `S`, a list list of `0/1`;the texture `P` as a list of strings; and `w` as the width/height of `P`. Returns a list of strings. [Answer] # [Ruby](https://www.ruby-lang.org/), 65 bytes ``` ->s,p,w,h{s.zip(p*h).map{|a,b|a.zip(b*w).map{|x,y|x>0?y:' '}*''}} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9euWKdAp1wno7pYryqzQKNAK0NTLzexoLomUSepJhEslqRVDhWr0KmsqbAzsK@0UldQr9VSV6@t/V9QWlKskBYdHW2gY6BjCIRAOlYnGsIG87HwECqBXCX9mBglHQWlmBh9pViQRRpqVskZiUXFmjomOmax/wE "Ruby – Try It Online") **Input**: Matrix of 0 and 1, texture as 2d array of characters, size of the matrix (width and height). [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ËmÈù1VgEY ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=bcs/UDpT&code=y23I%2bTFWZ0VZ&footer=Vm1xIHFS&input=W1swLDAsMSwxLDAsMF0sCiBbMCwxLDEsMSwxLDBdLAogWzAsMSwxLDEsMSwwXSwKIFswLDAsMSwxLDAsMF1dLApbIi9cIiwKICJcLyJd) ]
[Question] [ Put simply, you are to print out the following number: ``` 0202020100110020122120012121100120121020202100012110002002010110211221012021112010200012112021220120022222102211121110110201220020202001111212210010100222100112101201122100222120201002002020200011110002211002202100022210212020112002020000120222111121112002112101000011112021202002210220022121002011021000202102101010210220022011011210102021110111212122201122021101211110121100111110122110110201011100022000212022020110211221022001201211120110221212221012220101121222011202112012221010212021120022110020022202020212022222012000012111001022021211110221211001201020202020011122222010010112222002010220111111111101010220120110010102100211000120111022212000220210121222000020212112010102012210201021022020202102102002011100211022101011202222111120100000021221101221220220200102010010021110120012202111012000100021102111102220102021100021001010020020001001222220121221122100102020000000221101220111201210200212111010211122211011210012020010012110110021221010121121202220001112220120221112001021001211112211110112212100001212200021111011200010120221010201110201121021002201221111210102010200200210112020022102110212020112111000121001021202101012000112210101112122220120012022121202101110221120012122120220120010122102110102002222120201102002111100001021001121100211122200011102122022110122000102212201111020200010222211002210021200202210102022221022222101121020102100100111221102211100102000211010012201121121220122021122102201000011221122101101111201102120001002012211020211122102002211111121222112110222212012201221111222010100101120022022111002012122112201212201011022212100010001022010102100120112001012110202210101220021102112210122210010202011211010002122111111221121222002211200201122010022021011110112111020102102001110000201111222220120011111112102212011200021210100210100010 ``` This is a randomly generated string of zeroes, ones, and twos. It is 1777 characters long. You may be asking: what makes this challenge interesting or unique? In normal text compression you would be able to get this down to roughly 29% of its initial size. However, if you were to use a base-4 compression - i.e. using two bits per character - you could actually get that down to 25% of its initial size. The point here is that simply compressing this file will likely not be enough to win this challenge. And, base-4 or base-8 (etc...) compression may not actually be the best solution, because no powers of 2 can be evenly divided by 3. So, you will need to get creative! # Other -You are allowed to have a trailing newline after the output -This challenge was inspired by [this question](https://codegolf.stackexchange.com/questions/205879/print-the-sars-cov-2-covid-19-genome) and, while it is true that the premises are largely the same, the biggest and most important difference between the two are that this challenge in not in a friendly base (the linked question is effectively in base-4, which makes compression relatively nice). -Other than the optional trailing newline, you must output the string/number exactly (i.e. no switching those characters for different characters), as this is [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes wins! [If you wish, you can also try to solve this in as few characters as possible - but make sure you still include the byte count] [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 356 bytes ``` ”)∨➙γOZNh≕◧≧hO=↖Laκ%mNπCσm‽⌊₂α¶↷⁴L⁶→XγU<¡'²xP`E←≡¤≔`"⦃NoT3# <≔3P'I³i↨⁸~⭆ jLγD≡vU[\F3^¹wV6?ξeλ4q⊕XLHH`⪪CtFνS,{}z↗q"d⊙Mρ&⁼Zqu¤ε‹⊙S4SR*=HD|νsX⁰±s⁹d#αj⧴σZηχº«⎚⌈UKa⍘⌈DIχR>\₂Nψ ⊗w⸿◨K´*y↶/§◧?↖Q¶X&rÀv⌊↘�§G≕ⅉβ8⁰I>∨FQ¬|F↓&V⪫M⬤s›LïyWuE⸿◧H)*⎚↓'kψ‽τ⁻≦lSl∕»RιPζxqv⮌PiPγ·¿0v∕)¦≦¶=|w¬!▶¬G⭆iTwQL↘`×I↨"`T&“κh⭆&ι]⊙₂✳→V⊞¶⊖ê{✂wP#⟧⧴f➙<ε<J+→₂→f¹F´ê⪫✂ξ#!We≦qÀηl⁶²∕6m≕▷8χo;wZ3Xσ≡�+ ``` [Try it online!](https://tio.run/##TZXBbtxADEP/ZU/tIYCoa34ivxDk0gKLBlgU/X13ho@y7WB37fFoRJGU8vXr8/X1/fk8jo/X7z9/fzyq/acqrc@66Vavh/W9F7RXxKb1WKyuJ8es@/W8Iva@dbd373fetld6h6@9@1pvvGV9HLhTVdKvhf1mb9rHOsKQOJocXgzYK9KhG5KRdXCSj93KZuPym8DY66SonNOJKeD6t@FFObh8sFGee8oleRUeinIWbMDvRZOSH7LJbA8bNXXsLwOdtBo0qGGaBbSG/Cb@TOigyltOo1xIMj8RtVHHOiGcNTBmAPfNC2EdxRJY5O6OKwxhLohqVKyhrbCRFxVdR7xUEa4ppOIXiIKNPrUgr3IsNSuFKa701eG77cymjri/Ipxp7uvBsY0OYB2VvT5@rcreYYVccXTsNzYVFE1vhekiR8cTDeWdU/EJJRQuing1YmBvjA3NKNgxnuJm2huf5YWxEw4jeFIduWBfp8lDuvW6dYxuTadIDAHqdA1wRyTE7tAeT3Mq8yKzKA1BZZpcipUnJ4hIPAzg3RALVRX5owR2jyajleIeCjP@uuiZeUaD6fIlgxSb9dlLcRDuAFJmY9/aO1NobMMUSa@PE6NDxkzHPk2vMQ5EbpOim3DMiDQrzQbAm1ljDEbSuEWh42xeZahmlg0tzPP7/4Sb@4GlswnHl2n2SJ1peQ7ysWfsmGaPwOh1TS8NC0XtyiSlQZU6Hj/fj@N4@/f8Dw "Charcoal – Try It Online") Link is to verbose version of code, which is just a Print statement of the original string, which the deverbosifier helpfully compresses using the best supported compression algorithm, which in this case I think is converting from base 3 to bijective base 255. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~504 481~~ 474 bytes Builds a BigInt from a string encoded in base 126 and converts it to base 3. Because the data string contains many unprintable characters, it is not shown at all below. ``` _=>0+Buffer(`...`).reduce((n,v)=>n*126n+BigInt(v-1),0n).toString(3) ``` [Try it online!](https://tio.run/##BcGLc9lwAADgU2dV7aF2MQ21oUhCPeJ1bImWKupmnHdlUSKIxy/xk0Q95l@375sP1eGGg4IkPwJxzJ8n1HlA0ZFATplMeIh9XKLA4dgiqLcUDkja0KA/gRGxSsfVeVPZ7pK@vKcDK@yoV8xlMl3wlBfchtnKvNFJXLZWXhda6JVaa9zNOD1rHbLXuTiRRw3kkTKbkHJpSAdc/i@kW66mTmk2fHS157fJYxPRfavpCKWvUyxkKSNUSTyYxuKS@DDP9Rlm0XyvM7CbkYc7h@HVVzy50/vFaCu0Ohf@zlX/YOOVDrFGbjIrnd6u0Hgc7rqktdVtZ4k/X29sDPPvZ5vCZXuZ80fRYcBk9L4wDHGCDBP54awsEK2YBVSFgZd1c90zyGoczueDx003pUSFbCnvrUaD84G7YJVPallxrU1dfB/rLdlXklZmIKqP1VefqWhsjmZh2TH22u7V51BxYHowrs0Trr@Ow3HEf58wXJt9pjbyq/J7689oTOGaV3@k9r6eSyio6H70@TdkthyMzrcpBg9WuwZ/sSL1WymMOMNPpWXiWFAHvRH7gYcgP1Y4HsNAUMUpGhBRMgkCOWFaBjKmPkbxYATgIVlsyFAAUyyGnzkRbMQlH1qKU2yC4fj5Pw "JavaScript (Node.js) – Try It Online") The theoretical length of the string is: $$\left\lceil\frac{\log(3^{1777})}{\log(126)}\right\rceil=404$$ Because a few characters need to be escaped, we actually need \$410\$ bytes to store it in the source. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~360~~ 359 bytes ``` 0•1"ôÒ^¯ùg©ÞPò–>Δª7н8l9ëŒƶuÚ*'ΛZúΩиç“À¨'Õƒ†ìà\¬Õ¯zʒbGmK_¤Rï1αÉAΛ÷₂*ƶÃ/¿ž-‘`޾η¥ÓEÛ‰±þ»¡{ÒõÆΩf`ÆнÜmÙ*Ë-γèΩ²IĀSRÉ×₃"!ÒVNÑc¥à8¡{øs²†?тλ¢[)¿„œQ6ýÕl…cüÖ₄δðnøÍθds—'>oÉÙÛÄȉÓ|5&þMbǝ¥₄ü¿ö-.ã Äh›µ„玜LΩ.Ÿv¹[ïüãDÞw[š²ð,ê∊R–=¿ ݰ–Oôìʒi5ÛtWƒв²ÞΔgîγz₆/pÈv£A~y≠B₄Ý]®©₅^ïr÷Á©Ñþ‰”»«é¸₆Θ™šEΓCΘ‘ ™ÕâGε¼"Äθv4¼[F+„ûW¿–ãîvîð._e!ð‘h 4DŽÕ‡ZΩĆ1·ÜY“¨â²Œ₃;öŸrÐÿRƒδ¾ñI₆Œ@Θ˜ß!™∊G¨u[d•3B« ``` [Try it online!](https://tio.run/##FZLbTlNREIbveQrgQiIKSATFGFEQJMRzTSRSBeQgkHAwVGpEY5ab2hSNiexNtdiDPYh0A2lLgXYDPSTzs2qCyUp9hfUidfVuJpn5559vZt7xfHR6olK5IFm0tR770IcoicNJMhF6gLRkRqdYo63L5XzHzBVsc72UWcSPxgbhH8SRMMsWNiULgFG8Ad6SLlkYOwg/pR14Kbl0qo/2zd4epl82JFvFLla6hB9ZqWmNpQyWW6jIC02S@UZ4ngoiSxsweuGXLEW7KNAxRd5CxwHcwnwxAnc5j8As1hvxuUnsIS5MSvefsEc2rOC71Jbr66A/vofVMSUT7qj2Wg5SC4Sv/9PEMUXtZ6koWYgbDy8hD@@MZL/HkMM3qbnEPlJzsPBFWOMOydYaOueV6Dr8cMGj7MB4134Ghbujf4K0oeqRoyIyTc2I1cI1JdkRHShlbPI8N@4Is5lbTjq0I6nkYz0IvbbzCKWROo8t6flkU0yvUbEGQUqp8L5ivnOqT7fD/2qgpJfTqjIk1iaREHtLUnO3vITHSbGu92/kSri7Ojz4jBJkSu3jEJILyOKDutUqCsqnZEFFbRsmWapT@KQryiO9wripQuarUSm8iPaJA8rVwyUsZxvl7LfOVb0fD1TpGIgh4UQCqebhiTooQd9UbVsPV7wkiwwK88TdSlkEnqibUxxRSnNdob@KDLcW8BVFW0kX@1TAbr8ywPUbwvc3gJ91arLavI/ii/Zx9WgXu2m7UvkP "05AB1E – Try It Online") Ah yes, 05AB1E. The language designed to perform well with base conversion challenges. [Shamelessly compressed using this trick by Kevin](https://codegolf.stackexchange.com/a/166851/78850) *-1 thanks to @mypronounismonicareinstate* [Answer] # Google Sheets, ~~674 635 624~~ 426 Closing parens discounted. Column A: Padded original number up to something of length divisible by 10, then converted each 10-character chunk into a number. Then converted that into a unicode character (using `UNICHAR`): ``` Ȣ 僂 � 栩 㦱 讛 ꎫ 휾 莡 쉹 苼 䢸 ⑅ 㦚 紗 ᱨ 竾 횂 㙓 㤁 侏 펵 뫁 艁 ⶂ 败 覤 疒 ᠃ � 惦 愮 援 媉 㿂 郸 껙 殰 犅 ␱ 佭 蟷 䅑 ໑ ꘒ  嫌 秿  䂥 勣 굑 � 貇 뀓 �   ൉ ᫀ 켑 ♱ 嚪 ꕈ 떹 葜 脄 ぎ 㪳 垈 㛠 㦸 㕏 㾈 ⣏ 甒 ᚜ � ઍ ᕂ ㄲ 聸 涠 킙 گ ᆹ ᄎ 쮾 ῵ ࠉ ꛏ 㖼 ⃌ 欎 ꬲ 橧 뛕 衠 罡 삼 刜 뿪 裀 췒 ⟨ 놢 焠 㲪 쁾 ꑉ 럧 ퟬ 걣 ԓ 욾 魕 娑 ꠲ 쥼 溚 郗 ⬙ 懦 䱽 汹 䵉 ⤩ 缶 捳 崉 � 㣿  ᗩ 뛼 믬 笠 俥 뺡 Ὡ ᭰ 썴 꾋 ꉟ 쏧 珴 聼 镄 繷 쁁 � � � 嗍 ឭ ዟ 錃 夶 ䷙ 큇 ⰲ ⻁ 圻 淅 韫 㟕 ފ 眪 쾺 㟩 䚜 媤 ⁽ 暾 耏 ೑ 敎 ݥ 㳃 ``` * `B1` - `=RIGHT(JOIN(,ArrayFormula(BASE(UNICODE(FILTER(A:A,A:A>0)),3,10))),1777)` + Convert A1 back to unicode numbers, then back to Base 3. ## Supplementary Formulae I added these because copy+paste from the code box drops some characters. * Padded original number (`A1`) with this formula: ``` =REPT(0,10-MOD(LEN(A1),10))&A1 ``` * Converted using this formula, where A2 holds the padded number. ``` =ArrayFormula(UNICHAR(DECIMAL(MID(A2,SEQUENCE(LEN(A2)/10,1,1,10),10),3))) ``` * Byte count done for column `A` with this formula (=347): ``` =ArrayFormula(SUM(LENB(A:A))) ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~3178~~ ~~3073~~ ~~3072~~ ~~2961~~ 2955 bytes -6 bytes thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) ``` ++>->>->->->>->>+>->->>->>+>>+>->->->+>>>->+>>+>+>->>+>>>>>>>>->->+>>->+>+>+>+>+>>>>>->+>->->->->>>>->->+>->>+>->>->+>->>>>+>>>->>>>>->>+>->+>+>->->>->+>+>>>->+>->->+>>>+>+>->->+>+>+>>+>>>+>+>>>>>>>+>+>>+>->->->>->>>+>>>->+>->+>->>->->>+>+>+>>->>+>+>>>+>->>>+>->->+>+>>->>->>+>+>->+>->>>+>>->>->->+>>>->+>>->->>+>->>->>->+>+>->>->->->>->->->>+>>+>+>+>->>>->>->+>+>>+>>->+>+>>>+>+>>+>>->+>->->>>>+>+>->+>+>->->+>>>->>->->>->>->+>+>+>>>>>+>+>>->+>+>>->+>>+>+>+>+>->>>+>>>+>+>+>>+>>>>>>>+>+>->->+>->>+>+>>>>+>->+>->>>+>+>>->+>->->>->->->+>>+>->>>->+>>>>>->>>->>+>+>>>+>+>>>->->->->>->+>+>->>+>+>>>+>->+>+>>->+>+>>+>>>+>>>->+>+>>->->>->>>+>->->->+>->>->->>>>+>+>->>>+>+>>>>->->>->->>+>->>->+>->>+>>>->>+>+>+>+>+>->>+>+>+>+>->+>->>->>+>+>->+>->->+>>+>->->>+>+>->->>>+>+>+>+>->>->->->+>->+>->>>>>->+>+>>+>+>->>->->->+>+>>->>>+>+>->+>+>>+>->>>>->->->+>+>+>>>>+>->->>>+>>>->->>+>->>->->->->>>>>+>->->+>->>>->+>->+>>+>+>+>+>->->+>->>->>>+>->>+>+>>->>->->+>>->+>+>->+>>+>+>>+>>->->+>>>+>+>->>>>->>+>->+>>+>>+>+>->+>>->->+>>->+>+>+>+>>+>>>>->>->>+>+>>>->->->+>>->>->>+>->+>>+>->>->->>+>>->->->>>>+>>>->+>->+>>+>->>>+>->>+>+>->->+>->+>>>->>+>->->+>->->+>->>->+>->>->>+>>>>>+>+>>->+>+>->->>+>->>+>>>->+>->>>>->+>->>->>+>+>->+>>->>->->->+>>>->>>>>+>->->->+>+>>+>>->->->->>+>>+>+>>>->>>>>+>+>>>>>+>>->->>+>->>->->+>>>>+>+>->+>>->+>+>+>>>>->->->+>+>+>->+>>+>>>+>>->>->>+>+>>+>->->>>->>>+>>->->>->->+>->+>>->->>+>>>->>>+>+>+>>>>+>->>->>>>+>>+>->->+>->>+>>->+>>>>->+>+>>->>>+>+>->->->->->->->+>->+>->>->->>+>+>>>+>+>>+>>->+>+>+>+>+>>->->>->->->+>->->+>->->>->>->->>+>->->->>>+>->+>->>->+>+>+>->>>>>+>->>>+>->->->>->->->+>>->>>>+>->+>+>>->->+>>->>>>+>->->>->->>->+>->>->->+>->+>+>->+>+>>+>+>>->>>+>+>>+>->->->->->->>->+>>>>>+>+>+>+>->+>>>->>->>+>+>->>>+>->->>>>->+>->->+>->>+>->>+>->+>->+>->+>+>->>+>->>->+>->>+>+>>->+>->>->>->+>>>+>>+>->+>->->->->+>+>+>>+>>->>+>->+>+>->->->+>>+>+>+>->>>>->+>>->->->>>+>->->>+>->>->>->->>>->+>>->+>+>->>->>->>>>>>>>>>>->+>+>->>->+>->->+>+>+>+>>>->>->->>->+>+>+>+>+>>>>->->+>->+>->+>->+>->>->+>>->->>>+>>+>+>->>>>>+>>+>->+>+>->>->->>>>+>>->->->->+>>->+>+>+>+>+>->+>>+>->+>->+>->+>+>+>->->+>->->>>+>+>->->+>>>+>->+>>+>->>->>+>+>+>>->+>>>+>->+>>>->+>+>+>>+>>>->>->+>+>+>>->>+>+>+>>+>>+>+>->>>->+>>>>+>>->+>>->->+>+>->>+>+>>>+>->>>->+>->+>+>->+>>+>->->->+>+>->->->>>>->>->+>->>>->>>+>+>>->>>>>>->->>>+>>->>>>>+>>->>>+>->+>+>>>->+>+>+>>+>>+>>>>->>>>+>->+>->>->>+>>>->>>->+>+>->->+>+>->>+>->>->>->>+>->>+>->+>->->->>+>->>>->+>->->>+>>+>+>->->+>+>->>+>+>->->+>->+>>+>->+>>>>>->->->->>->>+>>>+>->->+>>>>+>>>>>+>+>+>->+>>->->->->+>->+>->->+>>>->+>->+>>+>->>+>+>+>->->->>+>->+>+>->->>>+>+>->->->>>>>->->->+>->+>->+>->->+>->->>->+>->+>>+>+>+>->->>+>+>>>->+>>->>+>>>->->>+>+>+>->->>->>->->>+>+>>+>>>>>->->+>->+>->+>->->+>+>>->+>->>>->>>>+>>>>+>+>->>+>+>+>+>+>->->+>>->+>+>>+>->+>>>+>>->->->+>->>->+>>>>+>->+>>->>+>+>>>+>->>>->>->+>->->+>->->->>>+>>->->->>+>->+>->+>->>+>>->+>>->->>>+>>+>>->->+>>+>+>>->+>->->>>->->>->+>->+>->+>---[>-[<+>-----]<.[-]<--] ``` [Try it online!](https://tio.run/##bVZbTsRADDuQZU6AcpEVH4CEhJD4QOL8ZWmb2J7uPqfTmUniOE7ffl4/vz9@37@2DSjW/cPjr2Cj84L/w@MX@9R@vb/Om9xvHO8617IP7VXn4T2u89RjwT4HWcfYbPuYMQ5PasxVTykM2z4B9lb2Tpwr@9gJfLbNpGFAi2SclmkOducdCwgKza/ZeDgIqDGtE6Boqb/BvgM3jCqgm9AjRHdjEt6@d0YDN1QpwRQtUMqkBT3goTxDlFcBwThJS52YA/kCNw1Pt11R5BDFfLP8wBASRncGQyxPvZ7OzDIT6f0UhOdjLJtHisKA5VJus6dRhQGoklIceFCvjbPSRy2KQ5QJxYF0P/wVpKYrEZwytZBamMlA1YPcBmEDWgYyXpNa13aXHMFr0dPqWaYx29DrzNMONiBo9E26DJ5Rqe3NhXz@vmpcLWqDqLzMAytqjJNEuOoI2pBZMSXKPiclYkg44GWmss/4RoG8wlOpBXsyDOKvm1y0BE6sLiLTjuw5S6diKr2ybF7BMc4CnsRPO4V7Z2UaKCI5ieVrXDMR87hSci3MOJ4OBIwLDBGV9LhSiHR2L9u3dzV600I2H5SLF9b@nXSK@rcnEJNbI1wZTpQcGJvD5RbLWjpNjSNIL@kyGqQK52lhR4xMeUVVNt6BQVBVefpWkeADzYZjFc9hCeJy1KIhyGKwfgJDKcylaKEeEZpRomo7a@NHMnjgQuVjhj38XIm0REXfnyWGa5W5HFiJBDz7l7wVb8/7iHx5frrdf@6DbfsD "brainfuck – Try It Online") It first stores the number backwards then it adds 49 to the cell before printing it then goes to the cell before that and it does that until it reaches `++` [Answer] # [MATL](https://github.com/lmendo/MATL), 438 bytes ``` '1ye}Ju:]rrY6|H!R^ 4Fl^/z*F|`[=I"5A3nYj](eaiU/+1dxw5}MWfh-G6uV9@/jQy_)I6D@e?f+5*!4xOE^1+=\.Op`=?K8Wurme+#3F}+v*n\Hd<2e")H*JzcUR.1fg{q 3b+i(xtuj-0]hTrr@<wj?y$uj&2zstc=uDv}p|1_IM1$I)o^p*~~WE/kkG?R<QS=x{%Y5EMLCUVk%$s69A#mHm,6RjN`*tI\,{10o,0zQ_<LK+\uG2p*y\=-vQ?n*1W~`sjgmR2c>tfZ%.vWk=eL"JP{QP /)gR{Et\hjwx dUZVz%\4utDRexe=KI $tv<,P8U mDxuTgi%44;6FYN`i/|HQ&9gpLOtWu<7:[)AH:t?h"h7N#j\X;m(_(L+h!2 zVA"NzMb!`:}|9>mi>s||MrxQE/9M&6:S+.P{Z}n'T210VZa ``` [Don't try it online!](https://tio.run/##BcGLerEAAADQV8klUyGFtqzE94tCqKnGQka6WOZPJV28up3j7vyf5/MFuxvZKGivPW9JpFxO2gDNwc8GjeFBqn/RfL7Va5yXzrps7GwZRbBDdGtlgnq0qkMiUMgu6oj3LcQT/a7BHJEWnGtGM3aDIbRWm110mhm/qYHnGkihMciQED5r3IHCjTzEwaN4L0s17Ggm/4HGN2KXIz9wqvW1tfC8LnVzmHsxcEp4fPX3dNAPs0uKbXkBK/LQ7@YCPx4qi55OQ0aixA86SsBlixUm/2TlBBavBNkruJxbISRnqsM@r1USrP5bqcfilpqMES0Y4hf4rtHVUGTOMKY@9KtjuhK@7/jHFVgL1RNtTPKjeSLOARQypYT1Ncu5RcBBXikxqDUDvy8ZkUGPeaDoh1Rl/iYDbj8KFqYNNpvvxGA51W005cQSaV4mM18NqNf2F9Tj2j5j5a3XacHRPt/d8rY8QawcDsRKLz@Nhe@c3s5SsuPanWuaCl4ksigplIj2B1KbJ6vs/LLAsbqy2j2ffw) (it times out). Here is a GIF file of the program running with the offline MATLAB compiler: [![enter image description here](https://i.stack.imgur.com/7ZHyR.gif)](https://i.stack.imgur.com/7ZHyR.gif) ### How it works ``` '1ye}Ju:]rrY6|H!R^ 4Fl^ ··· S+.P{Z}n' % Push this very long string (not shown in % full; it contains 427 characters plus the % 2 enclosing single quotes) T % Push true. This indicates the that origin % base is the 95 printable ASCII chars 210 % Push number 210 V % Convert to string. This gives the % destination base, '210' Za % Base conversion. Implicitly display ``` [Answer] # Pyth, 361 bytes This has too many unprintables for TIO, so here's the hexdump: ``` 00000000: 746a 6b6a 4322 01bd bf32 7574 a357 55f7 tjkjC"...2ut.WU. 00000010: f4ca 74e0 9fbf 89f3 58ad 59c8 798b b009 ..t.....X.Y.y... 00000020: 60bc 0f8a 71f4 a90e da7b 61a6 6145 9a5b `...q....{a.aE.[ 00000030: 2f16 8968 611f 9b8d 75fb a9f0 0308 7d38 /..ha...u.....}8 00000040: 9acd fdf3 53b1 e7be 2fa4 1ce2 6870 fcae ....S.../...hp.. 00000050: 51df 0aec 521b e506 bb84 df0b f439 2917 Q...R........9). 00000060: 7303 8ac3 0d48 489c 727c 3712 4e66 2ed6 s....HH.r|7.Nf.. 00000070: ec54 c5e3 eb14 4b10 8a10 6974 683b fbcd .T....K...ith;.. 00000080: 9976 1731 c976 2d60 b2d8 c644 7641 bcd2 .v.1.v-`...DvA.. 00000090: acfd b4da 6026 341f 8994 7cc8 ef94 ff58 ....`&4...|....X 000000a0: 5b47 47c8 a880 1a8e b8ae 385f 632a 306c [GG.......8_c*0l 000000b0: 4d64 9b80 4e7e fb93 2c51 7484 0e53 2d7c Md..N~..,Qt..S-| 000000c0: 9e46 10ac 9a6d 3d2f 0237 3fa4 9ae8 056f .F...m=/.7?....o 000000d0: 5e2e aca5 ac4b 424c f151 d152 094f 8f57 ^....KBL.Q.R.O.W 000000e0: a644 f6ad 7032 f28c e937 3d2c a65f b434 .D..p2...7=,._.4 000000f0: 8279 4ab3 b349 ec8e 0244 44db 50e6 5426 .yJ..I...DD.P.T& 00000100: b177 d3b0 5f95 6d98 7b7f ba7e 0bac 1131 .w.._.m.{..~...1 00000110: 6f77 2710 c024 05d9 88e2 7194 fb5f 00d6 ow'..$....q.._.. 00000120: 6204 d12b 5620 0020 3ab6 23ea acdd 05cf b..+V . :.#..... 00000130: 254e ebed 0448 f957 64a7 47f8 35fb 368f %N...H.Wd.G.5.6. 00000140: 203e f9c6 aa02 a9f4 4618 c9da 48d0 56d3 >......F...H.V. 00000150: 29ac f370 2178 6d05 e2dc 2985 aca1 8be9 )..p!xm...)..... 00000160: 082c c9a6 dfcd 5e22 33 .,....^"3 ``` To run this, put the above hexdump in `a.dump`, run `xxd -r a.dump > a.pyth`, and then run `python3 pyth.py a.pyth`, using `pyth.py` from the [Pyth repository](https://github.com/isaacg1/pyth). Basically, the program is ``` tjkjC" ... "3 ``` The long string is equivalent to the ternary string with a 1 placed in front, converted from ternary to base 256. `C` converts the string from base 256 to an integer, `j .. 3` to a ternary list of digits, `jk` to a string, and `t` removes the leading 1. By sheer luck, this has no characters that need to be escaped (e.g. `"` and `\` in certain cases), so it's shorter than it would have been otherwise. Unfortunately, Pyth's base conversion takes inputs backwards of the sensible choice, so that adds two bytes, and the required output is a string, not a list of digits, which adds another 2 bytes. [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 431 bytes ``` say 0,:127[q[ ... ].ords].base(3) ``` [Try it online!](https://tio.run/##XVWLVhpJED0QzIbR4xrjK5rFyYhGDTt2NxFBEjcS8KyPSNxEXYIkvCNREQbRIYn76@5M32ogGQ8w3V3VVXXvrbJRsc4jdxcdPWjrr/T18GLrvG01lszG5Xnn4rK8yMWabtvLS6ZVua5YrYpZOrVacU2T5kar0NFZaN0xyjazQTtnXlrlVs4sFlqVxfCSEddcg6BtVuqly3LFLHauKi39P93Q5Ztz7pyljjb34tpcPnv30236zqBRfPw8OvAxmbL9XBsOFsb17/bUyL835fTQ/K3/eHvbXs6c7lrfPPuV8tWzkP1H4PPQm7Bv/8mL9lDE0taMydjupHcjuRgshM3xZ//M/l1tJIeW2vrkD81IrRZvI1d/5o@NbGKHJQ7eecNzheigJ3A6E280f7ywRqNfbzT/QNN8GTIeZbL3N82NoJnSSsvTp4eHtfjeyk0@sXUW1TKlmEeP@fzP78e9Y4ex3c5mcrB9lj0eadbW62P21kD@3XfvRXP9W81T99Vm4tGj3688c4Pa/OxR/I2R6EzFX2eSK1MHsxORg1BJ96X3H4w8zd1ea/4FVhc7H@uHc9WTD2tvG9VSej43/b6Q3mqvNiL3rPZvCc9Lbn5ub49GH2j39CeZjYXjnK/29KE2OdqcsD/V50N6dbO9vPd@xXw1UR6/GY5Ov/U3/iocDC9krPxqpvb6kaekpfh08zawcD180f6aaRbTsbPUOR/T7ZMvJ7VP1dZewAjNJAIfdO8v9N7l7piQf5wx7nycFyG4cBbOt7vB3R0OI2fJsOuspI/z7qwdD9fOeXOt3TNp5u4I192xdR/nRJo4H@nohmIU3tlwT1wj91rpIVPC1YghNynZnqd0dVOSmQnKE/FgzclY5iVPKA13HyEY3SPIhyFd@SuAC6eLmbxYZtm1YbIkuQscGMpx0kby7qYEhX4QjUu0FRpM1eF@yURVWK6yARsSZo7UBMAX8O8GlE6MTnEbygVIEh8iVYAdyROIkxzInJGw6NMCoQ7GyJEhthCkCpmCegCUAItMwcYgI7nJiVdFHlVBWKMQRnoBUEBDdLlAXE7XomZOhXFSpXwE4S2kMgXqIPUzIk7CLHoL6SvAA3JVLMt9pVfGyFahglikaJKfkikHRKq3CGmGGII0IQC5oFuhE5TAoCIijykyIG8IGzCDQUHC46RmtDd0Rgcyd7gDEWiSC6IL6POuyAl0yVdfx/C@puNEMQDggroG6SqSQLYg2EnTuBXzgmYRNQQq4yoWJymrmMgIgRUC0C4BC6gY0U9MQO7EieKKk3pQmMyf9eBR8wwNxnu6xCCFzES3l0hBUAdSotko@tqbppCSDaYI9bpSIvFAY0aQfAR6DeOAI7YEhfcRhxlBzYpmQ4J9YiVhYCQptXCCo9u8nIYqzTIFC@Z5//@EPvUjLd5tQqVLanaimqZld5AreZIcqdmJYPDVm15cocBQO6dJigblVMf/) Uses conversion from base 127. Since TIO can't really handle carriage returns and to a lesser extent NUL bytes, I've generated and then eval'd the program in the header. I'm lucky that the generated string contained three pairs of `[]` so I was able to use the `q[ ]` quoting construct. [Answer] # [Rust](https://www.rust-lang.org/), 551 ~~566~~ bytes (404 ~~405~~ byte code + 147 ~~161~~ byte decoder) ``` fn main(){for x in br#"..."#.chunks(5){let mut v=x.iter().fold(0,|a,x|a*127+*x as u64-(*x>13)as u64);for _ in 0..5*x.len()-3{print!("{}",v%3);v/=3;}}} ``` Formatted: ``` fn main() { for x in br#"..."#.chunks(5) { let mut v = x .iter() .fold(0, |a, x| a * 127 + *x as u64 - (*x > 13) as u64); for _ in 0..5*x.len()-3 { print!("{}", v % 3); v /= 3; } } } ``` Rust source code is always UTF-8. Looking at the [table of encodings for UTF-8](https://en.wikipedia.org/wiki/UTF-8#Description), it becomes clear that ASCII contains the most amount of information per byte (7 bits per byte), while the mult-byte encodings all are less than 6 bits per byte. Because Rust doesn't have arbitrarily large integers, we need to fix a length of bytes we transform at once. In `k` bytes, we can encode $$\lfloor \log\_3 (k\cdot7) \rfloor$$ *trits* (base 3 digits). Looking at these values without the floor, we see that we get pretty close to the optimal information density for `k=5` (4.4 trits/byte vs the optimal 4.4165 trits/byte (for 7 bits per byte)). That means we will encode every 22 trits as 5 bytes. To embed the data in our source code, we can use the raw byte string literal syntax (the `br#"..."#`) to get it as a `&[u8]` instead of a `&str` (byte string), and not needing to escape special characters. I stumbled into the problem that a raw CR (not part of a CRLF sequence) is not allowed in a raw byte string. So I just added 1 to every byte that was above the ASCII for CR when encoding, and subtracted it again. Fortunately we can still fit 22 trits into `5*log2(127)` bits :) Then we just need to avoid printing extra zeroes at the end, which I avoided by checking if the second byte was 7 (which only occurred in the final 5-byte-tuple). **EDIT**: The first byte of the last 5-byte-tuple is zero. We can leave it out to get the same value for `v`, and then we can use `5*x.len()-3` to switch from printing 22 trits to 17 trits at the end, also making the decoder shorter. This also means we are at the theoretical optimum code size! (404 bytes vs 403.0055 (rounded up to 404)) Here's the encoded sequence as a hexdump: ``` 00000000: 2439 7e78 2947 2e4b 167f 4608 6e70 135f $9~x)G.K..F.np._ 00000010: 1741 3f2d 6f1a 226b 641e 782c 1e76 752d .A?-o."kd.x,.vu- 00000020: 0416 4650 045f 473d 3c4e 5229 731b 2961 ..FP._G=<NR)s.)a 00000030: 007f 5b6d 7a71 6a05 3139 7818 2557 747e ..[mzqj.19x.%Wt~ 00000040: 2347 032d 256a 2f4e 7658 6774 4a5a 3700 #G.-%j/NvXgtJZ7. 00000050: 4125 466b 6a2e 5f73 2845 1402 0642 3034 A%Fkj._s(E...B04 00000060: 374d 3902 6379 3f65 5111 2d3c 4453 7540 7M9.cy?eQ.-<DSu@ 00000070: 683c 0629 4f00 2815 4d5a 255e 513b 3a45 h<.)O.(.MZ%^Q;:E 00000080: 1f75 3252 087d 0725 273a 3a35 297e 142d .u2R.}.%'::5)~.- 00000090: 4461 3a3d 086a 5643 4312 2347 305e 7b44 Da:=.jVCC.#G0^{D 000000a0: 1a4a 0e64 4c00 1b6f 0766 2c53 192a 4526 .J.dL..o.f,S.*E& 000000b0: 2f0e 6d2e 3e29 2020 320f 1e59 5a2b 6324 /.m.>) 2..YZ+c$ 000000c0: 2f6f 4000 051c 7503 5459 473e 554a 2040 /[[email protected]](/cdn-cgi/l/email-protection)>UJ @ 000000d0: 6034 445a 6c53 4637 0c1f 4a14 0750 5313 `4DZlSF7..J..PS. 000000e0: 6e08 3500 3615 0355 6c4f 7d64 2f25 594b n.5.6..UlO}d/%YK 000000f0: 5666 310e 3d4d 2a54 761d 5f09 627a 3763 Vf1.=M*Tv._.bz7c 00000100: 3647 0302 2057 1904 7a2d 0003 5b06 5a05 6G.. W..z-..[.Z. 00000110: 4d4c 3a1d 7558 392a 1643 2359 3270 3e1c ML:.uX9*.C#Y2p>. 00000120: 4315 1501 7a4a 3354 1f6a 0f29 6f19 1947 C...zJ3T.j.)o..G 00000130: 172a 6563 0634 442f 4853 3672 1014 6b49 .*ec.4D/HS6r..kI 00000140: 4319 0e12 7903 6a56 467d 5a0f 1313 4658 C...y.jVF}Z...FX 00000150: 526a 5159 362f 5614 3a53 5c6d 2c16 1343 RjQY6/V.:S\m,..C 00000160: 6058 7410 2c17 2d65 5b13 633f 2331 7440 `Xt.,.-e[.c?#1t@ 00000170: 3b1c 0160 765d 1355 6950 3e65 1856 156c ;..`v].UiP>e.V.l 00000180: 7a09 6464 2529 2161 496b 7103 583e 712f z.dd%)!aIkq.X>q/ 00000190: 070e 557f ..U. ``` --- Old code (without the removed null byte at the end): ``` fn main(){for x in br#"..."#.chunks(5){let mut v=x.iter().fold(0,|a,x|a*127+*x as u64-(*x>13)as u64);for _ in 0..(if x[1]!=7{22}else{17}){print!("{}",v%3);v/=3;}}} ``` Formatted: ``` fn main() { for x in br#"..."#.chunks(5) { let mut v = x .iter() .fold(0, |a, x| a * 127 + *x as u64 - (*x > 13) as u64); for _ in 0..(if x[1] != 7 { 22 } else { 17 }) { print!("{}", v % 3); v /= 3; } } } ``` [Answer] # [R](https://www.r-project.org/), ~~454~~ 419 bytes (360-byte string + 59-byte decoder) ``` cat(head(rep(utf8ToInt("I¸{A´ ;ÐÄ ` 3’<ˆp>ƾ]Ò‰}HµÁ‡©+\\m’'šdI°‚Y%ÊúÞ7I\\‰‹Ú(5ÆEÒ&Ì3`NhN·2žJ}¤ø¨~… 5o}F‚UR뀩濌wäo¹¥½QBi›–Ó·ÃRÿ: zW¡wÓ—ÃD“è,ýF醃0;asO „ô%Ϭà¹HÐsëÄÐGew,É׸ªAíDF*ƒ´ÅmO×[ryË*)ÿ?ÛaÁ\rñ§ŒÐS|ØñŽ< {©n£÷6êY•L¡ª}õâ#}°<ͼGÑ%ªŽqE\"&OÞ8yuM:9hø´Z›4ó ôêð|·ô»¶‚bӨ儍Ôåwé°]{Ì–XrúÿlqLbªYa±|@â¨’Vªïk˜RÀØÐY‡­ þÀAй–È{?Û?¹x(vic7-ï@OÛoËI(ã†ó¬Yµ‘fMƒ¡FÐ4‡ý•†ŸÝ”ße(d")-13,e=5)%/%3^(4:0)%%3,-3),sep="") ``` [Try it online!](https://tio.run/##bVbpbxNXEP9cf6BSkaBSi7oyMt4Fp933nBQaSDkEgVRAWo62aU3Fer3UFr7YdZqkIeVICFcAE04RAeVqEwMiiFBIW4g084fRt29mHX/oJrb3HfNm5vf7zez671YatYrh@p5T8wy3Uqr6XhB4OSOo@YXyz52xrBN46b16sK@yRQ1ke7rrUH/ZrRUqZXPQGo69V@oqOWrDoOkVTWUWVIuFmjmYSiYtK9Vhxd5zqtXikFlKyVSLXdBfMp3g03J/yfMLrppYnf7JbO@0LcuKjcSy6a64LfWfsG2hPupGSiHVQH2HEyKcEbRJDW2aVSNto@7VWFmE@9RduDtc09vCGRmaq73hpVb0FvXRhqErm92riXAl3BQeqy10SHQ0@dCTHOyipTYNQ9KRSY6T/NFuwZt1XHqFwwjnyYXN50i2sSlc/SsJF8EH2/pgHWVzj61T0rOEg03pqLAp@HBSg8I/5E1otCM07CiP8EsHGrkVUTTEhoZZUGiSwJdk33SojWxepdMoXQJJ48OkSmJH80TEaQ50zBSwbNECo06MsaFNvqVkVegQoouAksSiHcFmk4z0pGBeI/I4C8aaErFZLwQUoSGbXJBfwcdSzoITE6xKfUnGW2plSsqD1W8zcRpmuTjQtpJ4oFgjlvV8pFfb5r0RKuSLFc3yi2QqCKKothhpm3xI1oQkyCWfSjqhFGxSEZNnR2SQvEnYBDMxKFl4gtVM5U064wUdO5kTIqRJIZkuQl80Rc6ga75aKka0FJ1gigkAIblqKNyIJCJbMuysaTqV@gX3Ii4IykxEvgRLOfJJEZHjCAHSLgNLUNlMPzNBcmdOIq4Eq4cS0/Hbi/BE/YwKTCzqkhopyUw2a4kVROqgkLg3ypby5i4UyYa6CNd6pETmgduMZPlIqjVqB4J8a1BEC3HUI7hYqdgowBaxsjCoJUVqEQxHs3gFN1XuZREs1M9bnwkt6qewRLMII11ysTPV3C2bjTySJ8uRi50JJr4Wu5eIULApd8GdlApUcB7xWDZ8uP7fE9fMpq0YPZK7CuXavsr@2qF1Zrh9jVArKw3XqZm0bhlqVKkOtVWdQD3SadJQRuopX8l5KaPklPudYnFIDX3fc2tGMuMnjVXG7i17vzbcvOM7bs3zAzXj5HJG1nEPB0UnyHtB@KLgBa5T9ZRJaJGMJw2z7Km3BbUSbm4f1CuLh1jvwsDynpMzfa9q9quo91V6yjUz3gOvhzfDnLEe6zi24qCRhskNcKb6JY7D2wM4CWdHdsBLPAGnYWZNJvNRCSaTcCvXA7Nwsi@B5/BvvLO254NMBs7CebxlduD4NpxchRPpg7vzu@GVhDtfjcBDfA3Tv8Epo6My0g0n9@/Bx3AcZvAPWICJAXxYgXl4BG@@2VKAKbiOV@AVju7Bhc4Vv34H9wbU@AaOboUrOJ3CN904A@Mwaq93gt6PYQznEngJnizF32F@B9YDfIxjWN/uDaTwLN6A1@9DYzM@3dq9GkZhDk@VlvXijR/9ITy/@hMLFzbilIMnMj4@hz9hAut7j@JNdX9xwzJjGGbK8ABffY6NPri2E@5BYwRfLsH7K0dgdgNegH@34@UENODikW2ZOFxY1Yt31g3B7f5dnV/koa4ynvsBptrxxQqcw8ZynD2qspqDf@AvOPlhFq8oR49gDKbxKj4awJljMHtgGCfg@ve@wnSheGRnFhp9Djw/ugku4X2Yhslvl0ADnx2Gm3uW4fFjyr7ep2h5auBbPL4ZzsH8coXdmWGV00aYH4Tb5i8Fd23bMXy2qRenKni@By6Z@ADG8QU86YOXcPnQLgXKvW6sty@F0/gGrilg7@JtuIp3PTMXt9pEOuV1dViJzxL8UphIpFNtaSsVeNWueNxSL61u3nMPG7W8UzMCo6D@y7lQiF45FHnOcAIjULovem3ZofDFtqnITlUsJWfQDOittPWVlUolpc63Uk2lWpahLGRHx7v/AA "R – Try It Online") *(Note that copy-pasting within TIO seems to convert some single-byte utf8 characters to multi-byte versions, resulting in a higher reported byte count. See code footer for check that all characters are indeed encodable in single-byte representation. If anyone can suggest how to avoid the utf8 recoding upon copy-paste within TIO, I'd be grateful!)* **How?** The general approach is to encode the base-3 string as a base-243 (=3^5) number, represented by a string of utf8 characters in the range 13-255. The compressed string therefore represents compression to log(3)/log(243) = 0.2 of the original string length. However, to type the string into a program (or, put another way, to be copy-pastable), we need to escape the '\r' (carriage-return), '"' (quote) and '\' (backslash) characters. So the final average compression for base-3 strings is 0.2 \* (243+3)/243 = 0.2024691. In the particular case of the string in this challenge, we need 356 base-243 characters plus 4 escape '\' characters = encoded string length of 360 single-byte characters. Since [R](https://www.r-project.org/) cannot natively handle arbitrarily large integers, we decode character-by-character, which is made possible by using 243 = 3^5 as the encoded number base: so every 5 base-3 digits are independently converted to a base-243 number, represented by a single-byte character. See the TIO header for the code to perform this step. The R decoder is 59 bytes, giving a total size for this particular string of 419 bytes. ``` cat( # output... head( # all first characters of... rep( # repeats of... utf8ToInt("_string_")-13 # utf8 codes of _string_ minus 13... ,e=5) # x5 each... %/%3^(4:0)%%3, # converted to base-3 digits... -3) # except last 3 characters... ,sep="") # joining digits without spaces ``` [Answer] # [Ruby](https://www.ruby-lang.org/) + `bases`, 588 bytes ``` $><<?0+Bases.val('43ur6p5v87byc6oertnvopy75perajuyj6vvdx4dirisox7zjv1cn2viaoe4ta62al6phj2yiy8wqrx1yki34ihtmasmgf42gboode2gkhqu50yw3ttiblo95td8gb692jshoixb66h1mmcrfekd154h5gvo9b0p98hy6dj8oeq1nn9hihzyah1fmb9i9oqf38x8xrgabaldnxf5d1okwf7gagydqlctacv9x9r8shhnkrcj7xf34rgj3c6gb54kd8apxealduij2tecvzd31re7u1kc0ddesug9zp064abj4yrnoydre17zrfmjlpcho43146gase8zk9kkl348mopxx3qkcdepo3svrxtezb4jra4bzdjn1tytt76g74hroej9zaswy9zb0q55p3urqcbjqylcjhtxjtiadvmosf2ytxznjh3980mxkntwz4thp10ldkowsxymmhpuvbw5o0wh2t5uke1k896sjb4e07txzory0mgqj8jsrupiuvj4x19ncfyo2rspdx4u5wryx6lrlo1bncpi3').in_base(36).to_base(3) ``` I tried converting across multiple bases, and got the shortest string at base 36. This is a pretty simple number conversion. [Try it on repl.it!](https://repl.it/join/vvoqocct-razetime) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 361 bytes ``` “¥ḷɗ4ḄṄƥƭ&Ȯ¡ƲẓḃsÑ}G⁸ƲkẈ$ọ,Ŀ²|6ñĿṘỵHṬżṁm;=İḥɼḶɲ8Œ5Ɓ).yṙṛ7ṫʂṃ¶\Æ\gḷ¢KÞŀȮ]zƇẎẠ×ȷ÷;|Dy[¬Çe⁶Mỵ}ʋ⁵Ż;⁷ɱċlı7¦ĊĠƈỵOḄK³Ñ"}ȷɗİʠỤ,ɓÐṣẓẠẎDỊxĊċ0€⁷ɠ,wⱮȧ)u÷⁷⁵@ṬƓƑLị?`ẊạʋɠḂȧĖ>xRḢ"ls⁾Ạ"×Z⁴Ḃq^ẈƁç⁾ỴM!Ƥzẏ¹G6µ-ż0zĠ⁾Ḅ€Mɦ?ĖḞ/eẸ¹/⁼%Ġ Xẹxȷ`1ḄÄkÄ;Ṫɲ<fLW&Yɲ¡U6ẏu3ƇAɱỤḶWF°SS⁸ṪvC[`°½ḍẏ¬Äạr¿pFR0ḋ@#⁷Ʋyc\⁸ÑQÐẉⱮ#BĠƲ§×ỵMẎṾɠẆ⁹ḲlƲ5ḥÐ}ṘṄḟ|(Ẓ]¶J¿Ȥŀ;µỊ(ȤỌ⁾ÆV²ċ#ɓ¿ŀmYœʋƈḊḟ¬ŀ*ỴḂĿq⁴ḣ¹3¡r⁽Ẋø*+ƇṄỌRƘ’b3ŻṾ€ ``` [Try it online!](https://tio.run/##HZL9ThNBFMVfRUEJIAoGAZOqoBIwQmOEKCJgiAZNpCR8BKWEJl3YAHZBKU0oRINbKDTRStqVtjO7hSYzs5PdvsXdF6l3/XNyP849vzMfp0KhcK3mRX@wEyAlN3kHiApUlSfyT4NzxlLSADMBZG2BxyP9nkKkMQ3m5jWwtltEhRkrnTwvKkD3wSo8AZq1y0CVmcB9kQNy4paBFF3jrr3bIZWmW2GgB0C/dwH9XV0FusaK43x9/APKsqMBfmhHnbOJZbkB5lcwdZ50SrwUWOkNj7Es35jylGIQNSJVzVMKthXwlJKbF1pI5LvYqYgJXW5i@RleP8D@8nhdxEEzIlfVwUq3uAm@A/TYd2LquL8XrNgSDmlt3mrW36S3fPbyZ06maZGX8I0SPWhGJmR8ECytexLMGJipqubqQFadjNh7sDQE5KgutOApl7izjidfe8o5FufeIB6p8IxfsM6DV2V6GcxvjPZ3ssJNu9y2LHS/RFSUDrqn3WIPyGHrFJiE0VZPKV8X@pVXYNIlpzR5G9u4Os3VANBfrnHv/eBIw6hrsNSLTty52C43Hrp5NIiYR/pYbngYA8LOT4/HJlmOXQDZ9qWzXMXj51lltm@oDYjWU48WpRF@N47tPP4c2Zhf0H79I6RosAxPIsmgHwO9RMPmuqdQIEZIGh0YKt@J@HFTFcjPlUYwdydY8SmrOGk7GmAFBNvopMHaQo98/SUzhFbvJljFjs6M2omqhimRGE6yrB1tRj5ITFTm/qM7ZrSdpeY95QJpc9J8A78CqlhbQ3Lfix68bbctPAip1Wr/AA "Jelly – Try It Online") Mostly for completeness. Jelly is slightly worse at compressing than 05AB1E because it uses base 250 instead of 255, but on the other hand, it seems to take fewer bytes to display the number, though it's still 2 bytes longer overall. ## Explanation ``` “...’b3ŻṾ€ Main niladic link “...’ The integer in base 250 b3 Convert to base 3 Ż Prepend a zero Ṿ€ Unevaluate (convert to string) each ``` [Answer] # Deadfish~, 3366 bytes ``` {{i}ddddd}ddciicddciicddciicddcicdcciccdcciicddciciccdcicddccicicdcicdccdccicicddcicicdcdciicddciicddciicdcdcccicicdccdccciicddcciicddcicdciccdciicdcciccdcdcicicddciicdcccicddcicdciicddcccicicdccicddciicdciccddcicicddcciicccccdcdciiccdcccicdcccdciccdciicddciciccddcciicddciicddciicddcciccccicdciccdcdccicdcicdcciicccdcdcciccicdcdcicicddcicciccdcdcciicccdcicddciicddcicdcciicddcciicddciicddciicddccciccccdccciiccdccdcciiccddciicdcdccciicccdcdciicdcicddciicddciccicddcciicddciicddccccicicddciicccdccccicdcccicddcciicdccicdcdcicdcccciccccicddciicdcicddciicddcciiccdcdciiccddcciiccdcicdcdcciicddciccdciicdcdccciicddciicdcdciicdcdcicdcicdciicdcdciiccddcciiccddciccdciccicdcdcicdciicddciicdcccdcicccicdcicdcicccddcicciccddciicdccdcicicdccccdcicicdccdccicccccdciciccdccdciccdciicddcicdcicccdccciiccddccciicdcicddciiccddciicddciccdciicdcciccdcdciiccddccicicddcicicdcccicddciccdciiccdcicdcicccdcdcicicccddcicdciccicdcicccddciccicddciicdccicddcicicccdcdcicdciicdcicddciicdccicddcciiccdccdcciicddcciicccddciicddciicddciicdcicddciicccccddcicicddccccicicdcccdccicdciiccddciicdcicdccccdciiccdcicdccdccicicddcicdciicddciicddciicddciicddccicccicccccddcicdccicdcicciccccddcciicddcicdciiccddci{c}dcicdcicdciiccddcicicddciccdccicdcicdciicdcdcciicdccdcccicicddcicccdciicccdcicddccciiccddciicdcdcicicdcicccddcccciicddciicdcicdccicddcicdcicdciicddciciccdcdciicddcicdciicdcdciiccddciicddciicddciicdcdciicdcdciicddcciicddcicccdcciicdccdciiccdcdcicdciccicddciiccccdccccicddcicdcccccciicdciccdccdciciccdciccddciiccddciicddccicdciicddcicdccicdcciicdcccdcicicddcciciccddciicdcccdcicicddcccicdccciicdccdciicdccccdciicccddcicdciicddciicdccdccciicdcdccicdcicdcciicddcciicddcccicdccicicccccddcicicdciccdcciccdcdccicdciicddciicddccccccciiccdccdciciccddcicccicddcicicdcdciicddcciicdcicdcccdcicdciicdcccicccdccdciccicdcdccicicddciicddccicdccicicdccdciccdcciicdciccdcdcicdcicicdccicdcicddciicccddcccicccicccddcicicddciiccdcccicddccicdciicdcdccicicdcccciccdccccdcicciccdcicdcdccccicicdciccddccciicdccccdciccicddcccicdcicicddciiccdcdcicdciicddcicccdciicddciccicdcdciicdcdcciiccddciciccdccccicdcdcicdciicddcicdciicddcciicddcciicdcdciccicddciicddcciiccdcdciicdccdciicdcicddciicddciccicdcccdcccicicdcdccicdciicdcicddciicdcdcicdcicicddcccicciccdcdcicdcicccicdciccccddcicicddccicicddciiccdcicdcicddciicdcdcicccdciiccdccicddccicicdciccdcicddciiccddcicicddccicdciciccdcdciicdccdcicdciicddcciiccccdcicddciicddciccdciicddcciicdccccdccccicdciicdcdcciccicdccdcciicdcccicccddcccicccdciicdciccddciiccdccdciciccddcccicdciiccdciccddciccccdciicddciicddcccicdciiccccdccdcciiccdcdcciicdcicddcciicddciiccdcdcicdciicddciiccccdcdciicccccdcdciccicdcdciicddcicdciicdcdccicdcciccciccdccdciiccdcccdccicdciicddccciicdccdcicdcciciccddciccicdccicdciccddciciccddciicdcciccdcdciiccddcicdccccicciccdcciccdcdciccdciccccicddciccdciicdcicddcccicdcciicddciciccdccdciicddciicdccciccdcdciicddcciiccdccccccicdcicccdccicdccdciiccccdcicddciciccddciciccdccccicccddcicdcicdccicdciccicddcciiccddciiccdcccdcciicddcicicdciccdcciccddcicicdciccddcicdciccdciicccdcicdcdcccicdcccicdciiccddcicdcicdciicdcdccicicddciccicddccicdcicicdccdciicddciiccdcdcicdciciccddcciicdccdciicdcciccdcdcicicccdcdccicdciicddciicddciccicdccdcicdccciicdciccdcccccciccdccicdcicccddcciiccdccicddcciicddcicciccddcicdcciiccddciicdcdciccccdciccicdcccdciicddcicdciicdcdciicddccicccdcccciicddciccccicccccddcicicddccicccccccicdcdciiccdcicddciccicddccciicdcicdcdcicdcciicdcdcicdcccicdc ``` Who cares about compression? [Answer] # [Deadfish~](https://esolangs.org/wiki/Deadfish%7E), 3354 bytes ``` oiioddoiioddoiioddoiodooioodooiioddoioioodoioddooioiodoiodoodooioioddoioiododoiioddoiioddoiiododoooioiodoodoooiioddooiioddoiodoioodoiiodooioododoioioddoiiodoooioddoiodoiioddoooioiodooioddoiiodoiooddoioioddooiiooooododoiioodoooiodooodoioodoiioddoioiooddooiioddoiioddoiioddooiooooiodoioododooiodoiodooiiooododooiooiododoioioddoiooioododooiiooodoioddoiioddoiodooiioddooiioddoiioddoiioddoooioooodoooiioodoodooiiooddoiiododoooiiooododoiiodoioddoiioddoiooioddooiioddoiioddooooioioddoiiooodooooiodoooioddooiiodooiododoiodooooiooooioddoiiodoioddoiioddooiioododoiiooddooiioodoiododooiioddoioodoiiododoooiioddoiiododoiiododoiodoiodoiiododoiiooddooiiooddoioodoiooiododoiodoiioddoiiodooodoioooiodoiodoioooddoiooiooddoiiodoodoioiodoooodoioiodoodooiooooodoioioodoodoioodoiioddoiodoiooodoooiiooddoooiiodoioddoiiooddoiioddoioodoiiodooioododoiiooddooioioddoioiodoooioddoioodoiioodoiodoiooododoioioooddoiodoiooiodoioooddoiooioddoiiodooioddoioiooododoiodoiiodoioddoiiodooioddooiioodoodooiioddooiioooddoiioddoiioddoiiodoioddoiioooooddoioioddooooioiodooodooiodoiiooddoiiodoiodoooodoiioodoiodoodooioioddoiodoiioddoiioddoiioddoiioddooioooioooooddoiodooiodoiooiooooddooiioddoiodoiiooddoi{o}doiodoiodoiiooddoioioddoioodooiodoiodoiiododooiiodoodoooioioddoiooodoiiooodoioddoooiiooddoiiododoioiodoioooddooooiioddoiiodoiodooioddoiodoiodoiioddoioioododoiioddoiodoiiododoiiooddoiioddoiioddoiiododoiiododoiioddooiioddoiooodooiiodoodoiioododoiodoiooioddoiioooodooooioddoiodooooooiiodoioodoodoioioodoiooddoiiooddoiioddooiodoiioddoiodooiodooiiodooodoioioddooioiooddoiiodooodoioioddoooiodoooiiodoodoiiodoooodoiioooddoiodoiioddoiiodoodoooiiododooiodoiodooiioddooiioddoooiodooioioooooddoioiodoioodooioododooiodoiioddoiioddoooooooiioodoodoioiooddoioooioddoioiododoiioddooiiodoiodooodoiodoiiodoooiooodoodoiooiododooioioddoiioddooiodooioiodoodoioodooiiodoioododoiodoioiodooiodoioddoiioooddoooioooioooddoioioddoiioodoooioddooiodoiiododooioiodooooioodoooodoiooioodoiododooooioiodoiooddoooiiodoooodoiooioddoooiodoioioddoiioododoiodoiioddoiooodoiioddoiooiododoiiododooiiooddoioioodooooiododoiodoiioddoiodoiioddooiioddooiiododoiooioddoiioddooiioododoiiodoodoiiodoioddoiioddoiooiodooodoooioiododooiodoiiodoioddoiiododoiodoioioddoooiooioododoiodoioooiodoiooooddoioioddooioioddoiioodoiodoioddoiiododoiooodoiioodooioddooioiodoioodoioddoiiooddoioioddooiodoioioododoiiodoodoiodoiioddooiioooodoioddoiioddoioodoiioddooiiodoooodooooiodoiiododooiooiodoodooiiodoooioooddoooiooodoiiodoiooddoiioodoodoioiooddoooiodoiioodoiooddoioooodoiioddoiioddoooiodoiioooodoodooiioododooiiodoioddooiioddoiioododoiodoiioddoiioooododoiiooooododoiooiododoiioddoiodoiiododooiodooioooioodoodoiioodooodooiodoiioddoooiiodoodoiodooioiooddoiooiodooiodoiooddoioiooddoiiodooioododoiiooddoiodooooiooioodooioododoioodoiooooioddoioodoiiodoioddoooiodooiioddoioioodoodoiioddoiiodoooioododoiioddooiioodooooooiodoiooodooiodoodoiioooodoioddoioiooddoioioodooooioooddoiodoiodooiodoiooioddooiiooddoiioodooodooiioddoioiodoioodooiooddoioiodoiooddoiodoioodoiiooodoiododoooiodoooiodoiiooddoiodoiodoiiododooioioddoiooioddooiodoioiodoodoiioddoiioododoiodoioiooddooiiodoodoiiodooioododoioiooododooiodoiioddoiioddoiooiodoodoiodoooiiodoioodooooooioodooiodoioooddooiioodooioddooiioddoiooiooddoiodooiiooddoiiododoioooodoiooiodooodoiioddoiodoiiododoiioddooiooodooooiioddoiooooioooooddoioioddooioooooooiododoiioodoioddoiooioddoooiiodoiododoiodooiiododoiodoooiodo ``` [Try it online!](https://tio.run/##fVZNj9owEL3zK6IcSrLLrqC9VKly6k/okSJUMUGxtOuJQlC7Rfx2mgTb88YJ5RAR25mPN2/euPnoarZfvjbtjapj8pYd8mKR1OV2t0iO3CZmxYmxSWXP71X7q6vu@4k5JlyWy8uyqJ/LrdnJ0nU57CdU1q8NN1k@vPRbb5XN6rws10VbdefWJoctFeZ5s1sMbik7rGy5XtXlejD/f8d14Wz27tJrWtQv5QZWLukQ07hyYNsZe64kOrMs7H3TLVC/8IILp37h6an8LCu8LJrW2C6zq8pSmaa57B383qFuM5tPD1zucOz71Hpst6bY5dtN8bLZrcYIx0z7PLfr3dNmXdiSsv3K9t87lOyn9Z/jcUFZU5TGNucuy/Nv@715b7jt9vssPX2c0vz11FHVtq@/W9MDdUy/M1XJD/O3KpLLAHyTX3/aNL/dbmwME@knE/eP8ekWxrfx//jizvg3cos0MTYccZv3v85G8HM3LB4pWDTuW3/w/qU3JmeGz8JXw9Lwc7F4E8zoyickgcCTRwMhNGJJd7Ttlny@PkA5bThghXCaR/7uDh04HlWXVEDQSE6RbZ4aZgYQ76YZ0Axwk09Mkp56cFGRj8m9m5AtYRGlxkYIwRQwlFWx5b/HkAxyYNwTE8wAuT/kKcjw1xeTA4NjFjhrHCJhnb8COuapzwE7IBA28E@cuCjAc5wOiQsKpxG5@IimTOA/zTSi8EH1S2iowHRAVQANqaiepznxkC4CZ6GNHNu1BjiXF74qpkCchrETDbCPRWI80NiCcS8ZBF2TFZFX2UHFaY7GM6JnUA6FQhh06CtW1YeGDQVgUTogc3CuYI9EPDhk0EjVObDhKSwRQv2nJRdJj2VSkvYxsGZeKCh8qxUM9TAEzDw3bpCsUB/2iIO24HQhiE2kAaD2tQH6kmAhHCccWqizSFVQ2qBSjFLKgIxUgYEdLPFE9NHkJxRTaRXgMs9obUxX6ZhH40BIMplIDG2JBWbVJJp6GnRRRzXeMfmpPemr6LISazpWiOOMFBLTaR7xDiesVFvEEqgonMSbS8xy0GHgPU@vDaAXUBjAWb6YDla4JIUpoy9xKh@RdBAv1r3LCkLsWhwAcP2am6fSJkoiPBrRgCWlXEqv41uEEvGQAPCMQtF02XnaOoxTQik46HEAyMzJHql2x6swakK4UyA8E11B93j9mSk/Xnxnr94PFFkYDTMCMQQgEOBoAEKN47kMUsf8YNr6mwWObtY3DbjEMxBaqslGX/RwbEl6/fMf "Deadfish~ – Try It Online") The TIO link links to an interpreter I made in Python. The interpreter that already exists in TIO crashes since the code is too long. First time using Deadfish~ ]
[Question] [ # Mountain range number A number is a mountain range number if the inequalities satisfied by their consecutive digits alternate. In a way, looking at the number's digits should exhibit a `/\/\/\...` or a `\/\/\/...` pattern. More formally, if our number `n` has \$k\$ digits $$n = d\_1d\_2d\_3\cdots d\_k$$ then `n` is a mountain range number if $$\begin{cases}d\_1 > d\_2 \\ d\_2 < d\_3 \\ d\_3 > d\_4 \\ \cdots \end{cases} \vee \begin{cases}d\_1 < d\_2 \\ d\_2 > d\_3 \\ d\_3 < d\_4 \\ \cdots \end{cases}$$ # Your task Given an integer with 3 or more digits, output a Truthy value if the number is a mountain range number or Falsy otherwise. # Input A positive integer `n` with 3 or more digits, in any reasonable format, e.g. * Integer * String * List of digits # Test cases ### Truthy ``` 1324 -> Truthy 9191 -> Truthy 12121 -> Truthy 121212 -> Truthy 1212121 -> Truthy 19898 -> Truthy ``` ### Falsy (Added another Falsy test case as per the comments, some answers might not cover the 4422 test case) ``` 123 -> Falsy 321 -> Falsy 4103 -> Falsy 2232 -> Falsy 1919199 -> Falsy 4422 -> Falsy ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer in bytes wins! Standard loopholes are forbidden. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` ¥ü*0‹P ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0NLDe7QMHjXsDPj/39DYyAQA "05AB1E – Try It Online") With truthy and falsy reversed, this would be 5 bytes: ``` ¥ü*dZ ``` [TIO](https://tio.run/##yy9OTMpM/f//0NLDe7RSov7/NzQ2MgEA) [Answer] # [R](https://www.r-project.org/), ~~44~~ 40 bytes crossed out 44 is [still](https://codegolf.stackexchange.com/q/170188/86301) regular 44 -1 byte thanks to Giuseppe. ``` function(x,d=diff)all(d(sign(d(x)))^2>3) ``` [Try it online!](https://tio.run/##K/qfpmD7P600L7kkMz9Po0InxTYlMy1NMzEnRyNFozgzPQ9IVWhqasYZ2Rlr/k/TSNYw1DHSMdbU5AKxjYFsQyjbUAfEM4HyTHQMdQzg6iyBPEu4SiOQCTpGcH1AM1DMgfIxVaCogpoJxJZIYhYgrKn5HwA "R – Try It Online") Computes the differences of the signs of the differences of the input. These must all be equal to 2 or -2, i.e. the square must equal 4; checking that the square is >3 is sufficient. If two consecutive digits are equal, there will be a 0 in the signs of differences, leading to a difference of signs of differences equal to 1 or -1. If three consecutive digits are in ascending or descending order, then the corresponding differences will be of the same sign, leading to a difference of signs of differences equal to 0. If neither of these occurs, the number is a mountain range number. --- Old version (included as it might be golfable): # [R](https://www.r-project.org/), ~~44~~ 43 bytes -1 byte thanks to Giuseppe. ``` function(x)all(s<-sign(diff(x)),rle(s)$l<2) ``` [Try it online!](https://tio.run/##K/qfpmD7P600L7kkMz9Po0IzMSdHo9hGtzgzPU8jJTMtDSikqVOUk6pRrKmSY2Ok@T9NI1nDUMdIx1hTkwvENgayDaFsQx0QzwTKM9Ex1DGAq7ME8izhKo1AJugYwfUBzUAxB8rHVIGiCmomEFsiiVmAsKbmfwA "R – Try It Online") Computes the signs of the differences of consecutive digits. Then verifies that * none of the signs are 0s (would correspond to 2 equal consecutive digits); * the runs of the signs are all equal to 1, i.e. no 2 consecutive signs are equal. [Answer] # JavaScript (ES6), ~~35~~ 33 bytes ``` a=>!a.some(p=v=>a*(a=p-(p=v))>=0) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1k4xUa84PzdVo8C2zNYuUUsj0bZAF8TR1LSzNdD8n5yfV5yfk6qXk5@ukaYRbahjrGOkYxKrqakAAfr6CiFFpSUZlVxoKi11DHWAmAiVhkATwRimlrBKHSOIWmJUQszFo9JSxwKEMW3HZqgxwkNgpW6JOcUYZhoj@wafQhOgAw2QzcSl0AhkNczX@BSCAx2KLaEeByv8DwA "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input list of digits, // re-used to store the last difference !a.some( // p = // initialize p to a non-numeric value v => // for each v in a[]: a * ( // multiply a by a = // the new value of a defined as p - // the difference between p and (p = v) // the new value of p, which is v ) // >= 0 // the test fails if this is non-negative ) // end of some() ``` [Answer] # Jelly, ~~[7](https://tio.run/##y0rNyan8/9/z8PRjcx/uXGCr@3DXgv@H2x81rfn/PzraUMdYx0jHJFaHK9pSx1AHiEFMQ6AYGKNwdIzQuDB5Sx0LEIbJGoMYxjBpE6BKA4iYEUgSZgrUOiC2jI0FAA)~~ 6 bytes A benchmarking solution. A monadic link taking as input the list of digits ``` I×Ɲ<0Ạ ``` You can [try it online](https://tio.run/##y0rNyan8/9/z8PRjc20MHu5a8P///2hjHSiMBQA) or [verify all test cases](https://tio.run/##y0rNyan8/9/z8PRjc20MHu5a8P9w@6OmNf//R0cb6hjrGOmYxOpwRVvqGOoAMYhpCBQDYxSOjhEaFyZvqWMBwjBZYxDDGCZtAlRpABEzAknCTIFaB8SWsbEA). ``` I Take the forward differences Ɲ and for each pair, × multiply them together. <0 Check if those are below 0. Ạ Check if this array of booleans only contains Truthy values. ``` *-1 byte* thanks to @79037662 [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-!`](https://codegolf.meta.stackexchange.com/a/14339/), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes input as a digit array. ``` äÎä* dÄ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=5M7kKiBkxA&input=WzEsMiwxXQ) [Answer] # [Haskell](https://www.haskell.org/), ~~57~~ ~~55~~ ~~47~~ ~~44~~ 42 bytes ``` all(<0).z(*).z(-) z f(x:s)=zipWith(f)s$x:s ``` [Try it online!](https://tio.run/##LYpBDsIgFET3PcVfuABDDR9cSGPP4aI2kVhRIq1EGtP08CIYNjN5b@ahw/PmXDTtOWrnyJHT3Uq2OWparWDI0gTartaf7PwghoZNEnGwdzsH4NBC11eFlkQLXMbXcAHk0EDxJMnBfrKkVTVqO6Wjf9tp3ozag/ln@XYoJJMCGUqxZ3vkkilUyISQgqHAvOQskDHvSqU@qEMfv1fj9D3E@ur9Dw "Haskell – Try It Online") Takes input as a list of digits. * -2 by swapping the order of `s` and `x:s` * -8 by using a different helper function * -3 by using partial application and pointfree code * -2 by excluding `f=` from the submission (which I didn't realize was allowed :P) [xnor improved my answer using `>>=`.](https://codegolf.stackexchange.com/a/199086/89930) [Answer] # [Python](https://docs.python.org/3/), 47 bytes ``` f=lambda a,b,*l:l==()or(a-b)*(b-l[0])*f(b,*l)<0 ``` [Try it online!](https://tio.run/##fZCxCoMwFEX3foXQwbzwAsY4VGnWfkE3cUgoYiFVsXbw61NjKkprDdwpJ@fdl3boq6YW1pbSqIe@qUChRmoyIyWBpiOKaaBEM5NHBdCSuEs4R7bt7nVPSkJzjgJjTAqAwJ9jcO1efTUcFiZFjmN2GT5apszUHoOxp/YZ79pkUjy5/JkVspByDl9WsfR3Ly7KPNdSsS6/jSRjq2jt@UViN2hebxuZ/vKT1G84IfYN "Python 3 – Try It Online") Takes input splatted like `f(1,2,3,4)`. Same idea as my second [Haskell answer](https://codegolf.stackexchange.com/a/199086/20260). [Answer] # APL+WIN, ~~17~~ ~~15~~ ~~12~~ 11 bytes 5 bytes saved thanks to Jo King & 1 byte thanks to Bubbler. Turning into a real team effort! Prompts for list of digits: ``` ×/0>2×/2-/⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4fnq5vYGcEJI109YFS/4GC/9O4DBWMFYwUTLjSuCwVDBWAmAskZqQAxshsBSOuNAVkLlTaUsEChKFKjYG0MVTOBKjKACxiBJIBGQBWD8OWAA "APL (Dyalog Classic) – Try It Online") (Dyalog Classic) [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` Λ<0Ẋ*Ẋ- ``` [Try it online!](https://tio.run/##yygtzv7//9xsG4OHu7q0gFj3////0YY6RjrGsQA "Husk – Try It Online") Algorithm taken from the APL answer. ## Explanation ``` Λ<0Ẋ*Ẋ- Ẋ- subtract pairs of consecutive elements Ẋ* multiply pairs of consecutive elements Λ return truthy value if all elements are: <0 lesser than 0 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), (5?) 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) 5 if we may invert the truthy/falsey output (strip the trailing `¬`). ``` IṠIỊẸ¬ ``` **[Try it online!](https://tio.run/##y0rNyan8/9/z4c4Fng93dz3ctePQmv@H2x81rfn/PzraUMdYx0jHJFaHK9pSx1AHiEFMQ6AYGKNwdIzQuDB5Sx0LEIbJGoMYxjBpE6BKA4iYEUgSZgrUOiC2jI0FAA "Jelly – Try It Online")** [Answer] # [Haskell](https://www.haskell.org/), 37 bytes ``` all(<0).g(*).g(-) g=(=<<tail).zipWith ``` [Try it online!](https://tio.run/##LYpBDoMgFET3noJFF9Cg4YMLaeQcXVgTiVYkRUsqaUwPXyqNm5m8NzPp9XF3Lo7qFrVzuGakMPicIieZUVjVddDWkeJj/dWGKQ7W2LAihhRq2uygbacNdfNz6BAwdEGHx7sc7DtJkmWztst@9C@7hNOsPRr/eXwb4IIKDhQEL2kJTFAJEijnglPgkJaUByRMu5R7V7Jq47cfnTZrzHvvfw "Haskell – Try It Online") Takes the `zipWith`-based [answer of 79037662](https://codegolf.stackexchange.com/a/199061/20260) and generalizes out the pattern of ``` g(?) = \s->zipWith(?)(tail s)s ``` that applies the operator `(?)` to pairs of adjacent elements. This is shortened to the pointfree `g=(=<<tail).zipWith`. We first apply `g(-)` to the input to take differences of consecutive elements, then `g(*)` to take products of those consecutive differences. Then, we check that these products are all negative, which means that consecutive differences must be opposite in sign. --- # [Haskell](https://www.haskell.org/), 40 bytes ``` f(a:b:t)=t==[]||(a-b)*(b-t!!0)<0&&f(b:t) ``` [Try it online!](https://tio.run/##LYrLCoMwFET3fsUViiQlQm7iwkjzJSIYsbbBR6WG4sJ/TxPIZoZzZt7mmJ/L4v1ETDM0jmqnddtdFzHlQO9kKF2ec/rgRTGRuPvRvqw7gIOGtssSnYFO6NfP2ANyaCB5EuRof1HSLFuN3cJx/9rNwQ1Ws8OUOv1bFJJJgQylqFiFXDKFCpkQUjAUGJeYCSLGXanQtao7/wc "Haskell – Try It Online") The idea is a bit clearer to see in the slightly less-golfed form: **42 bytes** ``` f(a:b:c:t)=(a-b)*(b-c)<0&&f(b:c:t) f _=1>0 ``` [Try it online!](https://tio.run/##LYpBDoMgFET3nuIvGgMNJnxwIaT2IsZU1NKSqjXVNN6eQspmJu/NPM32uk@T95YY3etB77QmpujpmfTFQC88zy35@8zCrcYr96N7uH0DDjU0bZboCHRAN7/HDpCDhuRJkKP7RkmzbDZuCcf145YdTjCbFWzq9G9QSCYFMpSiZCVyyRQqZEJIwVBgXGImiBh3pUJXqmr9Dw "Haskell – Try It Online") We check that the first three digits `(a,b,c)` have the `a->b` steps and `b->c` steps going opposite directions by checking that the differences `a-b` and `b-c` have opposite signs, that is, their product is negative. Then we recurse to the list without its first element until the list has fewer than 3 elements, where it's vacuously true. An alternative to check suffixes directly turned out longer: **43 bytes** ``` f l=and[(a-b)*(b-c)<0|a:b:c:t<-scanr(:)[]l] ``` [Try it online!](https://tio.run/##LYpBDoMgFET3nuIvupAGEz@4EKInISSi1JZUqVHTuOjdKSRsZvLezMsc78eyhDDD0htvVWmqkdzLsZpIV/@MHOUkz646JuP3UhKlFx2se7rzgBp6ULrIdEW6YFg/dgCsQUL2ZZTWfZMkRbEa5@Nx250/4Qar2WDOnf8KGaecIUXOGtpgzalAgZQxzigyTEvKDAnTLkTsVrQ6/AE "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~65~~ 58 bytes ``` lambda A:all((x-y)*(y-z)<0for x,y,z in zip(A,A[1:],A[2:])) ``` [Try it online!](https://tio.run/##bY1BDoIwEEXX9hTdtZUS6JQFJWrCBbgAElJjiCSAxLgQLo/TgsaFmWT@/Pd/03F63u4DLM3xvHS2v1wtzTPbdZy/wkns@RTO4hA39wd9yUnOtB3o3I48l3mpsgo3ZJUQiysULiyZ0pAwSZlRRjlVgPM9wF8mNemKtBO9FhIVewugt5ob46MEgFUZ2Y2PdnjSAlF4wqDhvR05IlkIQQhjjNg6JhxXYGslIiD8x9CA2hocRRYl3qpNwXX/Yq/68yrd4nSL15rGFH9f3g "Python 2 – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes ``` ¬{s₃.o↙Ḋ} ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9Ca6uJHTc16@Y/aZj7c0VX7/3@0oY6ljgUIx/4HAA "Brachylog – Try It Online") Takes a list of digits as input. ### Explanation ``` ¬{ } It is impossible… s₃ …to find a subsequence of 3 elements… .o↙Ḋ …which is already ordered ``` Slight subtility: `o↙Ḋ` is used to check whether the digits are increasing or decreasing. By default, `o` (which is the same as `o₀`) is for increasing order, and `o₁` is for decreasing order. By using `o↙Ḋ` (`Ḋ` being an integer between `0` and `9`), we check that the whole predicate is impossible for `o₀`, or `o₁`, or `o₂`, …, `o₉`. `o₂` to `o₉` are not implemented and thus will fail, which doesn’t impact the program as a whole. If `true.` is an acceptable falsy value, and `false.` an acceptable truthy value (which I don’t think it should be), then you should be able to remove these 3 bytes: `¬{…}`. [Answer] # Excel (Insider build ver. 1912), 122 Bytes ``` A1 'Input B1 =SEQUENCE(LEN(A1)) C1 =MID(A1,B1#,1) D1 =SIGN(IF(NOT(B1#-1),C1-C2,C1#-INDEX(C1#,B1#-1))) E1 =(SUM(D1#)=D1*ISODD(LEN(A1)))*PRODUCT(D1#) 'Output ``` Returns ±1 (truthy) or 0 (falsy) Explanation (can add more detail if people are interested) ``` B1 =SEQUENCE(LEN(A1)) ' Generates a spill array from 1 to the length of the input C1 =MID(A1,B1#,1) ' Splits characters into rows. Using each value in the spill array B1# ' as a charcter index D1 =SIGN(IF(NOT(B1#-1), ' Choose different value on the first cell C1-C2, ' Use the opposite of the first difference between digits C1#-INDEX(C1#,B1#-1))) ' get the difference between each digit and the previous E1 =(SUM(D1#)=D1*ISODD(LEN(A1))) ' Sum the digit differences, if the ' input length is even check if 0, else check if equal to ' thefirst row of the differences *PRODUCT(D1#)) ' ensure there aren't any repeated digits ``` Tests [![enter image description here](https://i.stack.imgur.com/UxYwg.png)](https://i.stack.imgur.com/UxYwg.png) [Answer] # [Ruby](https://www.ruby-lang.org/) `-nl`, ~~57~~ 41 bytes Replaces each character in the input string with the `cmp` comparison (`<=>` in Ruby) between it and the next character `$'[0]` (if there is no next character, remove the character instead). Then, check if the resulting string consists entirely of alternating `1` and `-1`. ``` gsub(/./){$&<=>$'[0]} p~/^1?(-11)*(-1)?$/ ``` [Try it online!](https://tio.run/##KypNqvz/P724NElDX09fs1pFzcbWTkU92iC2lqugTj/O0F5D19BQUwtIatqr6P//b2hsZMJlaWhpyGVoBIQQ0ojL0NLC0oILzDIy5jIGSpgYGhhzGRkZg@RA0PJffkFJZn5e8X/dvBwA "Ruby – Try It Online") ### Old Solution, 57 bytes Check for duplicate consecutive numbers first by checking if the input string matches `/(.)\1/` and inverting it. If no such pairs are found, replace each character with `true` or `false` based on whether its `cmp` style comparisons (`<=>`) to the character before it `$`[-1]` and after it `$'[0]` are not equal. (If there is no character before or after it, the `<=>` returns `nil`, which is definitely not equal to whatever the other character comparison returns.) Finally, it checks if the result does *not* contain an `f` (meaning no falses were returned). ``` p ! ~/(.)\1/&&gsub(/./){($`[-1]<=>$&)!=($&<=>$'[0])}!~/f/ ``` [Try it online!](https://tio.run/##KypNqvz/v0BBUaFOX0NPM8ZQX00tvbg0SUNfT1@zWkMlIVrXMNbG1k5FTVPRVkNFDcRUjzaI1axVrNNP0///39DYyITL0tDSkMvQCAghpBGXoaWFpQWQY8xlDBQ0MTQw5jIyMgaJg6Dlv/yCksz8vOL/unk5AA "Ruby – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), 147 144 bytes ``` M(){ a=${1:0:1} d=x i=1 while [ $i -lt ${#1} ] do b=${1:$i:1} case $d$((a-b)) in [ux]-*)d=d;;*0|u*|d-*)return 1;;*)d=u;;esac a=$b let i++ done } ``` [Try it online!](https://tio.run/##bVJNb6MwFLz7V7xlUZukQvIHX27kHnvrras9RDmQ2FksERKBUYPS/PbUmHYLpPjimTfz3viJTVbn1@vLbH5GmfDP5BE/kguS4oS0IOgt14WCFfgagsKAf/5NLrBG8oA2TuzrTr3NagW@9GezLNjM56BLtGpO62Axl0Iulwv83izepYWVMk1VArGcLTXLpaqzbTd3gwplQD882NalQpdrP7hSmbTdjo0B2ez3LajTUW2Nkl0CsJ/ewWoFnu80HghQ@6NpYb12VZOr0l2ctJMIB3cafblf/ptvHZWqm8KI16oxeetYVdRqWn7OirodtS0PRolRvK/YHvwSFvZOz8aEu7sfFH/K2iK900r@@BQ34G91KP@N5qptfvjexX3wdD@Y5fmdy@v3eyWMhhA8wefbOOFkAAm1Z4rpDTGS8JSnIwXrUL8c1kt7EBI8KFHK6DciXRDOB07OeNidNOJWGVGOCaaY4RBHOMYJTrE1UKeKeMwTGwMPYrhJw3WiJGVJGCcsDpM0jmjMwsheEpYOMk1dCE@J0w3RTpn@T5yQHw "Bash – Try It Online") I seem to like trying shell submissions, and learned some bash-isms in golfing this one. `$((a-b))` is equivalent to `$(( $a - $b ))` -- apparently you don't need the $ inside a $(( )) construct. There is a ++ operator, works in $(( )) and in `let` Subtracting letters is accepted, strangely. One of my samples in the TIO reads "xy", and apparently `$((a-b))` evaluates `a` to `x`, and then variable `x` to an empty string and the empty string as numeric zero, and comparable for b and y. If I set x and y in the environment, those values are used. Edit: -3 bytes by not putting whitespace after ;;, thanks to S.S.Anne [Answer] # [J](http://jsoftware.com/), 15 bytes ``` [:*/0>2*/\2-/\] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o6209A3sjLT0Y4x09WNi/2typSZn5CukKRgqGCsYKZgoKCjARCyBYiCMUGEExZgiRljFkFVaKliAMRdESF2dC1mHMVylMYo@EyDbAEnWCKzWCMVcGLYEmv0fAA "J – Try It Online") *-7 bytes thanks to RGS's technique* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~29~~ 27 bytes ``` UMθ⁻ι§θ⊕κUMθ×ι§θ⊕κ›⁰⌈…θ⁻Lθ² ``` [Try it online!](https://tio.run/##S85ILErOT8z5/983scA5Pzc3MS9Fo1BHwTczr7RYI1NHwbHEMy8ltQIk5pmXXJSam5pXkpqika0JBNZcqJpCMnNTidAUUJSZV6LhXpSaWJJapGEAtCyxIjO3NFfDuTI5J9U5I78A4QKf1Lz0kgyNQk0dBSNNsPb//6OjDXUULHUULCBkbOx/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of digits and outputs as a Charcoal boolean (`-` for a mountain range number, otherwise no output). Explanation: ``` UMθ⁻ι§θ⊕κ ``` Take consecutive differences (cyclic, so includes difference between last and first digit). ``` UMθ×ι§θ⊕κ ``` Take consecutive products (again, cyclic). ``` ›⁰⌈…θ⁻Lθ² ``` All results bar the last two must be negative. [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 22 bytes ``` XX2COqcm^m2COPD{0.<}al ``` [Try it online!](https://tio.run/##SyotykktLixN/Z@TV/0/IsLI2b8wOTcuF0gHuFQb6NnUJub8r82N/m9obGTCZWloachlaASEENKIy9DSwtICyDHmMgYKmhgaGHMZGRmDxEHQEgA "Burlesque – Try It Online") ``` XX # Explode into digits 2CO # 2-grams ("abc"->{"ab" "bc"}) qcm^m # Compare each via UFO operator 2CO # 2-grams PD # Product {0.<}al # All less than 0 ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 14 bytes ``` &/0>2_*':-':$: ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NSk3fwM4oXkvdSlfdSsXqf4lVtUp0ZV2RVZpChXVCfra1RkJaYmaOdYV1pXWRZmwtV0m0obGRiYKCgrVhLJBjaWhpCOcYGgEhCscIhWMI5VhaWFoglBkrgAwwAHGMQdphHBNDA2M4x8jI2AjOMQTZamkJ5PwHAA "K (ngn/k) – Try It Online") `$:` as string `-':` subtract (as ascii codes) each prior; implicit 0 before first `*':` multiply by each prior; implicit 1 before first `2_` drop first 2 elements `&/0>` all negative? [Answer] # [Python 3](https://docs.python.org/3/), ~~101~~ \$\cdots\$ ~~103~~ 94 bytes Added 13 bytes to fix error kindly pointed out by @ChasBrown. Saved 9 bytes thanks to @ChasBrown!!! ``` def f(l):x=[a<b for a,b in zip(l[1:],l)];return all(a!=b for a,b in zip(x[1:]+l[1:],x[:-1]+l)) ``` [Try it online!](https://tio.run/##fZCxDoIwFEV3v6LGgVYfiQUGQVn9AjfCUCIEkgZIhQT8@dpSUQxIkzs0OT3vvtZ9k1elK@U9zVCGOQm6MGKXBGWVQAwSVJToWdSYRzSIgZP4LNKmFSVinGO2DWdgp8GDwbsosKm6ECJrUZQNznBEwQUHvJgQZM4O3UTb5P3mg/hAQWUNocoxZIRWEHAMtIoY0xLiw0nnzyDLtvaUkl@n@62uH1wZf0yU7rT3IuGpRsepZUY4esq42CIxfOE7vtltNsVTlrlDvgA "Python 3 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 59 bytes ``` d;m(int*s){for(d=*s/s[1];s[1]&&s[1]/ *s-d;d^=1)s++;s=s[1];} ``` Takes as input a wide string of digits and returns zero if that number is a mountain range number. *-12 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!* [Try it online!](https://tio.run/##bVHfT4MwEH7nr7jUbGlhk7XsYdgx33zy0beJhrTgSDYwbdHMZX87thDnQK/J3fW77370KuZvQrSt5AdcVsbX5FTUCsvE16He0pQ7NZ06HYKv55LLl4QSHQRcJx3h3N6Uldg3Moe1NrKsb3cb7xf6FLtMOciz5eGQlRX@qEtJvJMHVrrwqwHfiG0KSYf1ESdhCEY1@eX@iGjElmh2BcQ0pgOAMnv@IuwfaESLV/HqCrHNi2yvB91ZNEiJRiWWdDEkMBaNGrt543iYtWQ/pDP3Ouv@wO3LQAILbs0adPmV1wU2goQXd7tIiY0GARkt7l3Z7AKjyV7DfAMT/VyhGdgEk87ggDuHwD2gB/vCI4I7QE@qMbsjIrwfpJ9D5aZRlR3BO7ff "C (gcc) – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), ~~95~~ 83 bytes ``` p->{int i=0,j=1;for(;p.length>-~++i;)j=(p[i-1]-p[i])*(p[i]-p[i+1])<0?j:0;return j;} ``` [Try it online!](https://tio.run/##rZO9coMwDMdn/BQacTEECEOpS/oEzZIxx@ASk5oSw4FJr8fRV6eCtHsTMkiyZPt/P/mjEGfhFoePMStF28KrULonAEob2eQik7Cd0rkAxka/T6GmHGsDQbcFDQmMtbvppxUq8VmRBDyvGpvXXin10bxv3G/HUZwWiV3vlRukLoaUPkzZPHaClD77L8WTzxtpukZDwYeRE1J3b6XKoDXCYDhX6gAnBLR3plH6iCSCEqsnlrX7ao08eVVnvBqnTKltLT/nbmzqac/M6YW@D9iahSwaKOWwWoFpOnmtRMwChrZEIkCG2e4iwsI7ySzlidnjZEtp1pMA7s9F2V4tsP5r41aBCE/CX8YQTk1cbuVWifmJ/Vq8rJ0Iaf7Bgv/aGsgw/gA "Java (JDK) – Try It Online") Thanks to all in the comments for improvements - especially bit-shifting which I never would have thought of!! [Answer] # [R](https://www.r-project.org/), 34 bytes ``` all((d=diff(scan()))[1]*d*.5:-1>0) ``` [Try it online!](https://tio.run/##K/r/PzEnR0MjxTYlMy1Nozg5MU9DU1Mz2jBWK0VLz9RK19DOQPO/IZcxlxGXCdd/AA "R – Try It Online") Alternately reverses signs of all differences, and then multiplies them all by first difference: mountain range sequences will all be positive Would be 40 bytes if defined as a function instead, so apologies to Robin with whom this would tie without the `scan` for input. [Answer] # [Scala](http://www.scala-lang.org/), 63 bytes ``` _.sliding(3).forall(t=>t(0)<t(1)&t(1)>t(2)|t(0)>t(1)&t(1)<t(2)) ``` Checks whether for all sliding triplets the center is strictly larger (or strictly smaller) than the previous element and the next element. [Try it online!](https://tio.run/##jZHRS8MwEMbf91ecZUgOwljbPbixDvRFfHDCRHwQkaxNt0pMZnMVpe5vr0nnxjaG@HAh/fHd1@8uNhVKNGb@KlOCW1NpEoWeCb2Q0@ptLksL8pOkzixcrlZQdzoAH0IBlRUtvyCBe/nOHIP2EvKYR3yAfEeGPOSu9kjoFG2dYjw6TY/UQ37hCx3CbaJcKHsiUMTjvdb4yGrgzPsHish3HMX4HcLV8KB34LTRLkQmcyBpieWVHnnF042mZ0gmcGWMkkLjCB50QS5j3ZpsdtjLTSlFumTWS1dloUlpZoNuXeTgvZhFhCA1ZemeKACprITgcXY3vQ7WYPT2Kbo2QGx92038bXv2D9/NQre2az9iO17z0rOqyAq9YDH63wilGCUTYn0cEwvx3B/uM8JvzyY7NvYMG7@vdfMD "Scala – Try It Online") ]
[Question] [ Most everyone here is familiar with Pascal's Triangle. It's formed by successive rows, where each element is the sum of its two upper-left and upper-right neighbors. Here are the first `5` rows (borrowed from [Generate Pascal's triangle](https://codegolf.stackexchange.com/q/3815/42963)): ``` 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 . . . ``` Collapse these rows to the left ``` 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 . . . ``` Sort them in ascending order ``` 1 1 1 1 1 2 1 1 3 3 1 1 4 4 6 . . . ``` Read this triangle by rows ``` [1, 1, 1, 1, 1, 2, 1, 1, 3, 3, 1, 1, 4, 4, 6 ...] ``` Given an input `n`, output the `n`th number in this series. This is [OEIS 107430](http://oeis.org/A107430). ### Rules * You can choose either 0- or 1-based indexing. Please state which in your submission. * The input and output can be assumed to fit in your language's native integer type. * 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. [Answer] # JavaScript (ES6), 79 bytes 0-indexed. ``` f=(n,a=[L=1])=>a[n]||f(n-L,[...a.map((v,i)=>k=(x=v)+~~a[i-1-i%2]),L++&1?k:2*x]) ``` ### Demo ``` f=(n,a=[L=1])=>a[n]||f(n-L,[...a.map((v,i)=>k=(x=v)+~~a[i-1-i%2]),L++&1?k:2*x]) console.log([...Array(79).keys()].map(n => f(n)).join(', ')) ``` ### How? ``` f = ( // f = recursive function taking: n, // n = target index a = [L = 1] // a[] = current row, L = length of current row ) => // a[n] || // if a[n] exists, stop recursion and return it f( // otherwise, do a recursive call to f() with: n - L, // n minus the length of the current row [ // an array consisting of: ...a.map((v, i) => // replace each entry v at position i in a[] with: k = // a new entry k defined as: (x = v) + // v + ~~a[i - 1 - i % 2] // either the last or penultimate entry ), // end of map() L++ & 1 ? // increment L; if L was odd: k // append the last updated entry : // else: 2 * x // append twice the last original entry ] // end of array update ) // end of recursive call ``` This algorithm directly generates the sorted rows of Pascal's Triangle. It updates **n** according to the length of the previous row until **a[n]** exists. For instance, 6 iterations are required for **n = 19**: ``` L | n | a[] ---+----+------------------------ 1 | 19 | [ 1 ] 2 | 18 | [ 1, 1 ] 3 | 16 | [ 1, 1, 2 ] 4 | 13 | [ 1, 1, 3, 3 ] 5 | 9 | [ 1, 1, 4, 4, 6 ] 6 | 4 | [ 1, 1, 5, 5, 10, 10 ] ^^ ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 46 bytes ``` @(n)(M=sort(spdiags(flip(pascal(n)))))(~~M)(n) ``` 1-based. [**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999BI09Tw9e2OL@oRKO4ICUzMb1YIy0ns0CjILE4OTEHKAsCGnV1vppA9v/EoqLEyrTSPI00HQVDK0NTzf8A "Octave – Try It Online") ### Explanation Consider `n=4` as an example. `pascal(n)` gives a Pascal matrix: ``` 1 1 1 1 1 2 3 4 1 3 6 10 1 4 10 20 ``` The rows of the Pascal triangle are the antidiagonals of this matrix. So it is flipped vertically using `flip(···)` ``` 1 4 10 20 1 3 6 10 1 2 3 4 1 1 1 1 ``` which transforms antidiagonals into diagonals. `spdiags(···)` extracts the (nonzero) diagonals, starting from lower left, and arranges them as zero-padded columns: ``` 1 1 1 1 0 0 0 0 1 2 3 4 0 0 0 0 1 3 6 10 0 0 0 0 1 4 10 20 ``` `M=sort(···)` sorts each column of this matrix, and assigns the result to variable `M`: ``` 0 0 0 1 0 0 0 0 0 1 1 4 0 0 0 1 1 3 4 10 0 1 1 2 3 6 10 20 ``` Logical indexing `(···)(~~M)` is now used to extract the nonzeros of this matrix in column-major order (down, then across). The result is a column vector: ``` 1 1 1 1 ··· 10 10 20 ``` Finally, the `n`-th entry of this vector is extracted using `(···)(n)`, which in this case gives `1`. [Answer] # [Python 2](https://docs.python.org/2/), ~~86~~ ~~78~~ 72 bytes -8 bytes thanks to [Rod](https://codegolf.stackexchange.com/users/47120/rod) ``` g=lambda n,r=[1]:r[n:]and r[n/2]or g(n-len(r),map(sum,zip([0]+r,r+[0]))) ``` [Try it online!](https://tio.run/##DcsxCsMwDEDRq2iUiEqdQJdATmI8qCR1BbFi1HRoL@94@m/59Xe@D5tay8su5bkKGPsSxzR7tDmJrdBxn9LhkNFu@2boxEUqfr6F/1oxhjQ4@9BLRK262hkzKr36o6AGLpY3DAyPQKld "Python 2 – Try It Online") ## Ungolfed ``` def g(n, row=[1]): if n < len(row): return row[n/2] else: next_row = map(sum, zip([0] + row, row + [0])) return g(n - len(row), next_row) ``` [Try it online!](https://tio.run/##TY3NCsIwEITvPsUcE4wYC17EPkkIUnBbA@02pCn@vHzcVijelm9m54vv/Bi5KuVOLTrFBml81u7k9WUHhBaMK3piJXhFQKI8J156jo@VF0b9RL@M6ZVvkqDG0EQ1zYPBJ0TlrMd@eVn35RSg9f@cuHHYTGZb0iWmwBmuU0GjHRMCgtgb7khZg7PVvnwB "Python 2 – Try It Online") The function recursively calculates the row of Pascal's Triangle. Given the current row as `row`, `map(sum, zip([0] + row, row + [0]))`. At each call `n` is reduced by the length of the current row. If the function arrives at the right row the `nth` lowest number of the row should be returned. As the first half of a row is in ascending order and each row is symmetrical, the number is at index `n/2` (0-indexed, integer division). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 55 bytes The indexing is 1-based. ``` (##&@@@Sort/@Table[n~Binomial~k,{n,0,#},{k,0,n}])[[#]]& ``` [Try it online!](https://tio.run/##DcVNCoMwEAbQwwRE4QMdtT8uCkNPILS7kMW0KA2aCJJdiFePfZvnJPwmJ8F@Jc@PXCpVMPNr20PNb/msk/bH0/rNWVmPBdGjgUqIy3@fTKW1MqbI42594HKuORJadOhxwRU33DGAGhCBWlAH6lOVTw "Wolfram Language (Mathematica) – Try It Online") ## Explanation This is likely golfable, I am not a very experienced Mathematica user. ``` Table[n~Binomial~k,{n,0,#},{k,0,n}] ``` For each **n ∈ [0, Input] ∩ ℤ**, generate the table of binomials with each **k ∈ [0, n] ∩ ℤ**. ``` Sort/@ ``` Sort each. Uses a shorthand to `Map[function,object]` – `function/@object`. ``` (##&@@@...)[[#]] ``` Flatten the resulting list and retrieve the element whose index in the list is the input. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~26~~ 25 bytes *1 byte saved thanks to @ngn* ``` {⍵⊃0~⍨∊(⍋⊃¨⊂)¨↓⍉∘.!⍨⍳1+⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OAZPWj3q2PupoN6h71rnjU0aXxqLcbyD204lFXkyaQbJv8qLfzUccMPUWQfO9mQ22g@tr//9MOgXhGBgA "APL (Dyalog Unicode) – Try It Online") [Answer] # [R](https://www.r-project.org/), 58 bytes ``` function(n)(m=apply(outer(0:n,0:n,choose),1,sort))[m>0][n] ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPUyPXNrGgIKdSI7@0JLVIw8AqTweEkzPy84tTNXUMdYrzi0o0NaNz7Qxio/Ni/xdDVBtaGRnopGn@BwA "R – Try It Online") Computes `n choose k` for each `n,k` in `[0,1,...,n]` as a matrix, sorts the rows ascending(\*), and removes the zeros, then selects the `n`th element. (\*) This also transforms them into *columns* but that's better since R stores a matrix as a vector columnwise, which allows us to index directly into it while preserving order. [Answer] # [Haskell](https://www.haskell.org/), ~~143~~ ~~132~~ ~~125~~ 123 bytes ``` ((p>>=s.h)!!) p=[1]:map(\r->zipWith(+)(0:r)(r++[0]))p h r=splitAt(div(length r)2)r s(a,b)=reverse b!a (h:t)!b=h:(b!t) x!_=x ``` The first line is a point-free function that takes an index (0-based) and returns the appropriate number in the sequence. [Try it online!](https://tio.run/##Dc0xDoMgFADQnVPA9n@sxjqSYNJTdFDTgEUhRfMDxJgevtT1Lc/p9LEhlEWNBYD6XqXGoRDISA33SW6aYIx1//X09NlBhdDKiBCramgnRGKOR5Uo@PzI8PYHBLuv@ULsMLIE@mZQRXvYmCw3QjNwMqMwykkwIiM7xUudZdN@54pT9HvmcK184UPbNN2VlN@8BL2mUs9Efw "Haskell – Try It Online") This is my first ever Haskell program! I'm sure it can get much shorter. Tips are appreciated. *Saved 2 bytes thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi)* ### Ungolfed ``` pascalRows = [1] : map (\row -> zipWith (+) (0:row) (row++[0])) pascalRows halves row = splitAt (div (length row) 2) row joinSorted (first, second) = interleave (reverse second) first interleave [] _ = [] interleave longer shorter = (head longer) : (interleave shorter (tail longer)) f n = (concatMap (joinSorted.halves) pascalRows) !! n ``` [Answer] # JavaScript, 57 bytes ``` f=(i,r=1)=>i<r?i>1?f(i-2,--r)+f(i<r?i:r-1,r):1:f(i-r,r+1) ``` 0-indexed. How does this come: Step 0: ``` c=(i,r)=>i?r&&c(i-1,r-1)+c(i,r-1):1 f=(i,r=1)=>i<r?c(i>>1,r-1):f(i-r,r+1) ``` This code is easy to understand: * function `c` calculate the Combination use formula: C(n,k) = C(n-1,k) + C(n-1,k-1); or 1 if k == 0 or k == n * function `f` try to find out the row number and index in the row, and then call function c for getting the result. Step 1: ``` c=(i,r)=>i>1?--r&&c(i-2,r)+c(i,r):1 f=(i,r=1)=>i<r?c(i,r):f(i-r,r+1) ``` In this step, we try to modify the call of function `c` to `c(i,r)` which makes it as same as parameter of `f`. Step 2: ``` c=(i,r)=>i>1?--r&&c(i-2,r)+c(i<r?i:r-1,r):1 f=(i,r=1)=>i<r?c(i,r):f(i-r,r+1) ``` We test `i<r` for whether using function `f` or function `c`. That's why we musk keep `i<r` holds during recursion of function `c`. Step 3: ``` f=(i,r=1)=>i<r?i>1?--r&&f(i-2,r)+f(i<r?i:r-1,r):1:f(i-r,r+1) ``` At this step, we merge these two function into one. After some more golf, we finally got the answer described above. ``` f=(i,r=1)=>i<r?i>1?f(i-2,--r)+f(i<r?i:r-1,r):1:f(i-r,r+1) for(i=0,x=1;x<10;x++) { document.write('<p>') for(j=0;j<x;j++,i++) document.write(`<b>${f(i)}</b>`) } ``` ``` p { text-align: center; } b { display: inline-block; width: 4ch; font-weight: normal; } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` 0rcþ`ZṢ€Ẏḟ0⁸ị ``` [Try it online!](https://tio.run/##ASYA2f9qZWxsef//MHJjw75gWuG5ouKCrOG6juG4nzDigbjhu4v///8xNQ "Jelly – Try It Online") Using Uriel's Dyalog algorithm. 1-indexed. Explanation: ``` 0rcþ`ZṢ€Ẏḟ0⁸ị 0r Return inclusive range from 0 to n ` Call this dyad with this argument on both sides þ Outer product with this dyad c Binomial coefficient Z Zip € Call this link on each element Ṣ Sort Ẏ Concatenate elements ḟ0 Remove 0s ⁸ị Take the nth element ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 17 bytes ``` ⎕⊃∊i!⍨,\⌊.5×i←⍳99 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra00DcR13Njzq6MhUf9a7QiXnU06Vnenh6JlDFo97Nlpb/gar@p3EZcKVxGQKxERAbA7EJEJsCsRkQmwOxBRBbgtSAFYJUGoKUGoLUGoIUG5oCAA "APL (Dyalog Classic) – Try It Online") 0-based indexing note that `(49!98) > 2*53`, i.e. the binomial coefficient 98 over 49 is greater than 253, so at that point Dyalog has already started losing precision because of IEEE floating point [Answer] # [JavaScript (Node.js)](https://nodejs.org), 65 bytes Not even an array is used. 0-indexed. ``` f=(n,i=0,g=x=>x?x*g(x-1):1)=>n>i?f(n-++i,i):g(i)/g(c=n>>1)/g(i-c) ``` [Try it online!](https://tio.run/##Fc1LDoIwFEbh7bTyF7k85GFaFmIckArNNdgSMaa7rzg7@SbnOX2n3b55@ygfHnNKixYerAs4HbWJYzw5ERXJgaQ23vC4CK@yjMFycILl2QmrvTH0L1ZWpqsNfg/rnK/BiVsBQokKNRpc0KJDDzqQQCWoAtWgBnQBtaAO1KMs7vlr2gRrsxwDKdMP "JavaScript (Node.js) – Try It Online") Explanation: ``` f=(n,i=0, )=> // Main Function g=x=>x?x*g(x-1):1 // Helper (Factorial) n>i? // Is n > i? f(n-++i,i): // If so, call function // f(n-i-1, i+1) to skip // . i+1 terms g(i)/g(c=n>>1)/g(i-c) // If not, since sorting // . the binomial coeffs // . equals to writing // . the first floor(i/2) // . coefficients twice // . each, so a shortcut ``` [Answer] # [Pascal](https://www.freepascal.org/), 373 bytes ``` function t(n,k,r:integer):integer;begin if(n<k)then t:=r-1 else t:=t(n,k+r,r+1)end; function s(n,k:integer):integer;begin if(k=0)then s:=n else s:=s(n+k,k-1)end; function f(n,k:integer):integer;begin if((k<1)or(k>n))then f:=0 else if n=1 then f:=1 else f:=f(n-1,k-1)+f(n-1,k)end; function g(n:integer):integer;var k:integer;begin k:=t(n,0,1);g:=f(k,(n-s(0,k-1)+2)div 2)end; ``` `g` is the function. [Try it online!](https://tio.run/##hdDBbsMgDAbge5/CR1DIFNobNHuXNAGG6EzksO7xUwjNDpm0XdAvgz9bzMMyDvfWzuM6U3Q0fMK8lfRqv3BMPiIkhiIIUh6TcYb4HvTNOI/gLcNr4OnD5Keqp1aCuS@m5K2zIUGN5AYnffoxl3Lzhxj6roqL6rF6OeWuJojQHjX7j8bCVfJILLwjr6xVfVdZbwF7CXv1tXxOGW3lNqx5xcNUx/D3zMdAEA4bhPoTnZBcuwIHkcGFdVU/88k/4Lzpa@n3CnbgVAUbSzWvnCJcOpgi1Po3@WSYY56rC9ew7ZePt/UJ "Pascal (FPC) – Try It Online") [Answer] # Java 8, 187 bytes ``` n->{int r=~-(int)Math.sqrt(8*n+1)/2+1,a[]=new int[r],k=r,x=0;for(;k-->0;a[k]=p(r,k))x+=k;java.util.Arrays.sort(a);return a[n-x];}int p(int r,int k){return--r<1|k<2|k>r?1:p(r,k-1)+p(r,k);} ``` **Explanation:** [Try it online.](https://tio.run/##LZBNbsIwEIX3nGLEKm7iQJAqVTWh6gFgwzLKwg0GjBM7nUwoCNKrpzZU8o9mxnp@7zvJs@SuVfa0M2NVy66DtdT2NgHQlhTuZaVgE0qA2tkDVJHvg2XCtwa//dqAhRxGy1e3MMP8l4dHbC3pmHbfSNHbi40zNlvEWSKLMrfqJ6gXWCYmx@SSz8XeYSQM56u5kIUp8zbCxDB2iXMjTt5j2pOu009Eee3SznlNyQQq6tGCLCy/lGKYiOByNoONI2glErg90FHB15UUr1xvaRIMto8ImITTsNtThXNcZnezXNzNCj@y94cBnrH46UQMI0Dbf9W6go4k@evs9A4aDyvaEmp7KEqQ7EkqIITGQwlJQxE9eAGEmOFb7SPr5as/4pg9JgDba0eqSV1Paev1KGpSm3rcLJ4m03/ew/gH) ``` n->{ // Method with integer as both parameter and return-type int r=~-(int)Math.sqrt(8*n+1)/2+1, // Calculate the 1-indexed row based on the input a[]=new int[r], // Create an array with items equal to the current row k=r, // Index integer x=0; // Correction integer for(;k-->0; // Loop down to 0 a[k]=p(r,k)) // Fill the array with the Pascal's Triangle numbers of the row x+=k; // Create the correction integer java.util.Arrays.sort(a); // Sort the array return a[n-x];} // Return the `n-x`'th (0-indexed) item in this sorted array // Separated recursive method to get the k'th value of the r'th row in the Pascal Triangle int p(int r,int k){return--r<1|k<2|k>r?1:p(r,k-1)+p(r,k);} ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` :qt!XnSXzG) ``` 1-based. [Try it online!](https://tio.run/##y00syfn/36qwRDEiLziiyl3z/39LAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmv5PDfqrBEMSIvOKLKQfP/f0MrQ1MA). ### Explanation Consider input `4` as an example. `;` is the row separator for matrices or column vectors. ``` : % Implicit input: n. Push the row vector [1 2 ... n] S STACK: [1 2 3 4] q % Subtract 1, emlement-wise: gives [0 1 ... n-1] % STACK: [0 1 2 3] t! % Duplicate and transpose into a column vector % STACK: [0 1 2 3], [0; 1; 2; 3] Xn % Binomial coefficient, element-wise with broadcast. Gives an % n×n matrix where entry (i,j) is binomial(i,j), or 0 for i<j % STACK: [1 1 1 1; 0 1 2 3; 0 0 1 3; 0 0 0 1] S % Sort each column % STACK: [0 0 0 1; % 0 0 1 1; % 0 1 1 3; % 1 1 2 3] Xz % Keep only nonzeros. Gives a column vector % STACK: [1; 1; 1; 1; 1; 2; 1; 1; 3; 3] G) % Get the n-th element. Implicitly display % STACK: 1 ``` [Answer] ## Batch, 128 bytes ``` @set/as=2,t=r=m=i=1 :l @if %1 geq %t% set/as+=r,t+=r+=1&goto l @for /l %%i in (%s%,2,%1)do @set/ar-=1,m=m*r/i,i+=1 @echo %m% ``` 0-indexed. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes 0-indexed ``` ÝεDÝc{}˜sè ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8NxzW10Oz02urj09p/jwiv//DU0A "05AB1E – Try It Online") **Explanation** ``` Ý # push range [0 ... input] ε } # apply to each element DÝc # N choose [0 ... N] { # sort ˜ # flatten result to a list sè # get the element at index <input> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḷc€`Ṣ€Fḟ0ị@ ``` **[Try it online!](https://tio.run/##y0rNyan8///hjm3Jj5rWJDzcuQhIuT3cMd/g4e5uh////1sCAA "Jelly – Try It Online")** A monadic link taking the index and returning an integer - uses 1-based indexing. ### How? Performs the challenge pretty much just as it is written, just with more of the right of Pascal's triangle (zeros) which is then thrown away... ``` Ḷc€`Ṣ€Fḟ0ị@ - Link: integer, i e.g. 1 or 9 Ḷ - lowered range [0] [0,1,2,3,4,5,6,7,8] ` - repeat left as right arg [0] [0,1,2,3,4,5,6,7,8] c€ - binomial choice for €ach [[1]] [[1,0,0,0,0,0,0,0,0],[1,1,0,0,0,0,0,0,0],[1,2,1,0,0,0,0,0,0],[1,3,3,1,0,0,0,0,0],[1,4,6,4,1,0,0,0,0],[1,5,10,10,5,1,0,0,0],[1,6,15,20,15,6,1,0,0],[1,7,21,35,35,21,7,1,0],[1,8,28,56,70,56,28,8,1]] Ṣ€ - sort €ach [[1]] [[0,0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,1,1],[0,0,0,0,0,0,1,1,2],[0,0,0,0,0,1,1,3,3],[0,0,0,0,1,1,4,4,6],[0,0,0,1,1,5,5,10,10],[0,0,1,1,6,6,15,15,20],[0,1,1,7,7,21,21,35,35],[1,1,8,8,28,28,56,56,70]] F - flatten [1] [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,2,0,0,0,0,0,1,1,3,3,0,0,0,0,1,1,4,4,6,0,0,0,1,1,5,5,10,10,0,0,1,1,6,6,15,15,20,0,1,1,7,7,21,21,35,35,1,1,8,8,28,28,56,56,70] ḟ0 - filter discard zeros [1] [1,1,1,1,1,2,1,1,3,3,1,1,4,4,6,1,1,5,5,111,1,6,6,15,15,21,1,7,7,21,21,35,35,1,1,8,8,28,28,56,56,70] ị@ - index into (sw@p args) 1 3 --------------^ ``` [Answer] # [Red](http://www.red-lang.org), 206 bytes ``` f: func[n][t: copy[[1]]l: 0 while[l < n][a: copy last t insert append a 0 0 b: copy[]repeat i k:(length? a)- 1[append b a/(i) + a/(i + 1)]append t reduce[b]l: l + k]foreach p t[sort p]pick split form t{ }n] ``` 1-based [Try it online!](https://tio.run/##PY7BasMwEETv@Yohp5hSaht6EYX@Q67LHmR5XQurspAVSgj5dmfbiLKHGfYNO5tl3M8ygnifDKZLdBSZioFb05WoYw4G7eFn9kEo4ANK7ZMi2K2gwMdNcoFNSeIIi1ZnqAc4SxKrGSzmFCR@lfkTtnlFRzU/wL6dfIOXP1XpGq6oIMt4cULD7xNB2cLTmsW6GQmFtlVrEyfvFmwp@AKl3yg33CPv/819C0LKPhZVj6M5YlJl8OG5vd2rof69r1wd7w8 "Red – Try It Online") ## Explanation: ``` f: func [n] [ t: copy [[1]] ; start with a list with one sublist [1] l: 0 ; there are 1 items overall while [l < n] [ ; while the number of items is less than the argument a: copy last t ; take the last sublist insert append a 0 0 ; prepend and append 0 to it b: copy [] ; prepare a list for the sums repeat i k: (length? a) - 1 [ ; loop throught the elements of the list append b a/(i) + a/(i + 1)] ; and find the sum of the adjacent items append t reduce [b] ; append the resulting list to the total list l: l + k ; update the number of the items ] foreach p t [sort p] ; sort each sublist v: pick split form t { } n ; flatten the list and take the n-th element ] ``` [Answer] # Perl, 48 bytes Includes `+1` for `p` ``` perl -pe '$_-=$%until$_<++$%;$./=$_/--$%for 1..$_/2;$_=$.' <<< 19 ``` Uses base 0 indexing. [Answer] # [Julia](https://julialang.org), 70 bytes ``` f(x)=map(n->binomial(n-1,ceil(Int,x/2-(n^2-n)/4-1)),round(Int,√(x*2))) ``` 1-based Explanation: it first find the row number, then the column number, then compute the binomial [Answer] # [J](http://jsoftware.com/), ~~43~~ 38 bytes ``` ](([-2!]){/:~@(i.!<:)@])[:<.2&!@,:^:_1 ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqCjYKBgBcS6egrOQT5u/2M1NKJ1jRRjNav1reocNDL1FG2sNB1iNaOtbPSM1BQddKzirOIN/2typSZn5CukKRkoZOopGBv8BwA "J – Try It Online") 0-indexed Notes: * `<.2&!@,:^:_1` gives the relevant row number of Pascal's triangle by rounding down the inverse of `y choose 2`. * `/:~@(i.!<:)@]` calculates the row and sorts it. * `[-2!]` gives the index into the row. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` ʀƛʀƈs;f$i ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%CA%80%C6%9B%CA%80%C6%88s%3Bf%24i&inputs=5&header=&footer=) No efficiency at all. 0-indexed. ``` ʀ # 0...n ƛ ; # Mapped to... ʀ # 0...n ƈ # Binomial coefficient with n, vectorised s # Sort these f # Flatten $i # Index input into this. ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 8 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` ĖDȷc€ṠḞi ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNCU5NkQlQzglQjdjJUUyJTgyJUFDJUUxJUI5JUEwJUUxJUI4JTlFaSZmb290ZXI9JmlucHV0PTE0JmZsYWdzPQ==) or [see the interpreter complaining](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNCU5NkQlQzglQjdjJmZvb3Rlcj0maW5wdXQ9NSZmbGFncz13) (explained below) #### Explanation ``` ĖDȷc€ṠḞi # Implicit input Ė # Push [0..input] Dȷc # Outer product over ncr with itself # NOTE: the interpreter actually tries to calculate all the # values: [0C0, 0C1, 0C2, ..., (input)C(input)], but # fails for the ones where r > n. It silently carries # on, ignoring those values, so we end up with input+1 # rows of Pascal's triangle :D. However, if you add # the w (warnings) flag, you'll see all the errors # which were caught by the interpreter (link above) €Ṡ # Sort each row of the triangle Ḟ # Flatten the list of lists i # Index in using the input # Implicit output ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `M`, 7 bytes ``` ƛʀƈs;fi ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJNIiwiIiwixpvKgMaIcztmaSIsIiIsIjE0Il0=) #### Explanation ``` ƛʀƈs;fi # Implicit input ƛ ; # Map over [0..input] ʀƈ # nCr with each of [0..that] s # Sort the resulting list f # Flatten the list of lists i # Index in using the input # Implicit output ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` 1+2\1,1j$$СṢ€Ẏ⁸ị ``` [Try it online!](https://tio.run/##y0rNyan8/99Q2yjGUMcwS0Xl8IRDCx/uXPSoac3DXX2PGnc83N39HyhvCgA "Jelly – Try It Online") [Answer] # Pyth, 15 bytes ``` @u+GSm.cHdhHhQY ``` 0-indexed [Try it](http://pyth.herokuapp.com/?code=%40u%2BGSm.cHdhHhQY&input=5&debug=0) ### Explanation ``` @u+GSm.cHdhHhQY u hQY Reduce on [0, ..., input], starting with the empty list... +G ... append to the accumulator... Sm.cHdhH ... the sorted binomial coefficients. @ Q Take the 0-indexed element. ``` [Answer] # [Clean](https://clean.cs.ru.nl), 80 bytes ``` import StdEnv ``` # ``` \n=flatten[sort[prod[j+1..i]/prod[1..i-j]\\j<-[0..i]]\\i<-[0..]]!!n ``` [Try it online!](https://tio.run/##JY2xDsIgGIT3PgWNo6HSXTYdTNw6AgMBaiDwQwBNfHkRdPvucvlOeSOhhaif3qAgLTQbUswVbVVf4dW2KnOdDmhHFHGgu5e1GmClT1jKUTN3XJfFitMvDMROcO7OmJHRd7Z/FmKeYaL9JHXbaFZCRPuo7nyUhm/3dnmDDFaVLw "Clean – Try It Online") As a lambda function. [Answer] # [Ruby](https://www.ruby-lang.org/), 56 bytes ``` ->n{a=0;n-=a until n<a+=1;[*2..a].combination(n/2).size} ``` 0-based First get the row and column in the triangle, then calculate the binomial coefficient corresponding to that position. [Try it online!](https://tio.run/##BcHRDkAgFADQX@lRzBWbp@RHrIfL2Nq4NWpD@vacc4b5yZvK9UgRlZBUK2SBvNkZDVipVk5lB4AaFnvMhtAbSwU1HYfLvGvKjhUCoBccDnTxu79tunXKPw "Ruby – Try It Online") [Answer] # [Actually](https://github.com/Mego/Seriously), 8 bytes Largely based on [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/155168/47581). Uses 0-indexing. ``` ;r♂╣♂SΣE ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/9@66NHMpkdTFwPJ4HOLXf//NzQBAA "Actually – Try It Online") **Ungolfing** ``` Implicit input n. ; Duplicate n. r Lowered range. [0..n-1]. ♂╣ Pascal's triangle row of every number. ♂S Sort every row. Σ Sum each row into one array. E Get the n-th element of the array (0-indexed). Implicit return. ``` [Answer] # [Coconut](http://coconut-lang.org/), 69 bytes ``` def g(n,r=[1])=r[n:]and r[n//2]or g(n-len(r),[*map((+),[0]+r,r+[0])]) ``` [Try it online!](https://tio.run/##FYtBCoAwDAS/kmNiK1bBi@BLSg5FayloKkHfX@tpBmZ3K1uR96l1jwckFKurH5lW9bJwkB2aDMPERf/an1FQyfruCjeiaebYqFXTSEz11iwP@oSZjnbJkAU0SIroLMzun3w "Coconut – Try It Online") ]
[Question] [ Help! I just logged into Stack Exchange, but I forgot what my password is! I need a way to work it out before I log off. Luckily, I'm an excellent hacker. Not only was I able to find my password's hash, but I also found Stack Exchange's hashing algorithm! It takes the ASCII value of each digit multiplied by that digit's place, then sums all those values together. For example: ``` "135" -> 1*49 + 2*51 + 3*53 = 310 ``` I remember that my password is 3 digits long, and that each character is a number between 0 and 5 inclusive (such that it will match the regex: `^[0-5]{3}$`), but that's still too many possibilities to guess. I need a program that can convert a hash back into potential passwords, but despite being an expert hacker, I can't code to save my life! I was able to write these tests out by hand though: ``` input -> output 288 -> 000 // lowest possible hash 290 -> 200, 010 298 -> 022, 050, 103, 131, 212, 240, 321, 402, 430, 511 318 -> 555 // highest possible hash ``` Can one of you write a program for me that will take in a hash and print all the possible passwords I could have used? The input will always be able to produce at least one valid password. Any output format is allowed, as long as the strings can be clearly identified. I'm also not concerned about leading zeroes, so if a potential password is `001`, I'll also accept `01` or `1`. Please help me from being locked out of Stack Exchange! ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` 5Ý3ãʒÇƶOQ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f9PBc48OLT0063H5sm3/g//9GlhYA "05AB1E – Try It Online") Returns list of lists of digits. [Answer] # [C](https://gcc.gnu.org), ~~113~~ 108 bytes ``` f(int h){int i=47,j,k;while(++i<54)for(j=47;++j<54)for(k=47;++k<54;)if(h==i+j+j+k*3)printf("%c%c%c",i,j,k);} ``` It is unique to see what is meant for output, the output is of the format: 200010 All passwords are written as 3-digits without delimiter. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ṿ€Oæ.J 6Ḷṗ3Ç⁼¥Ðf ``` A monadic link returning a list of lists of digits. **[Try it online!](https://tio.run/##ASsA1P9qZWxsef//4bm@4oKsT8OmLkoKNuG4tuG5lzPDh@KBvMKlw5Bm////Mjkw "Jelly – Try It Online")** ### How? ``` Ṿ€Oæ.J - Link 1, hash: list of integers (the digits of a password) Ṿ€ - unevaluate €ach (giving a list of characters) O - cast to ordinals (Ṿ€O could actually be replaced with +48 too) J - range of length (i.e. [1,2,3] in all use-cases) æ. - dot product 6Ḷṗ3Ç⁼¥Ðf - Main link: number, n 6Ḷ - lowered range of 6 = [0,1,2,3,4,5] ṗ3 - Cartesian power with 3 = [[0,0,0],[0,0,1],...,[5,5,5]] (all passwords) Ðf - filter keep if: ¥ - last two links as a dyad (right implicitly n): Ç - call last link (1) as a monad ⁼ - equals right? ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~126~~ 75 bytes -2 thanks to @ArnoldPalmer ``` lambda h:[(P/36,P%36/6,P%6)for P in range(216)if P/36+P%36/6*2+P%6*3==h&31] ``` [Try it online!](https://tio.run/##LY3BDoIwDIbP8BS9KAxJEJYsSsIRr3LwJh4mbkKCYykjwtPjpp7ar/3aXy@mHVS2yqJee/66Pzi0@TWsEsriakNZ4gojckCooFOAXD1FmKWMdBKctftZUWYbFtGiaLc0va0Gl9z33m3XC7jgJCx4MxT2hZ5MSCxp7JSBoFZBDLNlF8Hje9y4GBnOxJ38re/cF3MjtIHyfCoRB7R7zcdxpenez46HDw "Python 2 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 20 bytes ``` '0':'5'3Z^t3:*!si=Y) ``` [Try it online!](https://tio.run/##y00syfn/X91A3UrdVN04Kq7E2EpLsTjTNlLz/38jSwsA "MATL – Try It Online") ### Explanation ``` '0':'5' % Push inclusive range from '0' to '5', that is, '012345' 3Z^ % Cartesian power with exponent 3. Each Cartesian tuple is a row t % Duplicate 3: % Push [1 2 3] * % Multiply element-wise with broadcast !s % Sum of each row i % Input number = % Logical mask of values that equal the input Y) % Use as logical index into the rows of the matrix. Implicit display ``` [Answer] # [Python 2](https://docs.python.org/2/), 81 bytes ``` lambda h:[(a,b,c)for a in r for b in r for c in r if a+2*b+3*c+288==h] r=range(6) ``` [Try it online!](https://tio.run/##RY2xDoIwFEVn@Iq30QKDQmIISUdcXdzEodRim2BpHiXC12OLJm73vPtujl2dGk2x9azdBv7qHhxUfSM873JB@xGBgzaAEGL3j@IbdQ88K9IuK1ORFVXFmLrHyJCbpyQnujlc6zh6Kz1IuOIsPUQLMD@2syPUk0VtHCStSXJYPO/KIA@Cniw0TH5f@z2Wi5DWQXM5N4gj@t7yadrK4@ED "Python 2 – Try It Online") [Answer] ## Haskell, ~~71~~ ~~70~~ ~~64~~ 61 bytes ``` l=[0..5] f p=[show=<<[a,b,c]|a<-l,b<-l,c<-l,p-288==a+2*b+3*c] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P8c22kBPzzSWK02hwDa6OCO/3NbGJjpRJ0knObYm0UY3RycJRCSDiAJdIwsLW9tEbSOtJG1jreTY/7mJmXkKtgop@VwKCgoFRZl5JQoqCmkKQGVoApYG6AJoKowNLf4DAA "Haskell – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform),133 131 125 123 bytes ``` n=>{int i,j,k;for(i=48;i<54;++i)for(j=48;j<54;++j)for(k=48;k<54;++k)if(i+j*2+k*3==n)Console.Write($"{i%48}{j%48}{k%48},");} ``` [Try it online!](https://tio.run/##fcuxCsIwGATgPU8RRCGxVdRWqKQRxFUnB@cSY/mTmmATBQl99mrq5OJyHN9xws2EbWX/cGBqfHo5L28MiaZyDt8Dcr7yIPDTwgUfKzCEBrQTHqwpwfhtzXvDt@FTMaQq1exqWwI8LxiU65wlCdAoKor6ihpER9Ff0RSuBBI1XSV6mnFu6N4aZxs5P7fgJRmPAkzyogtqSB0zHVHW9QzVZFUUlKGfxwGMJHQYN4t/459ntoxj1/Vv "C# (.NET Core) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` F⁶F⁶F⁶¿⁼⁺℅Iι⁺×℅Iκ²×℅Iλ³Iθ«IιIκIλ⸿ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9nmWPGrchk4f2P2rc86hx16OW1vd7Vp7bCWQeng7l7Dq0Cc7efWgziNpxaDVYGVgaLP5ox/7//40sLQA "Charcoal – Try It Online") A similar approach to other answers: loop thrice from 0 to 5, calculate the hash and print the state of the iteration variables if it coincides with the input hash. Link to the [verbose version](https://tio.run/##S85ILErOT8z5/z8tv0hBw0yTS0EBwUJlKyhkpilouBaWJuYUazimpGjkF6VoOCcWl2hkamrqKIBEQjJzU4sR4tlAcSOgFJpwDlDYWBOkB8wtBDIVqqFWKCgEFGXmlcDNtcYmno1DPAdTXCmmSAkuWPv/v5GlxX/dsv@6xTkA). [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~26~~ 25 bytes *-1 byte thanks to Challenger5* ``` {:H;6Zm*{s:i3,:).*:+H=},} ``` Anonymous block expecting the hash on the stack (as an integer) and leaves the result on the stack (as a list of strings). [Try it online!](https://tio.run/##S85KzP1flPm/2srD2iwqV6u62CrTWMdKU0/LStvDtlan9n9dwX8jSwMA "CJam – Try It Online") ### Explanation ``` :H; e# Store the hash in H. 6Zm* e# 3rd Cartesian power of [0 1 2 3 4 5]. { e# For each tuple in the power: s e# Stringify the tuple. :i e# Get the code point of each digit. 3,:) e# Push [1 2 3]. .* e# Element-wise multiplication of the two lists. :+ e# Sum the result. H= e# Check if it's equal to the hash. }, e# Filter the tuples to only ones for which this block gave a truthy result. ``` [Answer] # Java, 162 Bytes ``` static void f(int n){for(int i=48;i<54;i++){for(int j=48;j<54;j++){for(int k=48;k<54;k++){if(i+j*2+k*3==n)System.out.println((char)i+""+(char)j+""+(char)k);}}}} ``` [Answer] ## JavaScript (Firefox 30-57), 72 bytes ``` n=>[for(i of s="012345")for(j of s)for(k of s)if(n-i-j*2-k*3==288)i+j+k] ``` [Answer] # Pyth, 18 bytes ``` fqQs*VS3CMT^jkU6 3 ``` [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 40 bytes ``` [0,5|[0,5|[0,5|~a+b+b+c+c+c+288=:\?a,b,c ``` ## Explanation ``` [0,5| Make a FOR loop run through the possible digits for pos 1, called a [0,5| Loop for #2, b [0,5| Loop for #3, c Calculate the hash by taking a once, b twice and c thrice, and raising all to their ASCII codepoints a+b+b+c+c+c+288 ~ =: IF thta is euqal to the given hash (read from cmd line) \?a,b,c THEN print the digits (the IF and the FOR loops are auto-closed by QBIC) ``` [Answer] # [R](https://www.r-project.org/), ~~67~~ ~~62~~ 61 bytes *-5 bytes thanks to Jarko Dubbeldam* ``` b=t(t(expand.grid(rep(list(0:5),3))));b[b%*%1:3==scan()-288,] ``` [Try it online!](https://tio.run/##K/r/P8m2RKNEI7WiIDEvRS@9KDNFoyi1QCMns7hEw8DKVFPHWBMIrJOik1S1VA2tjG1ti5MT8zQ0dY0sLHRi/xtZGvwHAA "R – Try It Online") reads the number from `stdin`; returns a matrix where the rows are the characters. It generates all possible trios of digits in a matrix format (`b`), computes the matrix product `b * [1,2,3]`, takes the rows of `b` which match (subtracting `288` from the input which is `1*48+2*28+3*48`) and returns them. ]
[Question] [ Sometimes it happens that while typing a sentence, I am distracted and I end up typing the same couple of words twice *couple of words twice* in succession. To make sure *make sure* other people are not bothered by this, your task is to write a program that resolves this problem! # Task Given an input string (if it matters for your language, you may assume ASCII-only input that does not contain linefeeds.) `str`, that contains somewhere in its middle a substring that occurs twice in immediate succession, return the string with one instance of this substring removed. In the case of multiple possibilities, return the shortest answer possible (that is, pick the longest consecutive repeating substring and remove that one). In the case of multiple, equally-long consecutive repeating substrings, remove the first (that is, the first one encountered when reading through the string from front to back) one. You may assume that the input is correct (i.e. always contains a consecutive repeating substring), which might help to golf it down. --- # Examples 1. Input: `hello hello world` -> Output: `hello world`. 2. Input: `foofoo` -> Output: `foo`. (So: Yes, the string might only consist of the repeating part twice). 3. Input: `aaaaa` -> Output: `aaa`, as the longest repeating consecutive substring is here `aa`. 4. Input: `Slartibartfast` -> This is not a valid input, as it does not contain a consecutive repeating substring, so you do not need to handle this case. 5. Input: `the few the bar` -> This is another invalid input, since the repeating part should immediately follow the original part. In this case, `the` and `the` are separated by something else in-between, so this input is invalid. 6. Input: `ababcbc` -> Output: `abcbc`. The two possible longest consecutive repeating substrings are `ab` and `bc`. As `ab` is encountered earlier in the string, this one is the correct answer. 7. Input: [`Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo`](https://en.wikipedia.org/wiki/Buffalo_buffalo_Buffalo_buffalo_buffalo_buffalo_Buffalo_buffalo). Output: `Buffalo buffalo buffalo buffalo Buffalo buffalo`. (The performed replacement should be case-sensitive). 8. Input: `Sometimes it happens that while typing a sentence, I am distracted and I end up typing the same couple of words twice couple of words twice in succession.` -> Output: `Sometimes it happens that while typing a sentence, I am distracted and I end up typing the same couple of words twice in succession.`. Only the longest consecutive repeating substring is removed. --- Your code should be as short as possible, since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. Good luck! [Answer] ## [Retina](https://github.com/m-ender/retina), ~~35~~ 33 bytes Byte count assumes ISO 8859-1 encoding. ``` (?=(.+)(\1.*)) $2¶$` O$#` $.& G1` ``` [Try it online!](https://tio.run/nexus/retina#dU5BasNADLzrFYK4xU6KIb2HHE1OOeSag2Wt3F2wd5esjMnH8oB@zF0n5NhhGIlhGOajbNqlPB7KeleV1329rSoovn8fRQvnYtNCUX9Cs2@XxcowBHzpHG6DgT6ETKAVQB113PHr5ofhEkZRN0pCp2gpRvEJ1ZLibN0gqPfo/A8SJvEqnuULT0gjGpf0RqxikLzJnmSd4juvVjDRKMhhirkm9Osck6tnx/@5zmOamCUlF3wNvK7sn/gD "Retina – TIO Nexus") ### Explanation Since regex engines look for matches from left to right, it's not trivial to find the longest match regardless of position. It can be done with .NET's balancing groups, but the result is rather unpleasantly long: ``` 1`((.)+)\1(?<=(?!.*((?>(?<-2>.)+).+)\3)^.*) $1 ``` So I figured I'd try to avoid that by making use of some other Retina features. ``` (?=(.+)(\1.*)) $2¶$` ``` We start by essentially applying *all* possible substitutions, one on each line. To do this, we match the position in front of a match (instead of the match itself), to allow for overlapping matches. This is done by putting the real regex into a lookahead. That lookahead then captures the remaining except the duplicate we want to remove in group 2. We write back group 2 (deleting the duplicate), a linefeed, and then then the entire input up to the match, which gives us basically a fresh line to be substituted. At the end we'll have one line for each match, with the corresponding duplicate removed. At the end there'll also be the full input again without any substitutions done. Now that we have all the possible substitutions, we want the shortest result (which corresponds to the longest removed repetition). ``` O$#` $.& ``` So we first sort the lines by length. ``` G1` ``` And then we only keep the first line. [Answer] # [Perl 6](https://perl6.org), 40 bytes ``` {.subst: m:ex/(.*))>$0/.max(*.chars),''} ``` [Try it](https://tio.run/nexus/perl6#xZC9bsMgEIB3nuKGqrYjB3fqkDTeO6djFozPNRIG5IM6UZQn69YXS8FJpKZS5yJ0P98d90MghI9nLtcsROsNya/ZcIBHaVuEzfnIKTTkVzCscF/lfFEU9cNTxQexzxdc9mKkosyy07mzI2hlkL4@OTmtfF7BC5@ohmxZZ1ezKmBZQw47ZVzwJexw71B6bKGAIwOIjXcjUtAeNpAmyOfEYh1jiuASKuH2qrwSdjr3qLWFi5zsqNvU6IfLOmvjTTQqJtJJTlRsq8XoVRNFJ8gnek@Y7xE6nCDpCFPGL8REIxrZyLlkMtjWDujVgATKQy@cQ0MxW3iYeqUR/MEp8w4CCI1HI7GEVxADtIr8KOY/EaaNDKMM7paf@pEYMP5OcLGM7dJ@bSw9KfkXVQYoSIlEyho@L/gv093P8Q0 "Perl 6 – TIO Nexus") ``` { .subst: # substitute m # match :exhaustive / ( .* ) # any number of chars )> # don't include the following in what is returned $0 # the first match again /.max( *.chars ), # find the first longest submatch '' # substitute it with nothing } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 bytes thanks to Dennis (avoid an argument reversal, remove subtly redundant increment) ``` ẋ2³wȧ+¥J ẆÇ€LÐṀḢṬœp ``` **[Try it online!](https://tio.run/nexus/jelly#dYw9CsIwGEB3T/HtioO3UNw8QUg@TcD80HwluBUHHVwEJ1dBXLq52I4tgtdILxKzOLq84fF4KbanWfcMn8e4uy@G6jqK7aE/Dvt62Z9jU8XXLTb1@@JSSiurkZRGD4pAMufQeCDJCIJUWwTaOWU2wMCjITQcJzAHpkEoTwXjhAKYEdlhZul@PUkEzzQCt6XLG7uGYAuR10Hxf1YZ8CXn6L2yZvoF)** Full program (a bug has been found with `ÐṀ` not acting with the correct arity over dyads, which will be fixed soon; although I'm not sure it can make for shorter code here). ### How? Finds the first of the longest slices of the input such that a repetition exists in the input and removes it from the input. ``` ẋ2³wȧ+¥J - Link 1, removal indices for given slice if valid, else 0: slice, x ẋ2 - repeat x twice, say y ³ - program input: s w - index of first occurrence of y in s (1-based) or 0, say i J - range(length(x)): [1,2,3,...,length(x)] ¥ - last two links as a dyad ȧ - and (non-vectorising) + - addition: [1+i,2+i,3+i,...,length(x)+i] or 0 - note: no need to decrement these since the last index will be the 1st index - of the repetition (thanks to Dennis for spotting that!) ẆÇ€LÐṀḢṬœp - Main link: string, s Ẇ - all sublists of s (order is short to long, left to right, e.g. a,b,c,ab,bc,abc) Ç€ - call the last link (1) as a monad for €ach ÐṀ - filter by maximal L - length Ḣ - head: get the first (and hence left-most) one Ṭ - untruth: make a list with 1s at the indexes given and 0s elsewhere œp - partition s at truthy indexes of that, throwing away the borders - implicit print ``` [Answer] # [Haskell](https://www.haskell.org/), 101 bytes Main function is `f`, it takes and returns a `String`. ``` l=length a=splitAt f s|i<-[0..l s-1]=[p++t|n<-i,(p,(r,t))<-fmap(a$l s-n).(`a`s)<$>i,r==take(l r)t]!!0 ``` [Try it online!](https://tio.run/nexus/haskell#nVDLasNADLzvVyjgg01sk969hRx77jEEIq@1sei@8MqYQv49Xbf02EuF0KBBDDPyyAE0cBBa0AhUsAbHgTL04DGBLfi9P512FO4yK9Q5OZazKAv5wUN3OfW9g9y9XPUlHY/yCEPHbZ3aemmlaYbOFqUaq/0mNH19w1tuhuqV20VrwQ@qHSyNXA@H0/M5k3MRfuYWFzcpG2NphXspHHE0o1Hv0ZOwLz5ZYMaUKGSQGQW2mR2BfCYOd0DIVKIFQy28AXqYOMselCbAMBWOylzT773MBBk9gYlrKjLR7iamIr2x@YstH8yrMZQzx9CrcbUWi/t/ovoC "Haskell – TIO Nexus") When I started this, I imported `Data.List` and used `maximum`, `tails`, `inits` and `isPrefixOf`. *Somehow* that got turned into this. But I still only managed to shave off 11 bytes... # Notes * `splitAt`/`a` splits a string at a given index. * `s` is the input string. * `i` is the list of numbers `[0 .. length s - 1]`, the `-1` is to work around that `splitAt` splits at the end if given a too large index. * `n` is `length s` minus the current length goal for the repeated part, it's chosen that way so we don't have to use two number lists and/or the verbose decreasing list syntax. * `p`,`r`, and `t` are a threeway split of `s`, with `r` the intended repeated part. The `fmap` there uses the `(,) String` `Functor` to avoid a variable for an intermediate split. * `!!0` selects the first element of the list of matches. [Answer] ## JavaScript (ES6), ~~81~~ 74 bytes ``` f= s=>s.replace(/(?=(.+)\1)/g,(_,m)=>r=m[r.length]?m:r,r='')&&s.replace(r,'') ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` Edit: Saved 7 bytes by stealing @Arnauld's `m[r.length]` trick. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 87 bytes ``` param($s)([regex](([regex]'(.+)\1'|% *hes $s|sort L*)[-1]|% Gr*|% V*)[1])|% Re* $s '' 1 ``` [Try it online!](https://tio.run/nexus/powershell#dU/LasMwEDwnXzEHp7JdN@CvCIWeWuglDWUtb2KBLQlJxi1xvt1dt@TYZZmdHYZ9qI773uEPJxf6VlXq7JykqqDoN1aWOoaIWGtDQVzUUKMbLezNDZzMwBEmoSPv2UYxUsLUmZ6Rvr2xFxAi28RWc4Vn0IDWxBRIJ25BthWNBUd/96@rIg0M7UYvY9x5vbCV0ZPR/6nGIo5ac4zG2b3CjB2u280DrounQEOexSI/Br7w1ym/E5XvH4uPWs07lJ28kcU5upDwUhbHp/ok8iGUgu/S16dC2CuX4oJSqJfNDdnn9rYsPw "PowerShell – TIO Nexus") (all test cases) ## Explanation Starting from the inside basically, we run `Matches` with the `(.+)\1` regex, to return all match objects for the specified string. The regex matches any sequence of characters that is followed by itself. Then the resulting match objects are piped into `sort` to be sorted by their `Length` property (shortened to wildcard). This results in an array of matches sorted by length, ascending, so index with `[-1]` to get the last element (the longest). That match's value is the match though, not the group, so it includes the repetition, so we retrieve the Group object (`|% Gr*`) and then the value of that (`|% V*`) to get the largest repeated string. Thing is the group object is actually an array because group 0 is always the match, but I want the actual group (1), so the resulting value is actually value**s**, hence indexing to get the second element `[1]`. This value is casted to a regex object itself and then the `Replace` method is called against the original string, replacing with nothing, and only the first match is replaced (`|% Re* $s '' 1`). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 21 bytes ``` ṚẆUẋ€2ẇÐf¹ṪðLHḶ+w@Ṭœp ``` *Thanks to @JonathanAllan for his `Ṭœp` idea which saved 2 bytes.* [Try it online!](https://tio.run/nexus/jelly#nU@xSsRAFOzzFdMbrvALLBXsDgvLl81bs5LsLtkXgp1YeIWNYCd@gVxhIXqJncEP2fuRuMdheY2PxwwMwzAzx@E5jvcXcXzY3q2P47iaHvX3EIfX6e38NG4@jvqTOKx/nvwcv96nVTJdIm4@t7cvWPraSI6GPHRnlRhnc1w7YxfzXHFdO@yxd21dZtq59BntLqOCClWobOkaFtNwgBFU5D3bAKlI0FemZsiNN/YKhMBW2CrOcQZqUJogLSnhEmTLpHHCzv/5pWIEahjKdT7FOL0rUabo3qhDqrEInVIcQhqyyIpOa0rt/8m7vQW12M/@BQ "Jelly – TIO Nexus") [Answer] # Mathematica, ~~63~~ ~~60~~ 59 bytes *4 bytes saved due to [Martin Ender](https://codegolf.stackexchange.com/users/8478).* ``` #&@@StringReplaceList[#,a__~~a__->a]~SortBy~{StringLength}& ``` Anonymous function. Takes a string as input and returns a string as output. [Answer] ## JavaScript (ES6), 70 bytes ``` s=>s.replace(s.match(/(.+)(?=\1)/g).reduce((p,c)=>c[p.length]?c:p),'') ``` ### Test cases ``` let f = s=>s.replace(s.match(/(.+)(?=\1)/g).reduce((p,c)=>c[p.length]?c:p),'') console.log(f("hello hello world")) console.log(f("foofoo")) console.log(f("aaaaa")) console.log(f("ababcbc")) console.log(f("Sometimes it happens that while typing a sentence, I am distracted and I end up typing the same couple of words twice couple of words twice in succession.")) ``` [Answer] This should be a comment, but I don't have enough reputations to comment. I just want to tell @Neil that his code can be reduced to 77 bytes. You don't need to use forward assertion in regex. Here is reduced version: ``` s=>s.replace(/(.+)\1/g,(_,m)=>(n=m.length)>l&&(l=n,r=m),l=0)&&s.replace(r,'') ``` [Answer] ## C#, 169 bytes ``` (s)=>{var x="";for(int i=0;i<s.Length-2;i++){for(int l=1;l<=(s.Length-i)/2;l++){var y=s.Substring(i,l);if(s.Contains(y+y)&l>x.Length)x=y;}}return s.Replace(x+x,x);} ``` ### Explanation ``` (s) => { // Anonymous function declaration var x = ""; // String to store the longest repeating substring found for (int i = 0; i < s.Length - 2; i++) { // Loop through the input string for (int l = 1; l <= (s.Length - i) / 2; l++) { // Loop through all possible substring lengths var y = s.Substring(i, l); if (s.Contains(y + y) & l > x.Length) x = y; // Check if the substring repeats and is longer than any previously found } } return s.Replace(x + x, x); // Perform the replacement } ``` This is the brute-force approach: try every possible substring until we find the longest repeating substring. Undoubtedly Regex is more efficient, but dealing with Regex in C# tends to be quite verbose. [Answer] # PHP, ~~84~~ 82 bytes Note: uses IBM-850 encoding. ``` for($l=strlen($argn);--$l&&!$r=preg_filter("#(.{0$l})\g-1#",~█╬,$argn,1););echo$r; ``` Run like this: ``` echo 'hello hello world' | php -nR 'for($l=strlen($argn);--$l&&!$r=preg_filter("#(.{0$l})\g-1#",~█╬,$argn,1););echo$r;';echo > hello world ``` # Explanation ``` for( $l=strlen($argn); # Set $l to input length. --$l && # Decrement $l each iteration until it becomes 0. !$r=preg_filter( # Stop looping when preg_filter has a result # (meaning a successful replace). "#(.{0$l})\g-1#", # Find any character, $l times (so the longest # match is tried first), repeated twice. ~█╬, # Replace with $1: first capture group, removing the # duplicate. $argn, 1 # Only replace 1 match. ); ); echo$r; # Print the result of the (only) successful # search/replace, if any. ``` # Tweaks * Saved 2 bytes because there is no minimum length of the repeated substring ]
[Question] [ ## Background [**Complex floor**](https://aplwiki.com/wiki/Complex_floor) is a domain extension of the mathematical floor function for complex numbers. This is used in some APL languages to implement floor `⌊`, ceiling `⌈`, residue `|`, GCD `∨`, and LCM `∧` on complex numbers. For the rest of this challenge, an *integer* refers to a Gaussian integer, i.e. a complex number whose real and imaginary parts are integers. Eugene McDonnell defined seven requirements of a complex floor function (copied from the wiki page, with APL code fragments translated into plain math notation): 1. *Existence.* Every number has a floor. 2. *Uniqueness.* Every number has only one floor. 3. *Fractionality.* The magnitude of the difference of a number and its floor shall be less than one. This property must be satisfied to guarantee that remainders are less in magnitude than divisors. It may be called the fundamental property of the floor function. 4. *Integrity.* The floor of a number is an integer. 5. *Convexity.* If \$g\$ is the floor of the numbers \$z\$ and \$w\$, then it is also the floor of all numbers on the line segment between \$z\$ and \$w\$. 6. *Integer Translation.* For \$c\$ a complex integer, \$c+ \lfloor z \rfloor = \lfloor c+z \rfloor\$. 7. *Compatibility.* The complex floor function is compatible with the real floor function. Furthermore, its action on purely imaginary numbers is similar to the action of the real floor function on real numbers. In particular, \$\operatorname{re}(\lfloor z \rfloor) ≤ \operatorname{re}(\lceil z \rceil)\$ and \$\operatorname{im}(\lfloor z \rfloor) ≤ \operatorname{im}(\lceil z \rceil)\$. (Ceiling for complex numbers is defined as \$\lceil z \rceil = -\lfloor -z \rfloor \$.) One shape that satisfies these conditions is a rectangle \$\sqrt{1\over2}\$ units high and \$\sqrt2\$ units wide, rotated 45 degrees, as in the following image. [![enter image description here](https://i.stack.imgur.com/BdrN5.png)](https://i.stack.imgur.com/BdrN5.png) One interesting consequence of *fractionality* is that the magnitude of the residue is always smaller than that of the divisor, and the Euclidean algorithm always terminates on arbitrary complex number inputs. ## Task Define your own complex floor that satisfies the requirements listed above, and implement it. It is OK if you simply use McDonnell's function. If you use a different function, please include an explanation of how it satisfies the requirements. Please note that simply flooring the two components is NOT a valid answer since it violates Fractionality: when \$z = 3.9 + 2.9i\$, $$ \lfloor z \rfloor = 3 + 2i \\ z-\lfloor z \rfloor = 0.9 + 0.9i \\ |z-\lfloor z \rfloor| = |0.9 + 0.9i| = 0.9 \sqrt2 > 1 $$ You may represent a complex number as a built-in complex number or a pair of real numbers. You don't need to care too much about boundary conditions, since floating-point imprecision will impact its correctness anyway. It is known to be implemented in Dyalog APL, J, and NARS2000. You are not allowed to use floor/ceiling/residue/GCD/LCM functions with non-real complex arguments for these languages. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Shortest code in bytes wins. [Answer] # **[BQN](https://mlochbaum.github.io/BQN/)**, 14 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` ⌊+·(⍋×1<+´)1⊸| ``` [Try it here.](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oyKK8K3KOKNi8OXMTwrwrQpMeKKuHwKCkbCqOKfqMKvMC4yNeKAvzAuNSwgwq8wLjI14oC/MC45LCAw4oC/MCwgMC4y4oC/MC4yLCAwLjXigL8wLjc1LCAxLjc14oC/MS414p+pCg==) ``` ⌊+·(⍋×1<+´)1⊸| # Tacit function which takes input as an array of 2 numbers ⌊ # floor + # plus ( ) # the parenthesized train: ⍋ # grade × # times 1<+´ # comparison 1 less than the sum · # applied monadically to 1⊸| # the fractional part ``` [Replicating the image in the challenge description.](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oyKK8K3KOKNi8OXMTwrwrQpMeKKuHwKMi/LmCjiipHin5wi4oqU4oy9wrciM3zCtyvin5woK8ucKcK0RinCqOKMveKNieKIvuKMnMucIDEty5wgMC4xw5fihpUyMQ==) [Answer] # [J](http://jsoftware.com/), 32 31 26 bytes ``` j.&<.+((1<:+)*0j1^<)&(1|]) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/s/TUbPS0NTQMbay0NbUMsgzjbDTVNAxrYjX/a3KlJmfkKxjqmSpo2Og5ZOkp2CqkaSoYwIQNUYQN9SwhEkZoEkZ6xhAJUzSJeGM9c5hZlpaodvwHAA "J – Try It Online") -5 thanks to Razetime for pointing out I could take real and imag parts as left and right args. Obligatory J answer. For reference, per the link in the OP, Eugene McDonnell's algorithm is: > > The algorithm for the determination of g , the floor of a complex number z , may be explained informally as follows: > > > 1. Let b be the point at the lower left corner of the unit square containing z . Let x and y be the fractional parts of the real and imaginary parts of z . > 2. Then: > > > * Let g = b if 1 > (x + y) , > * Let g = (b + 1) if (1 ≤ x + y) and x ≥ y , > * Let g = (b + 0i1) if (1 ≤ x + y) and x < y . > > > We take the real and imaginary parts as left and right args. We note that the answer is: ``` b + (0 or 1 or i) ``` depending on the case. * `j.&<.+` Floors both parts and converts back to complex `j.&<./`, then adds everything to the right `+`. This gives us the `b +` part. * `(...)&(1|])` Get fractional parts of real/imag pieces, and feed those as left and right args to everything in parens. This gives us x and y. * `(1<:+)` Is x + y greater than or equal to 1? Returns 0 or 1. Multiply that by... * `0j1^<` \$i\$ raised to "is x < y?" -- gives us \$i\$ if true, 1 otherwise. [Answer] # MMIX, 56 bytes (14 instrs) ``` 00000000: e0043ff0 17020300 17030301 06000002 ṭ¥?ṅ磤¡ç¤¤¢©¡¡£ 00000010: 06010103 04ff0001 01ffff04 6104ff00 ©¢¢¤¥”¡¢¢””¥a¥”¡ 00000020: 01ff0001 7005ff04 26040405 04000305 ¢”¡¢p¦”¥&¥¥¦¥¡¤¦ 00000030: 04010204 f8020000 ¥¢£¥ẏ£¡¡ ``` ``` cfloor SETH $4,#3FF0 // readj = 1. FINT $2,ROUND_DOWN,$0 // xf = floor(x) FINT $3,ROUND_DOWN,$1 // yf = floor(y) FSUB $0,$0,$2 // x -.= xf FSUB $1,$1,$3 // y -.= yf FADD $255,$0,$1 FCMP $255,$255,$4 CSN $4,$255,0 // if(x +. y <. 1) readj = 0 FCMP $255,$0,$1 ZSN $5,$255,$4 // imadj = x <. y? readj : 0 SUBU $4,$4,$5 // readj -= imadj FADD $0,$3,$5 FADD $1,$2,$4 // add in adjustments and swap (MMIX shuffle) POP 2,0 ``` [Answer] # [R](https://www.r-project.org/), 55 bytes ``` function(x,y=x%%1)(x+(sum(y)>1)*c(z<-diff(y)<0,!z))%/%1 ``` [Try it online!](https://tio.run/##K/qfnJ9bkJNaEZ@Wk59fZPs/rTQvuSQzP0@jQqfStkJV1VBTo0Jbo7g0V6NS085QUytZo8pGNyUzLQ3ItzHQUazS1FTVVzVENUYjWcPQQM9Mx9BUz1xT8z8A "R – Try It Online") Straightforward implementation of McDonnell's function. --- # [R](https://www.r-project.org/), 71 bytes ``` function(x,y=x%%1,w=c(z<-diff(y)<0,!z))(x+(sum(y/(1+2^.5*!w))>1)*w)%/%1 ``` [Try it online!](https://tio.run/##VcxBDoIwFAXAs7Bo8h6UwjdBN9Sj6KLahASoQUhbLl/XzgFmKy4sn/mdnn4OYbPFH6vbp7Ai6WyTUqKjdTjH9jV5j8yx19VJIjX4HgtyB2kuDzPUVSTvwjpSdUr@WzhIb65aBnMjyw8 "R – Try It Online") 16 bytes longer, but minimizes the amount of rounding-up required\*, while still satsifying the convexity requirement, for all complex numbers. McDonnell's function unsatisfyingly rounds-up either the `r`eal or `i`maginary part of a complex number whenever their fractional parts sum to greater than `1`, even though the fractionality requirement (condition #3) would still be satisfied by rounding down until `r^2+i^2>1`. The convexity requirement (condition #5) prevents us from rounding down for all `r^2+i^2<=1`, but we can minimize the amount of rounding-up needed by using a 'quarter-octagon' shape, instead of a triangle, for fractional `r` and `i` between `0` and `1`. The rounding 'domains' are shown in different colours here: [![enter image description here](https://i.stack.imgur.com/LivMU.png)](https://i.stack.imgur.com/LivMU.png) \* I think. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~57~~ 74 bytes ``` (a,b,x=a%1,y=b%1,s=Math.abs)=>1>x+y?[a-s(x),b-s(y)]:[a-x+(x>=y),b-y+(x<y)] ``` [Try it online!](https://tio.run/##FYhbCsJADEVXI2RoOrQ/ImLGFbgC8SNTWx@UTjFFktWP8efcc8@bvyzD57Vu7VLuY52oAmNGJd71aJSdQhfenpGzBEp90sbOV24FNGD2sXA7@tcGNJH9m7mePNehLFLmMc7lARN0cY9dPIRQfw "JavaScript (Node.js) – Try It Online") ## Explanation Uses a similar algorithm as @Jonah's answer. > > The algorithm for the determination of g , the floor of a complex number z , may be explained informally as follows > > > Let b be the point at the lower left corner of the unit square containing z . Let x and y be the fractional parts of the real and imaginary parts of z . > Then: > Let g = b if 1 > (x + y) , > Let g = (b + 1) if (1 ≤ x + y) and x ≥ y , > Let g = (b + 0i1) if (1 ≤ x + y) and x < y . > > > Needed to add 17 bytes in order to sort out a bug. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` Ḟɓ_Ụ’×S>1ƊƲ+ ``` [Try it online!](https://tio.run/##y0rNyan8///hjnknJ8c/3L3kUcPMw9OD7QyPdR3bpP3/cPujpjX//0frGugZmeooGOiZxuooIHiWIJ4BkAWm9YxAYkYQNljeHKzcEEjrKBhC9BromYFkzGIB "Jelly – Try It Online") -3 bytes by using the `grade up` idea from [frasiyav's BQN answer](https://codegolf.stackexchange.com/a/225782/68942). Go upvote that too. -1 byte by fixing a bug pointed out by tsh -1 byte thanks to caird coinheringaahing This is just a golf of Eugene McDonnell's algorithm. Using the same concept for golfing the 3-way conditional as [Jonah's J answer](https://codegolf.stackexchange.com/a/225766/68942). [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 58 bytes ``` lambda a,b:[a//1+(w:=a%1>=b%1)*(q:=1<=a%1+b%1),b//1+(q>w)] ``` [Try it online!](https://tio.run/##RYvBCoMwEETv/YpchERXzaZI29D4I9ZDQpEKrUYRNP35NBGhl5k3s7PWLa9xOF/t7Dv18G/9MU9NNBjZ6LLEjK5S6QRrZRJkKZ2kwnssspjB7JOpXlnru3EmGzjSD@TbW9o0vBAV8KJqockPvgXmwKMWImSxU7xc4gyDAYaPwMcuR8D/06GxEUFbJk/Ezv2w0I6mGwMHuyvlmP8B "Python 3.8 (pre-release) – Try It Online") thanks to @ovs for -12 [Answer] # [Ruby](https://www.ruby-lang.org/), ~~55~~ 47 bytes ``` ->a,b{(a-a%=1)+1i*(b-b%=1)+(a+b<1?0:a>b ?1:1i)} ``` [Try it online!](https://tio.run/##NYrLCoMwEEV/JZtKopMwUwjS4ONDQhYzC8GFIIUuRPrtcSp0cbnnwHl/5KjLWP3EIKdlz4@RXEdra8XLzZY7GWjGxJOYmRKt7lt3kzMCFjAZwzOCwRALZP@Xl4oy6G6KSv2vID0gjUvYeLfN4uoF "Ruby – Try It Online") Thanks [Eric Duminil](https://codegolf.stackexchange.com/users/65905/eric-duminil) for the idea of using 2 arguments. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~26~~ 23 bytes ``` NθNηIE²⌊⊘⁺⊕⁺θη×⌊⁻θη∨±ι¹ ``` [Try it online!](https://tio.run/##TcvLCsIwFATQfb@iyxuohUTFSpeC2EVrF/5AjBcTyKPNo78fCyp0dmeGEZJ74bjOubNTikMyT/Qwk7bYWq4evbIRLjxE6PkErCqv2jkPN64XfMGoU4DOCo8GbfwXc1VKQqryoQwG@B56ZTfL3cOAbx4R1CpKfmlz3tf0QI/ngtUn2rAm7xb9AQ "Charcoal – Try It Online") Explanation: Calculates \$ \lfloor a + bi \rfloor \$ using the following formula which is the complex conjugate of the rectangular tiling suggested in the question, and therefore trivially still satisfies all the requirements: $$ \lfloor a + bi \rfloor = \left \lfloor \frac { 1 + a + b + \lfloor a - b \rfloor } 2 \right \rfloor + \left \lfloor \frac { 1 + a + b - \lfloor a - b \rfloor } 2 \right \rfloor i $$ In particular when \$ b = 0 \$, \$ \lfloor a + bi \rfloor = \left \lfloor \frac { 1 + a - \lfloor a \rfloor + 2 \lfloor a \rfloor } 2 \right \rfloor + \left \lfloor \frac { 1 + a - \lfloor a \rfloor } 2 \right \rfloor i = \lfloor a \rfloor \$ and when \$ a = 0 \$, \$ \lfloor a + bi \rfloor = \lceil b \rceil i \$. [Answer] # Excel, 61 bytes ``` =LET(a,INT(A1:B1),a+(SUM(A1:B1-a)>=1)*({1,0}+(A1<B1)*{-1,1})) ``` Uses McDonnell's definition. Real coefficient in A1; imaginary in B1. Output is an array of real and imaginary coefficients. ## Without LET, also 61 bytes ``` =INT(A1:B1)+(SUM(A1:B1-INT(A1:B1))>=1)*({1,0}+(A1<B1)*{-1,1}) ``` ## Alternate, 35 bytes ``` =INT((1+A3+B3+INT(A3-B3)*{1,-1})/2) ``` This is a port of [Neil's answer](https://codegolf.stackexchange.com/a/225805/101349) ]
[Question] [ *Inspired by [a question](https://stackoverflow.com/q/45788547/2586922) at Stack Overflow*. Given a non-empty array of integers `x` and a positive integer `n`, compute the **sum** of each **sliding block** of length `n` along the array `x`, **circularly** filling the missing values at the left with values from the right as follows: * the first block contains the first entry of `x`, preceded by `n-1` circularly shifted entries; * the second block has the first and second entries of `x`, preceded by `n-2` circularly shifted entries; and so on. The output array `y` has the same size as `x`. It is possible for `n` to exceed the length of `x`, and then the values of `x` are circularly **reused several times**. # Examples ### Example 1 (values are reused only once) ``` x = [2, 4, -3, 0, -4] n = 3 ``` give as output ``` y = [-2, 2, 3, 1, -7] ``` where * `-2` is the sum of the block `[0, -4, 2]` (the first two values come from the circular shifting) * `2` is the sum of `[-4, 2, 4]` (the first value comes from the circular shifting) * `3` is the sum of `[2, 4, -3]` (no circular shifting necessary anymore) * `1` is the sum of `[4, -3, 0]` * `-7` is the sum of `[-3, 0, -4]`. ### Example 2 (values are reused several times) ``` x = [1, 2] n = 5 ``` give ``` y = [7, 8] ``` where * `7` is the sum of the block `[1, 2, 1, 2, 1]` (the first four values have been circularly reused) * `8` is the sum of the block `[2, 1, 2, 1, 2]` (the first three values have been circularly reused) # Additional rules * The algorithm should work for arrays of arbitrary size and for arbitrary integer values. It is acceptable if the program is limited by data type or memory restrictions; but positive as well as negative integer values must be handled. * Input/output can be taken/produced by any [reasonable means](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). * [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Shortest code in bytes wins. # Test cases ``` x, n, -> y [2, 4, -3, 0, -4], 3 -> [-2, 2, 3, 1, -7] [1, 2], 5 -> [7, 8] [2], 7 -> [14] [-5, 4, 0, 1, 0, -10, -4], 4 -> [-19, -15, -5, 0, 5, -9, -13] [-5, 4, 0, 1, 0, -10, -4], 1 -> [-5, 4, 0, 1, 0, -10, -4] [-2, -1, 0, 1, 2, 3], 5 -> [4, 3, 2, 1, 0, 5] [-10, 0, 10], 4 -> [-10, 0, 10] ``` [Answer] # MATL, ~~11~~ ~~10~~ ~~9~~ 7 bytes *3 Bytes saved thanks to @Luis!* ``` :gyn&Z+ ``` The first input is the size of the window and the second input is the array Try it at [MATL Online](https://matl.io/?code=%3Agyn%26Z%2B&inputs=3%0A%5B2%2C+4%2C+-3%2C+0%2C+-4%5D&version=20.4.1) **Explanation** ``` % Implicitly grab the first input (n) % STACK: { 3 } : % Create the array [1...n] % STACK: { [1, 2, 3] } g % Convert it to a logical array, yielding an array of 1's of length n % STACK: { [1, 1, 1] } y % Implicitly grab the second input and duplicate it % STACK: { [2, 4, -3, 0, -4], [1, 1, 1], [2, 4, -3, 0, -4]} n % Determine the length of the array % STACK: { [2, 4, -3, 0, -4], [1, 1, 1], 5} &Z+ % Perform circular convolution % STACK: { [-2, 2, 3, 1, -7] } % Implicitly display the result ``` [Answer] # Mathematica, 29 bytes ``` RotateLeft[#,1-n]~Sum~{n,#2}& ``` Or the same length: ``` ListConvolve[1~Table~#2,#,1]& ``` [Answer] ## CJam (16 bytes) ``` {_2$*ew1fb\,~)>} ``` [Online test suite](http://cjam.aditsu.net/#code=q'%2C-N%25%7B%22-%3E%22%25S*~%3AE%3B%0A%0A%7B_2%24*ew1fb%5C%2C~)%3E%7D%0A%0A~E%3Do%7D%2F&input=%5B2%2C%204%2C%20-3%2C%200%2C%20-4%5D%2C%203%20%20%20%20%20%20%20%20%20%20-%3E%20%20%5B-2%2C%202%2C%203%2C%201%2C%20-7%5D%0A%5B1%2C%202%5D%2C%205%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20-%3E%20%20%5B7%2C%208%5D%0A%5B2%5D%2C%207%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20-%3E%20%20%5B14%5D%0A%5B-5%2C%204%2C%200%2C%201%2C%200%2C%20-10%2C%20-4%5D%2C%204%20%20-%3E%20%20%5B-19%2C%20-15%2C%20-5%2C%200%2C%205%2C%20-9%2C%20-13%5D%0A%5B-5%2C%204%2C%200%2C%201%2C%200%2C%20-10%2C%20-4%5D%2C%201%20%20-%3E%20%20%5B-5%2C%204%2C%200%2C%201%2C%200%2C%20-10%2C%20-4%5D%0A%5B-2%2C%20-1%2C%200%2C%201%2C%202%2C%203%5D%2C%205%20%20%20%20%20%20%20-%3E%20%20%5B4%2C%203%2C%202%2C%201%2C%200%2C%205%5D%0A%5B-10%2C%200%2C%2010%5D%2C%204%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20-%3E%20%20%5B-10%2C%200%2C%2010%5D). This is an anonymous block (function) which takes the array and the length on the stack and leaves an array on the stack. ### Dissection ``` { e# Declare a block _2$* e# Repeat the array n times: this guarantees having enough windows even e# if x is only a single element ew e# Take each window of n elements 1fb e# Sum each of the windows \,~) e# Compute -n > e# Take the last n elements of the array of sums } ``` [Answer] ## Haskell, 57 bytes ``` a#n|l<-length a=[sum[a!!mod j l|j<-[i-n..i-1]]|i<-[1..l]] ``` [Try it online!](https://tio.run/##VYxBDoIwFET3nmIILvsbCyVu4CRNF00gUvwtRnDH3WvRxOBqMm8yb3TLfWBOyZVx45Z4iLd1hOvM8grGFUWYe0zgbWrJeIpSelLWbj5XJSVbm4LzER36@QQ8nj6uOMNUAlqAaoFLDm1Roj7uSqDaYfN32sn1SKj5eLJDfU3qp9PpDQ "Haskell – Try It Online") Just some index looping and accessing the input list at indices modulo the length of the list. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ṙC€}S ``` [Try it online!](https://tio.run/##y0rNyan8///hzpnOj5rW1Ab/P7zcSN/9//9oLoVoIx0FEx0FXWMdBQMgZRKro2CsAxQ21FEwArJNQWwQwxzE0DUFKwYqNIQoN4TpMcEvbQiWNgIJweSBHGOYBWCFIGEDiFGxAA "Jelly – Try It Online") ### How it works ``` ṙC€}S Main link. Arguments: A (array), n (positive integer) } Apply the link to the left to the right argument (n). C€ Complement each; map (z -> 1-z) over [1, ..., n], yielding [0, ..., 1-n]. ṙ Rotate A 0, ..., 1-n units to the left (i.e., 0, ..., n-1 units to the right), yielding a 2D array. S Take the sum of the rows. ``` [Answer] # [Haskell](https://www.haskell.org/), ~~69~~ ~~65~~ 64 bytes ``` r=reverse s#n=r$init[sum$take n$x++cycle(r s)|x<-scanr(:)[]$r s] ``` [Try it online!](https://tio.run/##jZDRisIwEEXf/YoL5kGxgaZN6a5sv6T0odSAxRolqYsL@@/dmbCViAoOgYSbc28ms2/9wQzDNLnKmW/jvFn4pa2c6G0/1v5yFGN7MLDiutl0P91gVg5@/Xv9kr5rrVtt13UjSGqmY9tbVNidFji73o4QqLMEOoHME6S06QZL5LiVlEAtiaFFiCKkbCI3CRlbCjyr4C4TfMSWwJd4UcGidGyQRWgxDc9zk@rWqZ47VJ@sE8gwXfMpSPmbSWpOeoHEKRnLM8ODiScQUnSYVjaHFHd2TmRv@v@Dx/9HyPQH "Haskell – Try It Online") Example usage: `[2, 4, -3, 0, -4] # 3`. --- Using `n` *succeeding* instead of *preceding* entries could be ~~50~~ 46 bytes (getting rid of the reverse at the beginning and the end): ``` s#n=init[sum$take n$x++cycle s|x<-scanr(:)[]s] ``` [Try it online!](https://tio.run/##DcVBCoAgEAXQq3zIRZFBZKuok4gLESHRhmgMDLq79TZvtxx9SrVyQ1ugkDXfh8g2epAofe8elzz4LevAztLVLp02bOphA2HDeQXKENCTxCwxKInxbzZooOoH "Haskell – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 bytes ``` ËVo rÈ+UgE-Z ``` [Try it online!](https://tio.run/##y0osKPn//3B3WL5C0eEO7dB0V92o//@jDXWMdIx1TGJ1FIwA "Japt – Try It Online") TIO doesn't support the `Ë`, so the TIO link won't work. Instead, [try it here](https://ethproductions.github.io/japt/?v=1.4.5&code=y1ZvIHLIK1VnRS1a&input=WzEsIDJdLCA1IC1R). [Answer] # [Pyth](https://pyth.readthedocs.io), ~~18~~ 16 bytes *Saved 2 bytes thanks to [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman)!* ``` JEms<.>*JQ-JhdJl ``` **[Try it here](https://pyth.herokuapp.com/?code=JEms%3C.%3E%2aJQ-JhdJl&input=%5B2%2C+4%2C+-3%2C+0%2C+-4%5D%0A3%0A&test_suite_input=%5B2%2C+4%2C+-3%2C+0%2C+-4%5D%0A3%0A&debug=0&input_size=3) or [Verify all the test cases.](https://pyth.herokuapp.com/?code=JEms%3C.%3E%2aJQ-JhdJl&test_suite=1&test_suite_input=%5B2%2C+4%2C+-3%2C+0%2C+-4%5D%0A3%0A%0A%5B1%2C+2%5D%0A5%0A%0A%5B2%5D%0A7%0A%0A%5B-5%2C+4%2C+0%2C+1%2C+0%2C+-10%2C+-4%5D%0A4%0A%0A%5B-5%2C+4%2C+0%2C+1%2C+0%2C+-10%2C+-4%5D%0A1%0A%0A%5B-2%2C+-1%2C+0%2C+1%2C+2%2C+3%5D%0A5%0A%0A%5B-10%2C+0%2C+10%5D%0A4%0A&debug=0&input_size=3)** Fixed all the flaws at a cost of *-6 bytes*! Thanks a lot to Luis for making me understand the task in chat. --- # Explanation (to be updated) ``` KEms<>_*QhK-lQhdKU - Full program. KE - Assign the second input to a variable K. m U - Map over the range [0...len(first input)). *QhK - First input * (Second input + 1). _ - Reverse. > -lQhd - All the elements of the above after len(x)-current element-1 < K - Up until the second input. s - Sum. ``` [Answer] # Java 8, 102 bytes Lambda (curried) from `int[]` to lambda from `Integer` to `int[]`. Assign to `Function<int[], Function<Integer, int[]>>`. ``` a->n->{int l=a.length,o[]=new int[l],i=0,j;for(;i<l;i++)for(j=i-n;j++<i;)o[i]+=a[(j%l+l)%l];return o;} ``` [Try It Online](https://tio.run/##fVLBitswED07XzGXBQnLYru7vVRxYCkUeugpR@OD6lWy41VGRpJTwuJvT2U5aVpoC7bkefNmxu9JvT7qyg2G@pe38zB@t9hBZ3UI8E0jwfuqGDwedTQQoo4puUPSFvpUJseIVu5G6iI6kl8uH2uk2LTiv5SvFM3eeAGZu9lAh74brfbb8RCgPutqQ9XmPWXB1lpaQ/v4KlzT1mR@5CLbCqzvRa92zjOFa6uwLPkc9DVWpPqyXKPirsG2rHXD@jtbWn5nW@VNHD2BU9O5UKukbxF9kXd0@AKHJJ1to0faNy1ovw98dqJYjPmsg8nhtXSxJEsBiyGqv@WA5mG/8LkJu5WIhbKMKYr4ikHOONS3jgtKCaIcT6v5TcvcK/Xp0hbmbLLoAuVu15hdvUv4g4AnAdWjgPu0PU0CHrn4F/mDgIfE@JgZU5aRjAaWjdB5/bRMv/z/9hSiOUg3RpluD0VL7HYbnr3XpyCjWwxmvx@91MNgTyz3zPr5HwhxzlVWnZ7p/BM) ## Ungolfed lambda ``` a -> n -> { int l = a.length, o[] = new int[l], i = 0, j ; for (; i < l; i++) for (j = i - n; j++ < i; ) o[i] += a[(j % l + l) % l]; return o; } ``` `(j % l + l) % l` computes a nonnegative remainder for any `j`. Taken from [here](https://stackoverflow.com/a/4412200). [Answer] # C, 91 bytes ``` i,j,k,s;f(a,l,n)int*a;{for(i=0;i<l;printf("%d ",s))for(j=n*l+i++,k=n,s=0;k--;)s+=a[j--%l];} ``` [Try it online!](https://tio.run/##fY/daoQwEIXvfYpBWEjWCajx5yL1ScJeiK0lau2ysVfis9tJbKFhsSEQkjnnOyedeO@6fTc44IhW9azFCWdu5uXaqrX/fDDTpMq8TOr@oMeexZdXiNFy7mZDM1@nxCQJjs2MlpSjEIrbpGn1IMRluqltJxt8tGZmPFojoOUelje76PIGDaw5QoEgJEJKR7EpL@qZkyCUCJKr@9diWRxzFQWE/AeRIeSBj5i0y1Oj1NmRHbioApHqU1eha@8Spa@cerkrnT03p3lNqifW32l2mlTp6kjKHf03ii4yCKkQqv@@WWt5YFxBx0gDO1WQvmO07d8) [Answer] # Octave, 53 bytes ``` @(x,n)shift(imfilter(x,+!!(1:n),'circular'),fix(n/2)) ``` [Try it online!](https://tio.run/##DchBCoAgEADAr@jJXdqozFOn/hEdRJQWzMAs/L11GpjLFfv61laolPA@OBTgM3AsPv/VSQnTkpCU4@yeaLNCClwhDRqx2XTDpkkYEv1MYvwxO4kZ2wc "Octave – Try It Online") * The `imfilter` function with option `circular` computes the circular convolution at the center of window so the result should be shifted. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` .׌ùOR¹g£R ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f7/D0o5MO7/QPOrQz/dDioP//o3VNdRRMdBQMdBQMwaSuIYgwieUyAQA "05AB1E – Try It Online") **Explanation** ``` .× # repeat input_1 input_2 times Œù # push all sublists of size input_2 O # sum each R # reverse the list ¹g£ # take the first len(input_1) items R # reverse the list ``` [Answer] # [Perl 6](https://perl6.org), ~~42~~ 39 bytes ``` {@^a;[«+»] map {@a.rotate(-$_)},^$^b} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPu/2iEu0Tr60GrtQ7tjFXITCxSqHRL1ivJLEktSNXRV4jVrdeJU4pJq/1tzcRUngvRoRBvpKJjoKOga6ygYACmTWB0FY01ruKyhjoIRUMgUSQjEN0fi65qCTQDqNoSYYQgzyIQoVYbIqoxAMjBlQI4xmuVgbSBZA4j5/wE "Perl 6 – Try It Online") My first Perl 6 entry. Can probably be improved. [Answer] # [Kotlin](https://kotlinlang.org), ~~141~~ ~~140~~ 138 bytes Just a first go ## Submission ``` fun c(a:List<Int>,n:Int):List<Int>{ return (0..(a.size-1)).map{var t=0 for (o in 0..(n-1)){var i=it-o while(i<0) {i+=a.size};t+=a[i]} t}} ``` ## Beautified ``` fun c(a: List<Int>, n: Int): List<Int> { return (0..(a.size - 1)).map { // Iterate over the items var t = 0 // Start the total at 0 for (o in 0..(n - 1)) { // Start at the item, go over the window backwards var i = it - o // ------------------------- while (i < 0) { // Make the index in range i += a.size // } // ------------------------- t += a[i] // Add the item to the total } t // Return the total } } ``` ## [TryItOnline](https://tio.run/##nVPBToQwFLz3K56eaAQCyGYVxcSDJiYmJurNeGh2WW3EdtMWN7rh29f3ygKuiXuwh7bMmzcMZfqmXS3VZrNoFMwCUdxK685vlLsIVYELH4E1M5VrjIIgieNAxFZ@VVHKefwulusPYcCVCVtoA4EGqYBIiuq@JkvpIs1Wr7KuAnmecFjLo7ITac8cbp/kc8tc2zI2F07ArBbWwn2jgg9Ro96ycQWM5oDQlVRzvSoAkQ7Qjdvlccbow96FJB0jzAtYZ6R6KR78gjYY4KBmLFoocTHi824ReLwf5KNGUcSzEPIQouMQElxyHgJut7UIi5kHUqxNOQ//UsF6hq2ToXUawskePpGnAznN91CjiXeYeBPkMe2N5qPR9JQKyCR24o1EHjr@l3I6Kv/B2aOaEatvoePbOZjcn2fW6032KdG7SCb59bEDzH1rN/uoUiIwrPTv@yz0eejChImYESv2EQyJGXe54wNbLjDzHfug9Izu6aciDfdq9Aoura2Mk1pdGaNNcPhYWQfXAi/G/HDUbNk4LzGqrlZb6hIvhqe2m803) # Edits * Removed newline on before last closing bracket [Answer] # [Röda](https://github.com/fergusq/roda), 52 bytes ``` f a,n{(a*n)|slide n|tail#a*n|{head n|sum}while open} ``` [Try it online!](https://tio.run/##hU9LCoMwEF0npxgsFJUIfumqJwmhhCZiQBMxli7Us9uYqnRXGJiZ95nhDUbwda2BEz2FPNbRbFslJOh55Kq9OGSeGsmFA@yrW96NaiWYXupl7bjSMGE0Sjs@ntxKC3egGCFKcwIlgaQgkLpWMgIFI57JCORurfZ1m2/7nFTe5RzZ15cd5vKvIjsU@YYektz/PZ95@cak/iZGDGNUmwHOBOAS/cQRxvn6QekxDGhAgNZhfNIRuzpoKxZEGAmjJV7WDw "Röda – Try It Online") Explanation: ``` f a,n{ (a*n)| /* Push the items in a n times to the stream */ slide n| /* Create a sliding block of length n */ tail#a*n| /* Push the last n*len(a) values in the stream to the stream */ { /* While there are elements in the stream (stream is open): */ head n| /* Pull n values from the stream */ sum /* Sum them and push the sum to the stream */ } while open } ``` [Answer] # JavaScript ES6 ~~80~~ 78 bytes ``` x=>n=>x.map((_,i)=>eval('for(L=x.length,N=0,j=++i-n;j<i;j++)N+=x[(j%L+L)%L]')) ``` 2 bytes saved thanks to Neil ### Usage: ``` f=x=>n=>x.map((_,i)=>eval('for(L=x.length,N=0,j=++i-n;j<i;j++)N+=x[(j%L+L)%L]')) f([2, 4, -3, 0, -4])(3) ``` [Answer] # [Perl 5](https://www.perl.org/), 66 + 1 (-a) = 67 bytes ``` $n=pop@F;$,=$";say map{$q=$c++;$t=0;$t+=$F[$q--%@F]for 1..$n;$t}@F ``` [Try it online!](https://tio.run/##K0gtyjH9/18lz7Ygv8DBzVpFx1ZFybo4sVIhN7GgWqXQViVZW9tapcTWAEho26q4RasU6uqqOrjFpuUXKRjq6ankASVqHdz@/zdUMFIw/ZdfUJKZn1f8X9fXVM/A0OC/biIA "Perl 5 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~69~~ 61 bytes **- 8 bytes Thanks a lot @muru** ``` lambda x,n:[sum((x[-n+1:]+x*n)[i:i+n])for i in range(len(x))] ``` [Try it online!](https://tio.run/##fVDdCoIwFL7OpziXWx7B@UMg@CRrFwu1FnoUM7Cnt21iGES7Gd/v2c7wmm49JUtTnpdWd5dKw4xUyMezY2yWEYWiUOF8JC5NYUJSvOlHMGAIRk3XmrU1sZlztVR60qUMDkwmCBlClCLE9soUQgocnSIwsShfwQ8bR/gcb7HkaU9@qVHuG2xarB1iK8ps5r9DuFZvSRy9eSxI1xfu57iU02NfHajA7wDvbgvu20UAw2hogoZZli9v "Python 2 – Try It Online") Explanation: First we need to ensure there is enough numbers on the left of the original list, this is acheived by the `x*n+x` part. For, example: `[2,4,-3,0,4],5`: ``` ,2,4,-3,0,-4 ....-4,2,4,-3,0,-4,2,4,-3,0,-4 ``` Then we shall reverse the list: ``` <original-> -4,0,-3,4,2, -4,0,-3, 4........ <-2's block-> ``` Next we obtain corresponding blocks for each element by `[len(x)+~i:][:n]`. The slice will be reverse i.e. 2 will gain a block: `[2,-4,0,-3,4]` which is reverse of the expected `[4,-3,0,-4,2]`, but we need the sum after all. So, this works. :) [Answer] # [R](https://www.r-project.org/), ~~101~~ ~~93~~ 89 bytes ``` function(x,n,w=sum(x|1)){for(j in 1:w)F=c(F,sum(c(tail(rep(x,n),n-1),x)[1:n+j-1])) F[-1]} ``` [Try it online!](https://tio.run/##JYvNCsIwDMfve4oeG0zBrPMy6LUvMTxIsdChmdSNFdRnr6le8v/6Jdfoatw4rGlhXZBxd8/trsubAF5xyXpWiRWNO3gXtMc2Br1e0k3n66N9ALIhwAITjXyYDZ0BOj@JfmoUtkc1oDIW1VFkALTQtZ6wBzz9vRHI0I@QK8G2qX4B "R – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 18 bytes **Solution:** ``` {+/+y':(1-y+#x)#x} ``` [Try it online!](https://tio.run/##y9bNz/7/v1pbX7tS3UrDULdSW7lCU7miNtpIwURB11jBQEHXxNo49v9/AA "K (oK) – Try It Online") **Examples:** ``` {+/+y':(1-y+#x)#x}[1 2;5] 7 8 {+/+y':(1-y+#x)#x}[-5 4 0 1 0 -10 -4;4] -19 -15 -5 0 5 -9 -13 {+/+y':(1-y+#x)#x}[-10 0 10;4] -10 0 10 ``` **Explanation:** Was about to post a **31 byte** solution then I remembered that oK has a [built-in](https://github.com/JohnEarnest/ok/blob/gh-pages/docs/Manual.md#verb-reference) for sliding windows... ``` {+/+y':(1-y+#x)#x} / the solution { } / lambda with implicit x and y parameters #x / take (#) from list x ( #x) / length of x y+ / add y (window size) 1- / subtract from 1 to give a negative y': / sliding window of size y + / flip +/ / sum ``` **Bonus:** The **31 byte** solution that also works in [K4](http://kx.com/download/): ``` q)k){+/+x#y#'|+(:':\|(1-y+x:#x)#x)}[2 4 -3 0 -4;3] -2 2 3 1 -7 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` £gVonY)x ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=o2dWb25ZKXg&input=WzIgNCAtMyAwIC00XQoz) ``` £gVonY)x :Implicit input of array U=x & integer V=n £ :Map each 0-based index Y in U g : Get the elements in U at 0-based indices Vo : Range [0,V) nY : Subtract each from Y ) : End indexing x : Reduce by addition ``` ]
[Question] [ The challenge this time is to find the *n*th *Fibohexaprime*. The definition of a *Fibohexaprime* is as following: We first observe a list with Fibonacci numbers: ``` N | Fibonacci number 1 | 1 2 | 1 3 | 2 4 | 3 5 | 5 6 | 8 7 | 13 8 | 21 9 | 34 10 | 55 11 | 89 12 | 144 13 | 233 14 | 377 15 | 610 16 | 987 17 | 1597 ``` After that, we convert the numbers to hexadecimal: ``` N | Fib | Hex 1 | 1 | 1 2 | 1 | 1 3 | 2 | 2 4 | 3 | 3 5 | 5 | 5 6 | 8 | 8 7 | 13 | D 8 | 21 | 15 9 | 34 | 22 10 | 55 | 37 11 | 89 | 59 12 | 144 | 90 13 | 233 | E9 14 | 377 | 179 15 | 610 | 262 16 | 987 | 3DB 17 | 1597 | 63D ``` From the hexadecimal numbers, we filter out the letters. All we are left with are numbers. We need to check if these numbers are prime: ``` hex | filtered | is prime? | N = 1 > 1 > false 1 > 1 > false 2 > 2 > true 1 3 > 3 > true 2 5 > 5 > true 3 8 > 8 > false D > 0 > false 15 > 15 > false 22 > 22 > false 37 > 37 > true 4 59 > 59 > true 5 90 > 90 > false E9 > 9 > false 179 > 179 > true 6 262 > 262 > false 3DB > 3 > true 7 63D > 63 > false ``` If the filtered number is a prime, we call this a **Fibohexaprime**. You can see that for `N = 7`, the related fibonacci number is 987. The task is simple, when given an input using STDIN or an acceptable alternative, write a program or a function which outputs the nth Fibohexaprime using STDOUT or an acceptable alternative. Test cases ``` Input - Output 1 - 2 2 - 3 3 - 5 4 - 55 5 - 89 6 - 377 7 - 987 8 - 28657 9 - 75025 10 - 121393 11 - 317811 12 - 5702887 13 - 9227465 14 - 39088169 15 - 102334155 16 - 32951280099 17 - 4052739537881 18 - 806515533049393 19 - 7540113804746346429 ``` The rules: * Given an integer between `1` and `19` (the values above `20` exceed the max value for a 64-bit signed integer), output the corresponding value. * You may write a function or a program. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! [Answer] ## [MATL](https://esolangs.org/wiki/MATL), 28 bytes This uses MATL version [1.0.0](https://github.com/lmendo/MATL/releases/tag/1.0.0), which was published in [Esolangs](https://esolangs.org/wiki/MATL) on December 12, earlier than this challenge. ``` 1Hi:"`tb+t16YAt58<)YtZp~]]1$ ``` ### Example ``` >> matl 1Hi:"`tb+t16YAt58<)YtZp~]]1$ > 10 121393 ``` ### Explanation The code is similar to that in [Martin Büttner's answer](https://codegolf.stackexchange.com/a/66410/36398). ``` 1 % number literal H % paste from clipboard H. Initial contents: 2 i: % vector of equally spaced values from 1 to input value " % for ` % do...while t % duplicate b % bubble up element in stack + % addition t % duplicate 16YA % convert integer to string representation in base 16 t % duplicate 58 % number literal: first ASCII code after '9' < % is less than? (element-wise) ) % reference () indexing with logical index from previous comparison Yt % convert string to number Zp % true for prime numbers ~ % logical 'not' ] % end ] % end 1$ % input specification for final implicit display function ``` [Answer] ## CJam, 28 bytes ``` TXri{{_@+_Gb{A<},Abmp!}g}*p; ``` [Test it here.](http://cjam.aditsu.net/#code=TXri%7B%7B_%40%2B_Gb%7BA%3C%7D%2CAbmp!%7Dg%7D*p%3B&input=19) ### Explanation ``` TX e# Push 0 and 1 to initialise Fibonacci computation. ri e# Read input and convert to integer N. { e# Run this block N times... { e# While the condition on top of the stack is truthy... _@+ e# Compute next Fibonacci number (dropping the second-to-last one). _Gb e# Duplicate and convert to base 16. {A<}, e# Keep only digits less than 10. Ab e# Convert from base 10. mp! e# Check that it's not a prime. }g }* p; e# Print the last number we found and discard the one before. ``` [Answer] # [Perl 6](http://perl6.org), 62 bytes My first pass of just get it to work was: ``` {(grep *[1].is-prime,map {$_,+[~] .base(16)~~m:g/\d/},(1,1,*+*...*))[$_-1;0]} # 77 ``` By combining the `grep` and the `map`, I can remove 10 bytes ``` {(map {$_ if is-prime [~] .base(16)~~m:g/\d/},(1,1,*+*...*))[$_-1]} # 67 ``` If I use `grep` instead of `map`, I save 5 more bytes: ``` {(grep {is-prime [~] .base(16)~~m:g/\d/},(1,1,*+*...*))[$_-1]} # 62 ``` usage: ``` # give it a name my &code = {...} say code $_ for 1..^20; 2 3 5 55 89 377 987 28657 75025 121393 317811 5702887 9227465 39088169 102334155 32951280099 4052739537881 806515533049393 7540113804746346429 ``` [Answer] # Pyth, 27 bytes ``` Leu,eGsGbU2ye.fq1lPs-.HyZGQ ``` [Demonstration](https://pyth.herokuapp.com/?code=Leu%2CeGsGbU2ye.fq1lPs-.HyZGQ&input=19&debug=0) `y` computes the nth Fibonacci number. A `.f` loop finds the fibohexaprime according to the input. [Answer] # Mathematica 111 bytes There may still be room for additional golfing. ``` t=Table[Fibonacci@k,{k,1600}];f@n_:=PrimeQ@FromDigits[Select[n~IntegerDigits~16,#<10&]]; g@k_:=Select[t,f][[k]] ``` --- ``` g[7] ``` > > 987 > > > --- ``` g[19] ``` > > 7540113804746346429 > > > [Answer] # Julia, 123 bytes ``` n->(a=[];i=1;while endof(a)<n b=([1 1;1 0]^i)[1];(s=filter(isdigit,hex(b)))>""&&isprime(parse(s))&&push!(a,b);i+=1end;a[n]) ``` This is an anonymous function that accepts an integer and returns an integer. To call it, give it a name, e.g. `f=n->...`. Ungolfed: ``` function f(n::Integer) # Initialize an array and an index a = [] i = 1 # Loop while we've generated fewer than n fibohexaprimes while endof(a) < n # Get the ith Fibonacci number b = ([1 1; 1 0]^i)[1] # Filter the hexadecimal representation to digits only s = filter(isdigit, hex(b)) # If there are digits to parse, parse them into an # integer, check primality, and push the Fibonacci # number if prime s > "" && isprime(parse(s)) && push!(a, b) # Next i += 1 end # Return the last generated return a[n] end ``` [Answer] # [GAP](http://www.gap-system.org/), 204 Bytes This answer is pretty unremarkable, except that GAP is cool enough to be able to find the next couple fibohexaprimes (and cooler still, it finds these in milliseconds with the given code). ``` gap>f(20); 31940434634990099905 gap> f(21); 12776523572924732586037033894655031898659556447352249 gap> f(22); 971183874599339129547649988289594072811608739584170445 gap> f(23); 1324695516964754142521850507284930515811378128425638237225 gap> f(24); 187341518601536966291015050946540312701895836604078191803255601777 ``` Note that f(24) is between 2^216 and 2^217. Here is the code: ``` f:=function(n)local c,i,x;c:=1;i:=0;while c<=n do x:=HexStringInt(Fibonacci(i));RemoveCharacters(x,"ABCDEFGHIJKLMNOPQRSTUVWXYZ");x:=Int(x);if IsPrime(x) then c:=c+1;fi;i:=i+1;od;Print(Fibonacci(i-1));end; ``` There's probably still some golfing that could be done. I think the implementation is pretty straightforward. Ungolfed: ``` f:=function(n) local counter,i,x; counter:=1;i:=0; while counter<=n do x:=HexStringInt(Fibonacci(i)); RemoveCharacters(x,"ABCDEFGHIJKLMNOPQRSTUVWXYZ"); x:=Int(x); if IsPrime(x) then counter:=counter+1; fi; i:=i+1; od; Print(Fibonacci(i-1)); end; ``` [Answer] ## C, ~~186~~ 183 bytes ``` #include<stddef.h> size_t a,b,c,d,m,x;size_t F(n){a=0,b=1;while(n){x=b;b+=a;a=x;c=0,m=1;while(x)d=x%16,m*=d<10?c+=m*d,10:1,x/=16;d=c>1;x=2;while(x<c)if(c%x++==0)d=0;d&&--n;}return a;} ``` The primality test is very inefficient, so the computation will struggle a bit for `n > 16` and become painfully long for `n = 19`. Nevertheless it works and gives the expected results. The code assumes that `size_t` is a 64bit type, which is true for both 64bit Linux and Windows. --- Bonus: unfortunately we are required to use 64bit types, which lead to an overhead of 33 bytes. The following version works for `n <= 15` using `int` and is 150 byte long: ``` a,b,c,d,m,x;F(n){a=0,b=1;while(n){x=b;b+=a;a=x;c=0,m=1;while(x)d=x%16,m*=d<10?c+=m*d,10:1,x/=16;d=c>1;x=2;while(x<c)if(c%x++==0)d=0;d&&--n;}return a;} ``` --- Test main: ``` #include <stdio.h> int main() { printf("Input - Output\n"); for (int i = 1; i < 20; ++i) { printf("%2d - %ld\n", i, F(i)); } } ``` [Answer] ## Python 2, 127 bytes ``` N=input();a,b=0,1 while N:a,b=b,a+b;t=int(''.join(c for c in hex(b)if ord(c)<65));N-=(t>1)*all(t%x for x in range(2,t)) print b ``` The algorithm could be a lot more efficient. In particular, the primality check `(t>1)*all(t%x for x in range(2,t))` checks potential factors all the way up to `t-1`, when really it would only have to check up to the [floor of the square root](https://stackoverflow.com/a/31224469/2554867). Since `range` stores an entire list in memory in Python 2 , this leads to a `MemoryError` at `N=17` (on my machine using default settings). [Answer] # Ruby, 160 bytes ``` ->i{t,o,k=[],[],0;f=->n{t[n]||=n<3?1:f[n-2]+f[n-1]};(r=('%x'%f[k]).scan(/\d/).join.to_i;(r>1&&(r==2||(2...r).none?{|j|r%j==0}))&&o<<r;k+=1)while !o[i-1];t[k-1]} ``` **Ungolfed:** ``` -> i { t, o, k = [], [], 0 f = -> n { t[n] ||= n < 3 ? 1 : f[n-2] + f[n-1] } while !o[i-1] do r=('%x'%f[k]).scan(/\d/).join.to_i o << r if (r > 1 && (r == 2 || (2...r).none?{|j| r%j == 0 })) k+=1 end t[k-1] } ``` **Usage:** ``` # Assign the anonymous function to a variable m = ->i{t,o,k=[],[],0;f=->n{t[n]||=n<3?1:f[n-2]+f[n-1]};(r=('%x'%f[k]).scan(/\d/).join.to_i;(r>1&&(r==2||(2...r).none?{|j|r%j==0}))&&o<<r;k+=1)while !o[i-1];t[k-1]} m[2] => 3 m[19] => 7540113804746346429 ``` [Answer] # R, 164 bytes ``` g=function(n){f=function(m)ifelse(m<3,1,f(m-1)+f(m-2));p=0;while(n){p=p+1;x=gsub("\\D","",sprintf("%x",f(p)));x[x==""]=1;y=1:x;if(sum(!tail(y,1)%%y)==2)n=n-1};f(p)} ``` Indented, with new lines: ``` g=function(n){ f = function(m)ifelse(m<3,1,f(m-1)+f(m-2)) #Fibonacci function p = 0 while(n){ p = p+1 x = gsub("\\D","",sprintf("%x",f(p))) #To Hex, and get rid of non-digits x[x==""] = 1 #If x is empty string y = 1:x #Converts to integer(!) and save the 1-to-x sequence to a variable if(sum(!tail(y,1)%%y)==2) n = n-1 #If prime, decrements counter } f(p) } ``` Examples: ``` > g(1) [1] 2 > g(5) [1] 89 > g(10) [1] 121393 > g(12) [1] 5702887 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` !föṗdf≤9B16İf ``` [Try it online!](https://tio.run/##yygtzv7/XzHt8LaHO6enpD3qXGLpZGh2ZEPa////DY0B "Husk – Try It Online") Using Husk here is just about cheating cause it has an infinite fibonacci sequence builtin. ## Explanation ``` !föṗdf≤9B16İf İf infinite list of fibonacci numbers fö filtered on the following four functions: B16 base 16 digits of the number f≤9 filter out the digits > 9 d interpret in base 10 ṗ is that prime? ! get element at input index ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` ÆḞb⁴<Ƈ⁵ḌẒµ#ṪÆḞ ``` [Try it online!](https://tio.run/##y0rNyan8//9w28Md85IeNW6xOdb@qHHrwx09D3dNOrRV@eHOVWCp//8NLQE "Jelly – Try It Online") Husk's infinite lists just beating me out. ## How it works ``` ÆḞb⁴<Ƈ⁵ḌẒµ#ṪÆḞ - Main link. Takes no arguments µ# - Read an integer n from STDIN and do the following for each integer, i = 0, 1, 2, ... until n return true and return the i's that return true: ÆḞ - The ith Fibonacci number... Ẓ - ...is prime when... b⁴ - ...converted to base-16,... < ⁵ - ...values less than 10... Ƈ - ...are removed... Ḍ - ...then is converted back to base-10 Ṫ - Take the last i ÆḞ - Return the ith Fibonacci number ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes ``` ÞF'Hkd↔⌊æ;i ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnkYnSGtk4oaU4oyKw6Y7aSIsIiIsIjYiXQ==) Infinite Fibonacci *and* hexadecimal conversion builtins go brr ``` ÞF # All fibonacci numbers ' ;i # Find the nth where... H # In hexadecimal kd↔ # Keeping only digits ⌊æ # Is it prime? ``` ]
[Question] [ If you visit Code Golf often, you may have heard of [Kolmogorov complexity](https://en.wikipedia.org/wiki/Kolmogorov_complexity). It's usually defined as the amount of bytes required to express some string in a programming language. Here the Kolmogorov-complexity of a natural number is defined similarly: the number of bytes required to represent it in a programming language. A number is Kolmogorov-simple if it's **more** space-efficient to represent it with the programming language, then with simply storing it in binary (base-256). In other words, if \$b\$ is the Kolmogorov-complexity of a number \$n\$, \$n\$ is Kolmogorov-simple iff \$b\lt\log\_{256}(n+1)\$. Every Turing-complete language has infinitely many Kolmogorov-simple numbers. Your task is to find the smallest Kolmogorov-simple number. In other words, output the smallest number \$n\$ in \$b\$ bytes, such that \$b<\log\_{256}(n+1)\$. ## Rules * If you express the number \$n\$, your program has to be at most \$\lceil \log\_{256}(n+1)\rceil-1\$ bytes long. * The number has to be a positive whole number * Use a **reasonable** IO format. These *may* include: printing to stdout, expressions, functions, storing the number to a variable, pushing the number to stack or taking a number as input and comparing it the represented number. Try to stick to the [convention](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422). Floating point numbers, complex numbers and fractions are allowed, as long as it's **exactly** an integer. * If you use a text-based format, your output should match this regex: `((\d+(\.\d*)?)|(\d*\.\d+))(e[+-]?\d+)?`. That is, it should be a decimal number. Trailing newlines etc. are allowed. Smallest number outputted (i.e. the value \$n\$) per language wins! [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 0 bytes, outputs `1` [Try it online!](https://tio.run/##K0otycxLNPwPBAA "Retina – Try It Online") Outputs `1`, and \$\log\_{256} 2 = 0.125 > 0\$ [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 byte, outputs `256` ``` ⁹ ``` [Try it online!](https://tio.run/##y0rNyan8//9R487//wE "Jelly – Try It Online") This outputs `256` in one byte, and \$\log\_{256} (257) \approx 1.0007 > 1\$ [Answer] # [R](https://www.r-project.org/) (& likely polyglot), 3 bytes, outputs 16777216 = 256\$^3\$ ``` 8^8 ``` [Try it online!](https://tio.run/##K/r/3yLO4v9/AA "R – Try It Online") [Answer] # [1+](https://codegolf.stackexchange.com/q/209529), 20 bytes, outputs \$2^{160}\$ *Reduced from \$2^{2^8}\$ due to @null* ``` 11+"*"*"+"*"*"*"*"*: ``` [Try it online!](https://tio.run/##jVVLb5tAEL7zKybkAMQYgxMlDQ2XHCr1YlVWeiIUrWFtUIGlu@smUdvf7s6CscEOao2F9vHNN@@hfpMZq64/1Hy3u4RMylr4s9kmF9LZ5DLbrpyElbMvhCfF2/SJvNJi5q6Se5re3SXz9e2auvSGJvd3t@m1N/fo9Y1LtLysGZcg3oS25qyEhBUFTWTOKgH7u5T@2FJNEzaIFIJ2a1o2/PqjaSldA6toXWyFKRAbwAK3lq8B/vI1VAy5uWz3@7OCVibqcwjf/LTgIoD58Vr9ap5X0tS/CrKhPugwgQ4duhHudAjXeUFBMlhRoK802UqaRro1YFEy9DWXpnc8z6saLWR1z4DQi2wwuHEEcfKCIIQ6nJLUHEg7ScEE3Z/RQqB9LRx9bM6aV1basLRhJaQNjzYs8D6MVLzsY/Bc/DfgNeOQILciGoQpgSAAwzSGwXmESQDe4Aj1OKRGp1JzYZ0zWGcM01OGZag4alabVqRSOLhEokd4AHfI0kvU53JFClIlNIUVJ8l3KsXFSTIGCZm/Y@SlAaRKURFuXB8j@I5Hi6PrjU0XQd@o/zPm1IjmtbAhKVXtYlI@Ecxqc/qSqSJboOuqYDE71lEZU3WER@Ei6vuiqh2Z/NP4KTg66Rk@iM4xzxpBTfoo0WZF9UC7GpO6ek/q6l9S@kAqnHrRGHLWIDmTRNJx25@f@7DpKO5bA6OvUukN90banbWjRjz0zXXVRefpw2GluhJGFV8ig@rHrOy0RiNIp6@LrISpygtHwFaaRrUtV5T72FvWaGjtvjzjaSebZATrUrbiONBGCXwkaIv6EB@kCnR9TOCj0oj1LWTKttJ54TnmIMl4Jz@qKUTBtgGe@JaOgE4HUTMqZdX1AVao5y@xHyKnJlzm6gtiGr@N8zmAlCiHcxetTUO1dCM1ddRqHp3BD1@XA/acUmV02e/FZjSPOBIdvD32em@8aIiM44qUNI4VXo/jkuRVHOstYWePtdt53kS/wqd9N4@/c5o8O@j/Xw) The fastest way to get big numbers in 1+ (of which I am its creator) is to repeatedly square. \$\lceil\log\_{256}(2^{160}+1)\rceil-1=20\$. [Answer] ## Batch, 38 bytes, outputs ≈2³⁰⁴ ``` @for /l %%a in (1,1,92)do @cmd/cset/a3 ``` `log₂₅₆(33...33) ≈ 38.004` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 24 bytes, outputs (1063-1)/3 ``` +[+++++>+<]++++[++++>.<] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fO1obBOy0bWJBNJhnp2cT@/8/AA "brainfuck – Try It Online") This creates 51, the ASCII value of `3`, as 255/5, and then outputs it 63=252/4 times. `+[+++++>+>+<<]>[->.<]` falls just short of working: in 21 bytes, it outputs `3` 51 times for ≈3.33×1050, while 25621≈3.74×1050. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `H`, 0 bytes ``` ``` The `H` flag pre-sets the stack to 100. $$log\_{256}\;101 = 0.83227643534397 > 0$$ [Try it Online!](https://lyxal.pythonanywhere.com?flags=H&code=&inputs=&header=&footer=) For a program without flags, you can use `₈` to output 256, similar to [caird coinheringaahing's Jelly answer.](https://codegolf.stackexchange.com/a/239759/45220) [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 3 bytes, outputs `16777216` ``` 8⋆8 ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=eCDihpAgOOKLhjgKeOKLiDI1NuKLhuKBvDEreA==) $$\log\_{256}\left(8^8+1\right) > \log\_{256}\left(8^8\right) = 3$$ [Answer] # [Husk](https://github.com/barbuz/Husk), 2 bytes, outputs 9! = 362880 = 256^2.3 ``` Π9 ``` [Try it online!](https://tio.run/##yygtzv7//9wCy///AQ "Husk – Try It Online") [Answer] # JavaScript (ES7), 8 bytes, `27368747340080914432` (displayed as `27368747340080914000`) ``` _=>7**23 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1s5cS8vI@H9yfl5xfk6qXk5@ukaahqbmfwA "JavaScript (Node.js) – Try It Online") The actual value of \$7^{23}\$ is \$27368747340080916343\$ but we get \$27368747340080914432\$ because of IEEE-754 loss of precision. We have \$\log\_{256}(27368747340080914432+1)\approx 8.07\$ [Answer] # x86-64 machine code, 7 bytes, outputs \$2^{56}\$ ``` 6A 01 58 48 0F C8 C3 ``` [Try it online!](https://tio.run/##TVDLasMwEDxbX7FVMEjNg/RBD0ndS8699FRocpBlyRbIkrFsImPy63XXfYRelh1mdmZY2TTrUsppEqEGBm@UkU1pfS4saKJ3SdOHCu5I0vgGWhFJkoez@F1b1RFOge@Jip1qHdADhbF3wZROFWC9K3@GcR1oxvcXQhbGSdsXCp5DVxi/qV4ImelaGMc4GTGpRawZTRfWxqOjq/kUM67E0b0KWRmnQPpC7ejMzRYRMtiuYEBYeBj/5JBu79/RZcgYu3aTlWhvueYfcbk8YTE4V8YqYAPcoEk8PPwPBJYayIdOBf7dJyJ5maZPqa0ow7Sunx5x4AMz1Cv7BQ "C++ (gcc) – Try It Online") Returns a value in RAX, as is standard. In assembly: ``` .global f f: push 1 # (2 bytes) Push 1 onto the stack. pop rax # (1 byte) Pop it out into RAX. bswap rax # (3 bytes) Reverse the order of the bytes in RAX. ret # (1 byte) Return. ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 3 bytes, outputs `100000000` ``` 8|A ``` [Run and debug it](https://staxlang.xyz/#c=8%7CA&i=&m=2) $$\left \lceil{\log\_{256}\left(10^8+1\right)}\right\rceil - 1= 3$$ [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 3 bytes, outputs `22222222`. ``` ×⁸2 ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCMkMze1WMNCR0HJSElT0/r///@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. `log₂₅₆(22222222) ≈ 3.05` Explanation: Charcoal only prints strings by default, so something like `φ` (`Print(f);`) prints 1000 `-`s instead of `1000`; casting to string costs a byte, meaning we now need a value of at least `65536`, however no predefined variable now holds a suitable value. This means we now need to look for a 3-byte answer that prints at least `16777216`, which can most easily be achieved in a number of ways by repeating the character `2`. [Answer] # [Python 2](https://docs.python.org/2/), 11 bytes, outputs `5704427701027032306735164424192` ``` print 9<<99 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EwdLGxtLy/38A "Python 2 – Try It Online") $$\log\_{256}(5704427701027032306735164424192+1)-1 = 11.77$$ [Answer] # [Python 3](https://docs.python.org/3/), 13 bytes, outputs `20282409603651670423947251286016` ``` print(16**26) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69Ew9BMS8vITPP/fwA "Python 3 – Try It Online") From what I can understand, this is the *absolute minimum* for a 13 byte program - it prints 256\*\*13, the minimum number that needs 13 bytes to store. Good luck getting anything below this in Python 3. Bonuses I found: ``` print(18**25) # 19% bigger than the actual answer ``` ``` print(27**22) # 52% bigger than the actual answer ``` ``` print(15**27) # 2.8x as big as the actual answer ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 5 bytes, outputs 2565 = 420 = `1099511627776` ``` 4 20? ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/30TByMD@/38A "GolfScript – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 12 bytes, outputs `79228162514264337593543950336` ``` print(4**48) ``` Inspired by [this](https://codegolf.stackexchange.com/a/242352/112488) answer. Explanation: ``` 4**48 == 16**24 == 256**12 ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69Ew0RLy8RC8/9/AA "Python 3 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/en/), 7 bytes, outputs `150094635296999121` ``` p 3**36 ``` Similar to other answers, uses `p` to debug print the number. Fortunately for numbers the debug print value is the same as the normal output would be. $$\left \lceil{\log\_{256}\left(3^{36}+1\right)}\right\rceil - 1= 7$$ [Answer] # [Excel](https://support.microsoft.com/en-us/excel), 5 bytes, outputs `1,09951E+21` ≈ 240 = 2565 ``` =2^40 ``` [Answer] # APL, 2 bytes ``` !9 ``` The program prints factorial of 9 = 362880. Validation of allowed length: ``` 1-⍨⌈256⍟1+!9 2 ``` ]
[Question] [ ## Background Given a triangle \$ABC\$, extend its three sides by the opposite side length, as shown in the figure below. Then the six points surprisingly lie on a circle called the [**Conway circle**](https://mathworld.wolfram.com/ConwayCircle.html), whose center coincides with the incenter (the center of [incircle](https://mathworld.wolfram.com/Incircle.html), the circle that is tangent to the three sides from the inside). [![enter image description here](https://i.stack.imgur.com/Ce0wV.gif)](https://i.stack.imgur.com/Ce0wV.gif) ## Task Given three side lengths \$a,b,c\$ of the triangle \$ABC\$, calculate the perimeter of the hexagon \$A\_b B\_a B\_c C\_b C\_a A\_c\$ (formed by the six points on the Conway circle). The answer must be within `1e-6` relative error from the expected. You can assume the side lengths form a valid non-degenerate triangle. The shortest code in bytes wins. ## Test cases ``` a b c ans --------------------- 1 1 1 9.000000 2 2 3 20.399495 3 4 5 35.293155 6 7 12 65.799785 2.3 4.5 6.7 31.449770 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~89 87 69~~ 68 bytes *Thanks @xnor for finding a shorter expression, saving 1 byte!* ``` f=lambda a,b,c,n=3:n and(a+b+c)*(c*c/a/b-a/b-b/a+2)**.5+f(b,c,a,n-1) ``` [Try it online!](https://tio.run/##NU3LboMwELz7K1Y52TwcwBjqqOmPVD2sDVaRiEHGlwjx7dSO0pVmV7Mzs7s@w@/ixHna@4wPPSBgoQtTuLu4OUA3UMx1blhGTWaueNVlgr5i3rAs4zK3NNmxcGXNzumxLj7A9twIsYuHeXIjTC4t@BaGyd0IvB@g2@AOD1ypnRcMxcvLt3WeAmUs2nyULX2ZEzWL96MJcYl6o76MefZZj2UXtdVPLlB72fEoYNepmQPKL9j9Ad/7O3r8XNhZA8A/QPHqVaSJJEGkWXGhVKskSayNkEmRvFGilpJ0kfXpQgx0kvdK9R@SNFxAyyV0vAdR87ZVfV/9AQ "Python 3 – Try It Online") A recursive function, takes in 3 sides of the triangle as input. Recursion is used to repeats the function 3 times, each time with the positions of `a,b,c` swapped in order to calculate each of the 3 summands in the formula below. ### How We can see that each side of the hexagon is the base of an isosceles triangle, whose vertex angle is an angle of the original triangle. For example: * \$C\_aC\_b\$ is the base of \$CC\_aC\_b\$ - an isosceles triangle with leg \$c\$ and vertex angle \$\widehat{C}\$. * \$A\_bB\_a\$ is the base of \$CA\_bB\_a\$ - an isosceles triangle with leg \$a+b\$ and vertex angle \$\widehat{C}\$. Given the leg \$l\$ and vertex angle \$\theta\$ of an isosleces triangle, the base is calculated as: $$l\sqrt{2-2\cos{\theta}}$$ Consider 2 opposites side of the hexagon, says \$C\_aC\_b\$ and \$A\_bB\_a\$. Since their corresponding triangles have the same vertex angle, their total length is: $$c\sqrt{2-2\cos{\widehat{C}}}+(a+b)\sqrt{2-2\cos{\widehat{C}}}$$$$=(a+b+c)\sqrt{2-2\cos{\widehat{C}}}$$ Then the perimeter of the hexagon is the sum of 3 opposite pairs: $$(a+b+c)\left(\sqrt{2-2\cos{\widehat{A}}}+\sqrt{2-2\cos{\widehat{B}}}+\sqrt{2-2\cos{\widehat{C}}}\right)$$ The cosine of an angle can be calculated from the sides of the triangle: $$2-2\cos{\widehat{C}}=\frac{c^2-(a-b)^2}{ab}$$ Thus, the final formula for the hexagon's perimeter is: $$(a+b+c)\left(\sqrt{\frac{a^2-(b-c)^2}{bc}}+\sqrt{\frac{b^2-(a-c)^2}{ac}}+\sqrt{\frac{c^2-(a-b)^2}{ab}}\right)$$ [Answer] # [Python 3](https://docs.python.org/3/), 64 bytes ``` lambda*t:eval("+((-(%s-%s)**2+%s**2)/%s/%s)**.5"*3%(t*5))*sum(t) ``` [Try it online!](https://tio.run/##NUzbaoQwEH3PVwyCkGQ1q8aYZun2R9o@RFepoFGStLCI324TaQfODOc269N/LYYfw/3jmPTcPjT1t/5HTzi5YJzj1OWpI5RWl9SFTa6pu54CEwnlKfZUEELd94w9OcZ5XawH93QIDYuFaTQ9jCYKzPnHaG4IQGdt1mXaOLjDrFc8TIv22Zllbp1GjwkJMRvsAZ/hSLvF2r7zQdStwzYPffJa9nkTvNWOxuMh2fSewdbG1e2Qv8Fmd3jf/qr7Z0KOEgD@AYoV56AqkAgeb8G4UrUSKLI6QERHsErxUgjUBCbjh1BoBJNKyReBKsahZgIaJoGXrK6VlMUv "Python 3 – Try It Online") Uses an adaptation of a formula [by Surculose Sputum](https://codegolf.stackexchange.com/a/203855/20260), written so that the variables `a,b,c` repeat in a cycle when the formula is read left to right. ``` +((-(a-b)**2+c**2)/a/b)**.5+((-(c-a)**2+b**2)/c/a)**.5+((-(b-c)**2+a**2)/b/c)**.5 ``` This lets us insert the input values into the formula as literals by string interpolation on the tuple `(a,b,c)` repeated 5 times, and then call `eval` to evaluate the resulting expression. --- # [Python 3](https://docs.python.org/3/), 76 bytes ``` lambda a,b,c:sum((2-(a*a+b*b+c*c-2*x*x)*x/a/b/c)**.5*(a+b+c)for x in[a,b,c]) ``` [Try it online!](https://tio.run/##NY3dboQgFITveYqTvQJU/EXLptsX2e4FsJqa@BegiRvjs1uwLclwMuebgeXlvuapPLrb5zHIUT0lyFjF@mq/R4yLBEsqI0VVpKlOCrrSldA1lalKNaGUcYo9jjTpZgMr9NP9bD/I0Y/LbBzYl0UowKGfWs/Dgln37Kcrgt@vYjlZuMEoF9wNs3TxmWV2GXqHCfEx43GHz3Cwejam1c4vpbLYJL5P3vM2qT1bTD853F02ucewqXDpHZIP2MwO9@2vuj8u5MgB4F8gWHYeVHgTVIaZsVKISnAUXOXFA@GsEGXOOaq9a8ILvlBz1gjRvHFUsBIqxqFmDZQ5qyrRNNkP "Python 3 – Try It Online") I took [Surculose Sputum's formula and solution](https://codegolf.stackexchange.com/a/203855/20260) and wrote the three summands in a closer-to-symmetric form like: $$(a+b+c)\sqrt{2-\frac{a^2+b^2-c^2}{ab}}$$ The idea is that we want the summand to be as symmetric in \$a,b,c\$ as possible so that we can iterate a single variable \$x\$ over \$a,b,c\$ to produce each summand. To this end, we write the core term $$\frac{a^2+b^2-c^2}{ab}$$ as the somewhat clunky $$\frac{a^2+b^2+c^2-2c^2}{abc}\cdot c$$ so that we can write it in this symmetric form: $$\frac{a^2+b^2+c^2-2x^2}{abc}\cdot x$$ Substituting \$x=a\$, \$x=b\$, and \$x=c\$ gives the three respective summands. Perhaps there's a better way to put this fraction into a near-symmetric form than doing so for the numerator and denominator individually. We can split it up as $$a/b+b/a-c^2/(ab)$$ but I don't see where to go from there. [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 68 bytes ``` 9k?scsbsa[lad*lblc-d*-lblc*/v]dsFxlalbsasblFxlalcsasclFx++lalblc++*p ``` [Try it online!](https://tio.run/##S0n@/98y2744uTipODE6JzFFKycpJ1k3RUsXRGvpl8WmFLtV5CTmAKWLk3LAzGQgMxnI1NYGiecka2trFfz/b6RnrGCiZ6pgpmcOAA "dc – Try It Online") [Or check out all the test cases.](https://tio.run/##NY1NCsJADIX3OcWjuOrQlo5aEURXdusBxMU0M1gxWun404V3rzOiBJIvLy9JY3w7srljfeu7Y28uWK2S7a5OxuV549k33uzF2FQa4cymWaxp8TxYXw9iJIx9I1/kgBxQqagLK5XexnCJiNtLZ/FQA34/6NWexKF3xkJOV0eA7UICHLcdkkkUE7xhGXnxX4qmqxtLhCANjSlNMcOcKixQatJ5aPM5qnxBHw) This is a direct implementation of [Surculose Sputum's answer (the original iterative one)](https://codegolf.stackexchange.com/a/203855/59825), which is the type of formula that dc ("desk calculator") can be pretty good for! **Explanation:** ``` 9k Set precision to 9 decimal places. ? Read input line (push a, b, and c on the stack). scsbsa Save the input numbers in registers a, b, and c. [ Start a macro. This macro takes the values in registers a, b, and c, and computes the first square root in the formula, leaving that result on the stack, as follows: lad* Push a^2. lblc- Push b-c. d* Replace b-c at the top of the stack with (b-c)^2. - Replace the top 2 items on the stack with a^2-(b-c)^2. lblc* Push b*c. / Divide to compute the formula under the radical sign. v Compute the square root. ] End of macro. dsFx Save macro for later use under the name F, and also run it now. lalbsasb Swap registers a and b. lFx Call macro F to compute the second square root. lalcsasc Swap registers a and c. lFx Call macro F to compute the third square root. ++ Add the three square roots. lalblc++ Compute a+b+c. * Multiply a+b+c by the sum of the square roots. p Print the result. ``` [Answer] # [Desmos](https://www.desmos.com/), 1455 bytes [![enter image description here](https://i.stack.imgur.com/SNgtbm.png)](https://i.stack.imgur.com/SNgtb.png) [Try it online!](https://www.desmos.com/calculator/8fi6eyddzx) Link is Desmos. Interactive! Click and drag triangle points. Obviously this answer is not going for shortest, I just wanted to show off an interactive demo. The bytes score was calculated by taking the length of concatenating all of the LaTeX from each formula in the calculator used to compute the perimeter (formulas used for interactive components were not counted). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes *Port of [Surculose Seputum's Python solution](https://codegolf.stackexchange.com/a/203855/6484)* ``` œεnÆy¦P/}ÌtO*O; ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6ORzW/MOt1UeWhagX3u4p8Rfy9/6//9oIx0FIDKOBQA "05AB1E – Try It Online") [Answer] # [Io](http://iolanguage.org/), 104 bytes Port of Surculose Sputum's answer. ``` f :=method(a,b,c,n,if(n!=0,(a+b+c)*(c*c/a/b-a/b-b/a+2)**.5+f(b,c,a,n-1),n)) g :=method(a,b,c,f(a,b,c,3)) ``` [Try it online!](https://tio.run/##XYxRCsIwEET/e4r6t5tMU5PaFoQeJokmFjQV6f1jCiJVlmXhzduZl5xDfZ4e1/W2XMjCwSNhDpQO0xFkpZOeBXnhW9u6ZlvXWmlYCNXLQJtvkRrNSMxV/O8Kn9sx50gaZbh@vua03lMVycCUaAc6nNDvwYAR2vz8qCKpHoMavzi/AQ "Io – Try It Online") [Answer] # Wolfram Mathematica, 99 bytes ``` (#1+#2+#3)(Sqrt[(#1^2-(#2-#3)^2)/#2/#3]+Sqrt[(#2^2-(#1-#3)^2)/#1/#3]+Sqrt[(#3^2-(#1-#2)^2)/#1/#2])& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X0PZUFvZSFvZWFMjuLCoJBrIjzPS1VA20gUKxRlp6isb6Ssbx2pDJY3AkoZwSUNkSWOYpBFc0ihWU@1/QFFmXomCQ3q0oQ4QxnLB@cZ6OiY6pkgCpno6hkY6hsax//8DAA) I am pretty sure that this code can be improved. But I wasn't able to wrap my head around it. So I just post this in the hope of learning something new from more experienced users. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~45~~ 44 bytes ``` +/×{+/{a b c←⍵⋄√(a×a÷b×c)+2-(⊢+÷)b÷c}⌽∘⍵¨⍳3} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X1v/8PRqbf3qRIUkheRHbRMe9W591N3yqGOWRuLh6YmHtycdnp6sqW2kq/Goa5H24e2aSYe3J9c@6tn7qGMGUOmhFY96NxvX/k8D6@x71NV8aL3xo7aJj/qmBgc5A8kQD8/g/2kKhiDIlaZgBITGQNpYwUTBFEibKZgrGBqBJPSAQnqmCmZ65gA "APL (Dyalog Extended) – Try It Online") Bubbler has a [27 byte solution](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfmvrX94erW2/qOOWUYah6frH97@qHfFo96tunqHp4NZS3QOrdDV1zR51LvF8FHPXqBULZe2PlgXkK0B1KcLVNm1@PB07cPbgQYAdQB5mka6@sha/kO0POpaRJSOrkX/0x61TXjU2/eoq/nQeuNHbRMf9U0NDnIGkiEensH/0xSMFUwUTAE) with a complete train, but I think it deserves it's own answer. This is a port of Surculose Suptum's formula, simplified by Kevin Cruijssen. -1 byte from dzaima. [Answer] # Java 8, 104 bytes ``` (a,b,c)->{double r=0,t,n=3;for(;n-->0;t=a,a=b,b=c,c=t)r+=(a+b+c)*Math.sqrt(c*c/a/b-a/b-b/a+2);return r;} ``` Iterative port of [*@SurculoseSputum*'s Python answer](https://codegolf.stackexchange.com/a/203855/52210), so make sure to upvote him! [Try it online.](https://tio.run/##fVFBbsIwELzzilVONtkYCAWkRuYHcOFY9bA2pg0FhzoLVYV4e@pAqsKlsrwer8bamfGWTpRt1x@N3VFdw4JKf@4BlJ5d2JB1sGyvAOvqaHYOrOgAYQfML7CyiMxLL5YleNCNIDRoZTY/d4ygh8jo9bjYVEEUPsvmw4I1IWmDRlu0mmVItaDUpFb2F8Tvqv4MLGzfDmhgsnabAaW5LILjY/AQiktTtDMPcURpoWbieJyqcg37aEasOJT@7eUVSN6csKtZjDCuq@CukWOO4/vGGJ9wct@Y4gxH@cMbFUlqglM1@/N@L@DK@iewm6DVd81ur6ojq0PUyjsfA0gwiSG01abJMySpd1/X3xFSeWW7bLuxl@YH) **Explanation:** ``` (a,b,c)->{ // Method with double as all three parameters and return-type double r=0, // Result-sum, starting at 0 t, // Temp-double n=3;for(;n-->0 // Loop 3 times: ; // After every iteration: t=a,a=b,b=c,c=t) // Rotate `a,b,c` to `b,c,a` respectively r+= // Increase the result-sum by: (a+b+c) // The sum of `a,b,c` *Math.sqrt( // Multiplied by the square-root of: c*c // `c` squared /a/b // Divided by both `a` and `b` -a/b // Minus `a` divided by `b` -b/a // as well as `b` divided by `a` +2); // Plus 2 return r;} // After the loop, return the result-sum ``` Or as a single formula: $$p = (a+b+c)\sqrt{c^2\div a\div b-\frac{a}{b}-\frac{b}{a}+2}$$ $$+(a+b+c)\sqrt{a^2\div b\div c-\frac{b}{c}-\frac{c}{b}+2}$$ $$+(a+b+c)\sqrt{b^2\div c\div a-\frac{c}{a}-\frac{a}{c}+2}$$ [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` I×ΣθΣEθ₂⁻²∕×ι⁻ΣXθ²⊗×ιιΠθ ``` [Try it online!](https://tio.run/##RY29DsIwDIRfJaMjhaXQiZGulSJgqzqEJBKW0pr8lcdPEwHCi093/s76qYIm5UqRAdcEFxUT3HGxEW55Ac8Fa3tUL/BV@qyCvRIlGHHNETrBBtzQ2C@Dgn2CBkl629CwjteagfLDWfM/RM6bLwOZrFN99ZtzKdN0FOwkWD/P5bC5HQ "Charcoal – Try It Online") Link is to verbose version of code. Port of @xnor's formula. Explanation: ``` Eθ Map over sides ΣXθ² Sum of sides squared ⁻ Subtract ×ιι Square of current side ⊗ Doubled ×ι Multiply by current side ∕ Πθ Divide by product of sides ⁻² Subtract from 2 ₂ Square root Σ Take the sum × Multiplied by Σθ Sum of sides I Cast to string for implicit print ``` Unfortunately `SquareRoot` doesn't seem to vectorise so I have to do that inside the `Map` which makes it marginally less efficient. [Answer] # JavaScript (ES7), 62 bytes Now a port of [Surculose Sputum's answer](https://codegolf.stackexchange.com/a/203855/58563). ``` f=(a,b,c,n)=>n^3&&(a+b+c)*(c*c/a/b-a/b-b/a+2)**.5+f(b,c,a,-~n) ``` [Try it online!](https://tio.run/##bc5NDoIwEAXgvaeYlWmhTKE/1C5w6TFMSgWDMa1RYlx5dbS4Ep1k3mq@vDm5u7v563AZixAP3TT1DXGsZZ4F2mzDXq7XxOVt7mlGfOa5422RtuUuFzTLUOc9SeeOFc9AJx/DLZ47PMcj6UnFAOATABTHuBse3YHUlALnABbLeVbfSiQwh/yjRInSWmX1QskEVAr9R0mNwspKL1WdgJk/FL@q1misNZulEvhuU6gZ1Gh@uypUyhpTTi8 "JavaScript (Node.js) – Try It Online") ]
[Question] [ Let's define the a function on natural numbers \$n\$, written as base 10 digits \$d\_k\; d\_{k-1}\; \dotsc\; d\_1\; d\_0\$, as follows: As long as there are equal adjacent digits \$d\_i\;d\_{i-1}\$, replace them by their sum \$d\_i+d\_{i-1}\$ from left to right. If there were any such digits, repeat the same procedure. In other words, in each iteration we greedily take all pairs of equal adjacent digits and replace them by their sum at the same time (using the left-most pair if they overlap). ## Example Let's take \$\texttt{9988}\$ for example: 1. The first adjacent digits which are equal are the two \$\texttt{9}\$ 2. So we replace them by \$\texttt{9 + 9} = \texttt{18}\$ which gives us \$\texttt{1888}\$ 3. Since we're still in the first left-right traversal and there were still two \$\texttt{8}\$s we need to first replace these 4. So we get \$\texttt{1816}\$ 5. Something changed, so we need to do another iteration 6. But there are no such digits, so we stop Therefore the \$9988^\text{th}\$ number in that sequence is \$1816\$. ## Challenge The first 200 terms are: ``` 0,1,2,3,4,5,6,7,8,9,10,2,12,13,14,15,16,17,18,19,20,21,4,23,24,25,26,27,28,29,30,31,32,6,34,35,36,37,38,39,40,41,42,43,8,45,46,47,48,49,50,51,52,53,54,10,56,57,58,59,60,61,62,63,64,65,12,67,68,69,70,71,72,73,74,75,76,14,78,79,80,81,82,83,84,85,86,87,16,89,90,91,92,93,94,95,96,97,98,18,10,101,102,103,104,105,106,107,108,109,20,21,4,23,24,25,26,27,28,29,120,121,14,123,124,125,126,127,128,129,130,131,132,16,134,135,136,137,138,139,140,141,142,143,18,145,146,147,148,149,150,151,152,153,154,20,156,157,158,159,160,161,162,163,164,165,4,167,168,169,170,171,172,173,174,175,176,24,178,179,180,181,182,183,184,185,186,187,26,189,190,191,192,193,194,195,196,197,198,28 ``` Your task is to generate that sequence, either * given \$n\$, return the \$n^\text{th}\$ number in that sequence, * given \$n\$, return the first \$n\$ numbers in that sequence * or generate the sequence indefinitely. You may choose your submission to use either \$0\$- or \$1\$-indexing, but please specify which. ## Test cases You may use the above given terms, however here are some larger ones: ``` 222 -> 42 1633 -> 4 4488 -> 816 15519 -> 2019 19988 -> 2816 99999 -> 18189 119988 -> 21816 100001 -> 101 999999 -> 181818 ``` [Answer] # [Python 3](https://docs.python.org/3/), 128 bytes ``` def t(z):j=z and(z[0]==z[1:2])+1;return[str(int(z[0])*j),*t(z[j:])]if j else'' def c(n):r="".join(t(n));return r!=n and c(r)or r ``` [Try it online!](https://tio.run/##lZPdTtwwFITv9ylcekFCB@Txv7favgjaC1RC2VUbUEildhHPTscs/6pUNdpNHHvO8fE3Ode/58ur0d/fnw8XZu52/XK72pmz8bzbndr1arU75dKt@0/8PA3zz2k8vZmnbjPOD8v90bbHURtvl@t@vbkwWzN8vxkODxct3ddu7JfT6uDgZHu1GbtZr/1jGjN9WI1tG4mm/moy0/3io7HHrHUxDzfzcG5WZjobvw2dhXHW9ovh1/Xwdb9wakE4eAREJGQUVNBqivp5MIARTGAGC1jhtEjJnYfTPcIluAxX4Cq8hSe8Uyof4CO8Bhm@wFcszKsrWASlcQhee4aIkBAygsYV0SIS0SF6xNDqiQkxIxbEimSRiKRNPFJAiq3WlJEKUkW2yER2yB45IEfk1I6RC/K7GopFIYpDUQ0BJaIklNyOWyqqRSWqQ/WoATWiJtSMWh5ICJyl/sJkxcm2MlWJ1WZWKWyT/IPWm2IoKaVtxKWma892NCVUBBVCxVCIKcYU5GaLMFOc6dtYMqGmWFN8GVo2yYS4VSzIDI2FZKG9SybSFGqKNQWbot3qEG6KNwWc8X2h4k8ZwNQqUIw8oExo98ZOIbKB8oEygnKCsoLygjKDcqMdTXZQflAeUCZQLrC0OrUmIygnKCva6eUFZQblBmUH5QdlCOUIZQnlCWWKK@vFhb7/Eeb5A9@MZre57vZ98DLfLx9OdD219ju4vTPHX8zt3cGJwn@cqbmgXmrdqS7r@4Xa6Wq@HKabxf7R2uYhvnPOwQTX7wF1ouH1/vQaQikwhel5PUY1kHqQ9Xmq1iZyr1S1XTCiUl5kTzq@Tmd1UUrLN7GPwSya/SuS/TH@i8H9Hw "Python 3 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~97~~ ~~96~~ 93 bytes ``` def f(n):r=re.sub(r'(.)\1',lambda m:`int(m.group(1))*2`,n);return r!=n and f(r)or r import re ``` [Try it online!](https://tio.run/##XYxBbsIwEEX3PsVUXcRThchjCrKD6Em6ICgOWGqcaHAWnD4YpOLA7Oa///54jech6HluXQedDFjznl11mY6SC1nhLxXlX9Mf2wb6@uBDlH114mEaJSF@6UMZcMcuThyAP/YBmtCmGcaBgYXvx4EjsJu79HvwqdSEk5NaKawFjJwGU/0SWXrEUjwCIf7zQmtdIHwCrH7gW@ectut1Bot8syH7BFqRXTBrjcnM0DYze78nI0NmKb6Z9KKSSkfZVfQ2@7pLZr4B "Python 2 – Try It Online") --- Non regex version: # [Python 2](https://docs.python.org/2/), ~~133~~ ~~130~~ ~~122~~ ~~112~~ 98 bytes ``` def f(n): r='';s=n while s:a=1+(s[0]==s[1:2]);r+=`int(s[0])*a`;s=s[a:] return r!=n and f(r)or r ``` [Try it online!](https://tio.run/##XY3LCsIwEEX3@YoRF218QCZqSSrxR0rBgK0NSCyTivj1NQqa6ixmcc@cO/1j6K5ejuOpaaHNPS8ZkMmyfTCewb1zlwZCaQ0u81CJ2phQYSlrvqelOTo/vFO@sMcohMqWddSb4UYeaGY8WH@KrcSvBDS2cTtwEVl/bnIpxOtbT7EmHoWBcsf5ir0Dxj55JqXMOMwB1gfYypRjsdkkMMl3O9RfIAXqCdNaqcQUFonp13wZKlRT8c/EHxVFHEyuwL/a315U4xM "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` DŒg+2/€FVµ¡ ``` This is an unnecessarily slow, full program. [Try it online!](https://tio.run/##y0rNyan8/9/l6KR0bSP9R01r3MIObT208P///4ampoaWAA "Jelly – Try It Online") ### Alternate version, 12 bytes ``` DŒg+2/€FVµƬṪ ``` One byte longer, but much faster. Works as a program or a function. [Try it online!](https://tio.run/##y0rNyan8/9/l6KR0bSP9R01r3MIObT225uHOVf@P7lE43A4UUXD//9/IyEhHwdDM2FhHwcTEwgLINjU1tARSlpYgniUIAHlQrqEBEBhChS0B "Jelly – Try It Online") ### How it works ``` DŒg+2/€FVµƬṪ Main link. Argument: n (integer) µ Combine the previous links into a chain. Begin a new one. D Decimal; yield n's digit array in base 10. Œg Group adjacent, identical digits into subarrays. +2/€ Map non-overlapping, pairwise sum over the subarrays. If there is an odd number of digits in a subarray, the last digit will remain untouched. F Flatten; dump all sums and digits into a single array. V Eval; turn the result into an integer. Ƭ Execute the chain 'til the results are no longer unique. Return all unique results. Ṫ Tail; extract the last result. ``` The 11-byte version does the same, except it calls the link **n** times for input **n**, instead of calling it until a fixed point is reached. [Answer] ## Haskell, 70 bytes ``` until((==)=<<f)f f(a:b:c)|a==b=show(2*read[a])++f c|1<2=a:f(b:c) f a=a ``` Input is taken as a string. [Try it online!](https://tio.run/##NYrLDoIwFET3fMUNq1bU2AqGEu4f6MqlGnNFCsSCDY@48dut1MTZnJyZqWl4lMa4Cs9u6sbGMIbIMc8114FmlN2ygr8J8YZD/XwxuehLup/owqNIQ/EWuUTKNPO3QAMhuZaaDhBasocrMDuNx7Hfd7CGigOcQilluAzFbrudEcdp6i1JhPJU6ufKx/u/EJs54r@o8OI@hTZUDW5VWPsF "Haskell – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 16 bytes ``` +`(.)\1 $.(2*$1* ``` [Try it online!](https://tio.run/##K0otycxLNPz/XztBQ08zxpBLRU/DSEvFUOv/fyMjIy5DM2NjLhMTCwsuQ1NTQ0suQ0tLINsSBLgMIRxDAyAwhIhZAgA "Retina – Try It Online") Link includes test cases. Explanation: ``` +` ``` Repeat until the input stops changing. ``` (.)\1 ``` Replace pairs of adjacent digits... ``` $.(2*$1* ``` ... with twice the digit. (`$1*` generates a string of `$1` `_`s, `2*` duplicates that, and `$.(` takes the length. Actually, the Retina engine is cleverer than that and just doubles `$1`.) [Answer] # JavaScript, ~~48~~ ~~47~~ 46 bytes Input and output as strings. Returns the `nth` term of the sequence. ``` f=s=>s-(s=s.replace(/(.)\1/g,x=>x/5.5))?f(s):s ``` [Try it online](https://tio.run/##XZBRa4MwFIXf/RXiU8I0elMtyUBHGQ72sJfq2xyLOC0tLooZw/16l9S2WM/b/XLOPdycyt9SVcOx//Fk91VPUxOrOFEeUrEiQ923ZVUjHxFcgH9wxzgZ/YhEGD81SOFHNVWdVF1bk7Y7IOHdq5Avr/sst2kQ2Hm6f8sKuXIIbC0XvBNCdsNQ/iEdwR/ku@wR@nRHHCcNGh@EwJicuqMUrr1KiuXqQuaprn3eZeld5brNciiljmtr@b4dUsuB7WZzBma2nDBk7Doy2Or3KAJuiAY0AK4J57PHkLOHG10IMGDGdHUZE8ybAi2YEQRwiXHnFgNmzR/QLG6e/gE) * 1 byte saved thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) * 1 byte saved thanks to tsh [Answer] # [Perl 6](http://perl6.org/), 37 bytes ``` {($_,{S:g[(\d)$0]=2*$0}...*==*)[*-1]} ``` [Try it online!](https://tio.run/##JYhNCsIwFAav8lEe0gYb8tIfGjW9hMtagqBxY6nUVQk5e6x0VjPzeS7vNk0rDh42hZzcMVxPryG/PQpSo9WCVJRSCmtFMYiSx5i@9xUZOZQ9gge5mMHPCy5aa3BbVajrrgM3DRuwMZubP@A9WG3w/kx/Tj8 "Perl 6 – Try It Online") This is a function which generates the nth term of the sequence, given n as its argument. `($_, { ... } ... * == *)` is the sequence of successive changes to the input number, generated by the bracketed expression (a simple regex substitution) and stopping when `* == *`, that is, when the last two numbers in the sequence are equal. Then the `[*-1]` takes just the final element of that sequence as the return value. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~231~~, ~~203~~, ~~200~~, ~~196~~, 192 bytes EDIT: Function is now at 185 bytes plus 18 for `using System.Linq;` Thanks to BMO (for 1>0 being equal to true plus newline removal) and Mr. XCoder (for f=!f statements)! EDIT2: Down to 182 bytes plus 18 for `using System.Linq` thanks to dana for sharing a few golf tips! EDIT3: Thanks to Embodiment of Ignorance for the int[] -> var, removal of short circuit && -> &, and changing up ToArray -> ToList! (178 bytes + 18 using) EDIT4: Embodiment of Ignorance dropped 4 bytes by changing an assignment. Dummy me shoulda counted! Thanks again :D ``` p=>{var f=1>0;while(f){var t=p.Select(n=>n-48).ToList();p="";f=!f;for(var j=0;j<t.Count;j++){if(j<t.Count-1&t[j]==t[1+j]){p+=t[j]+t[++j];f=!f;continue;}p+=t[j];}};return p;}; ``` [Try it online!](https://tio.run/##TZAxa8MwFIR3/wrVQ5FQbWLo4PAiL4FOKRRS6OBmsFUplXEkV3pOKca/3bWbEMobjvvuccPJkEjn1dQHY49k/xNQnSD679KdsV8QybYKgbx4d/TVaYgI6fq6NZIErHCWszMf5LkylrIlJOSpt3IT0M9FDxcpSE3E1IliOFeeaJEVK/j@NK2imv0hFF26V62SSK0obPKYs/TV7UxAyqATcQxa3GnQztPlvREraDaYbl1vERrO2WA0vZEku8eyOQiBZcabAxs6LhbAseSzv3RJZ9HYXsF4TWEcwSvsvSUdjDBdN9g6G1yr0jdvUNGaxut1nseMx@82ZhCN802/ "C# (.NET Core) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, 21 bytes ``` s/(.)\1/$1*2/ge&&redo ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX0NPM8ZQX8VQy0g/PVVNrSg1Jf//f0sQ@JdfUJKZn1f8X7cAAA "Perl 5 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-h`](https://codegolf.meta.stackexchange.com/a/14339/58974), ~~15~~ 14 bytes Returns the `nth` term of the sequence. ``` Æ=s_r/(.)\1/ÏÑ ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=xj1zX3IvKC4pXDEvz9E=&input=OTk4OAotaA==) This should work for 10 bytes but there seems to be a bug in Japt's recursive replacement method. ``` e/(.)\1/ÏÑ ``` [Answer] # [Groovy](http://groovy-lang.org/), 63 bytes ``` {s->r=/(\d)\1/ while(s=~r)s=s.replaceAll(r){(it[1]as int)*2} s} ``` [Try it online!](https://tio.run/##Sy/Kzy@r/J9m@7@6WNeuyFZfIyZFM8ZQn6s8IzMnVaPYtq5Is9i2WK8otSAnMTnVMSdHo0izWiOzJNowNrFYITOvRFPLqJaruPZ/QRGQk5OnkaahZGRkpKSpyYUkYmhmbIwmZGJiYYGuytTU0BJdzNISQ50lCKCrw6bQ0AAIDLHpBmn/DwA "Groovy – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Δγε2ôSO}˜J ``` [Try it online](https://tio.run/##yy9OTMpM/f//3JRzm89tNTq85VHTmmD/2tNzvP7/N7QEAQsLSwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1PObT631ejwlkdNa4L9a0/P8fpfq/M/2sjISMfQzNhYx8TEwkLH0hJIGJqaGlrqGILZliCgYwjhGBoAgSFEDKzAEiRsGQsA). **Explanation:** ``` Δ # Continue until the (implicit) input no longer changes: γ # Split the integer in chunks of the same adjacent digits # i.e. 199999889 → [1,99999,88,9] ε } # Map each to: 2ô # Split it into parts of size 2 # i.e. 99999 → [99,99,9] €S # Split each part into digits # i.e. [99,99,9] → [[9,9],[9,9],[9]] O # And take the sum of each part # i.e. [[9,9],[9,9],[9]] → [18,18,9] ˜ # Flatten the list # i.e. [[1],[18,18,9],[16],[9]] → [1,18,18,9,16,9] J # Join everything together # i.e. [1,18,18,9,16,9] → 118189169 # (And output the result implicitly at the end) # i.e. output = 28189169 ``` [Answer] # Wolfram Language 108 bytes ``` ToExpression[""<>ToString/@Total/@Flatten[Partition[#,UpTo@2]&/@Split@IntegerDigits@#,1]]&~FixedPoint~#& ``` ## Explanation `IntegerDigits` transforms the input number into a list of its digits. `Split` groups consecutive repeated digits. `Partition[#, UpTo@2]&/@` breaks runs of like digits into lists of, at most, lengths of 2. `Flatten[...,1]` eliminates occasional overly-nested braces--e.g., {{2,2}} becomes {2,2} `Total/@` sums totals of paired digits. Isolated digits need not be summed. `ToString` converts the totals (and isolated digits) to strings. `""<>` joins all the strings in the list. `ToExpression` converts the outcome to an integer. `...~FixedPoint~#&` applies the function until the result ceases to change. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc) with flag `/u:System.Text.RegularExpressions.Regex`, 70 bytes ``` s=>{for(;s[0]!=(s[0]=Replace(s[0],@"(.)\1",m=>m.Value[0]*2-96+"")););} ``` Outputs by modifying the input. Takes in a list containing one string for input. Thanks to @dana for golfing an entire 23 bytes! [Try it online!](https://tio.run/##TZBNT4QwEIbv/IraE1UWF/Yji2yJHrztaTV6WPdAyLA24SudohjCX7e2CybMZd4@eTt9pxkuMhT6KVOirvYHgWqPSorqkiQ518iTPq@lG@Npeb7hrm38CE2RZnA9eI/U9dlHQL2SJ6X/lhYtGHwbLqLtHaWMxSwedOyMM09nogAVEk56hxAahiH1rAi2q9Wo1uvdbmKbTRBNMor@aWRrojMcLE0FM4v1DLFjwkOafbpfqbw@TUQ1RmA2gaXIK/gm88V7azB3Se4iM@1dCgUHUY0bGzLo37qx/4X6vn14@UEFpf8KnfKPcGmLVD53jQRE67AIuj8 "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 118 bytes ``` import StdEnv,Data.List $[a,b:t]|a==b=[1,(a*2)rem 10]%(1-a/5,1)++ $t=[a: $[b:t]] $l=l ``` # ``` limit o iterate$o map digitToInt ``` [Try it online!](https://tio.run/##PY7NCoJAFEb3PsVdTKSllUKbYHa2EFwEtRtc3HSUC/MjeguCnr2pCFp@cA7na41GF6zvbkaDRXKB7OgnhjN3R3dPS2Tc1DRzJBSm1wM3T5TyKlWexrgqkklbyHfNIs4z3O7TPFmvQbBUeAChvngTCSNN6G@uZfIOJBiyxOCBWE/IWvhPd4SOBuKLrxxHZ8bPAQl/Ry2Lolg24dX2Boc5ZFUdyodDS@1vnAxy7yf7Bg "Clean – Try It Online") Takes the first repeated value (`limit`) from the infinite list of applications (`iterate`) of a lambda performing a single step of the collapsing process. Input taken as a `[Char]`. [Answer] # [Red](http://www.red-lang.org), ~~84~~ ~~83~~ 80 bytes ``` func[n][if parse s: form n[to some change[copy d skip d](2 * do d)to end][f s]s] ``` [Try it online!](https://tio.run/##VYqxDsIgFEX3fsUd1Uloa0o/w5UwNDxQYvogUAe/HuugtWe6J@dmR/XqSJvGj9U/2Wo2OnikKReHMsLHPIP1ElHi7GDvE9@ctjG9QCiPkEDmIHECRdBxvTkmoz2KKaamHHiBh5Sy@W5xadufdN0wbKXvhdpMqb@mPmxtH8V5Rey/qr4B "Red – Try It Online") Returns the `nth` term of the sequence. ## Explanation: ``` Red[] f: func [ n ] [ if parse s: form n [ ; parse the input converted to a string to some change [ ; find and change one or more copy d skip ; digit (in fact any character, no predefined character classes) d ; followed by itself ] (2 * do d) ; with its doubled numeric value to end ; go to the end of the string ] [ f s ] ; call the function with the altered string if parse returned true s ; finally return the string ] ``` [Answer] # [Scala](http://www.scala-lang.org/), 84 bytes ``` s=>{var t=s while(t!=(t="(\\d)\\1".r.replaceAllIn(t,m=>s"$m"(0)*2-96+""),t)._2){} t} ``` [Try it online!](https://tio.run/##bYw7C8IwGEX3/ooYHBKtxcRajBDBRXBwcrQisaZaibE0nw8o/e31tUj1LhcO516XKKPq8/aoE0ALlVmk76DtzqFpnqPSu6oCpWM0u9gEsrNlqyUUmd376NNrWTs5KV8WSOfdDpnRBFqSgMQkjnc0jhkOiqDQuVGJnhoztwT8k5w43D5h0qcd3hNRF2PqAw02nJaVB1WdP8/BWJISzDnHlHpfhEWDQQOF4WjUtIZDJppMiB9PvNL0/oms/wz7t37Pq/oB "Scala – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 111 bytes ``` s=>{var t=s;do{s=t;t="";for(int i=0;i<s.Length;)t+=s[i]%48*(s[i++]!=(s+0)[i]?1:2*++i/i);}while(t!=s);return t;} ``` [Try it online!](https://tio.run/##RU7BbsIwDL33K0y1SQnJWBMKSglht52474A4lC5ApClMjRmTqn57l1Jgvvg9v@dnV@GlCq57P/tqGbB2/sCHtoI9mC6YVfNT1oAm6M9TEwxqNGmq96eaOI/gTKbdMkzW1h/wqCkyEzZu@5yrMYmAse3IkMAyGodvYiHHjLlXR3V7ObovS3BkAtW1xXPtAXXb6SSJ0basjuSaX3Lo244C2hDPefD2stk2CRApJYdcUh6xmE@nkVxxnivFQYn5oMxmouAgM1EMvCh6Wd71oi8OQgl1M9wd4hGRxRLRk4n/lduOUHHU0gTgo3Zo185b8pQ6v4Cmf3hSthzs7/ed7iItK4x0TwadpSltU6q7Pw "C# (Visual C# Interactive Compiler) – Try It Online") HUGE credit to @ASCIIOnly for golfing ~30 ;) At first we were both posting updates simultaneously, but at some point he clearly went to town! -2 thanks to @EmbodimentOfIgnorance! Less golfed code... ``` // s is the input as a string s=>{ // t is another string used // to hold intermediate results var t=s; // the algorithm repeatedly // processes s and saves the // result to t do{ // copy the last result to s // and blank out t s=t; t=""; // iterate over s for(int i=0;i<s.Length;) // append either 1 or 2 times // the current digit to t t+=s[i]%48* // compare the current digit // to the next digit. to prevent // an out-of-bounds exception, // append a 0 to s which either // gets ignored or collapses // to 0 (s[i++]!=(s+0)[i] // if they are different, then // the multiplier is 1 ?1 // if they are the same, then // the multiplier is 2, and we // have to increment i :2*++i/i); } // continue this until the input // and output are the same while(t!=s); return t; } ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 15 bytes ``` →U¡ödṁoṁodΣC2gd ``` [Try it online!](https://tio.run/##yygtzv7//1HbpNBDCw9vS3m4szEfhFPOLXY2Sk/5//@/oaGlpYUFAA "Husk – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, ~~39~~ 34 bytes -5 bytes thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan) ``` $_.gsub!(/(.)\1/){$1.to_i*2}&&redo ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6BUuyCpaUlaboWN5VU4vXSi0uTFDX0NfQ0Ywz1NatVDPVK8uMztYxq1dSKUlPyISoXwChDU1NDSwgHAA) ]
[Question] [ > > Version 2 [here](https://codegolf.stackexchange.com/q/131845/70347). > > > Simple challenge: given an integer, draw a house of cards with the given number of stories. If the number is negative, draw the house upside-down. Examples: ``` Input: 2 Output: /\ -- /\/\ Input: 5 Output: /\ -- /\/\ ---- /\/\/\ ------ /\/\/\/\ -------- /\/\/\/\/\ Input: 0 Output: <empty, whitespace or newline> Input: -3 Output: \/\/\/ ---- \/\/ -- \/ ``` Input can be numeric or a string. Output must be exactly as shown, with leading and/or trailing spaces and newlines allowed. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest program/function for each language win! [Answer] # [Python 2](https://docs.python.org/2/), ~~97~~ ~~95~~ ~~94~~ 92 bytes -2 bytes thanks to Luka This version produces an exception on `n=0`,but without printing anything ``` n=input()*2 m=abs(n) for i in range(2,m+1)[::n/m]:print(i/2*'/-\-'[i%2::2][::n/m]).center(m) ``` [Try it online!](https://tio.run/##LckxDsIwDAXQvafIgmoXQoTFZKknaTsUFMBDfqM0DJw@XXjry7/62SCtYTTkbyUepEvj@tgJ3L224swZXFnxjiSXdL7xpIqQFs3FUMmCDH3ws@8nO4mqLP/n6zOixkKJW/P3Aw "Python 2 – Try It Online") ### Non-error version, Python 2, 94 bytes ``` n=input()*2 x=n>0 or-1 for i in range(2,x*n+1)[::x]:print(i/2*'/-\-'[i%2::2][::x]).center(n*x) ``` [Try it online!](https://tio.run/##HclBDoIwEAXQPafoxtBWKzJhNQleBFgYUnQ2v82kJvX0NeFtX/6VTwK1hlmQv8U6T12d8XyYpGHsjqRGjMDoC@9o6VY9rqNbmOvGWQXFykC@H8Ia@kUuxEzbue6@R5SoFr661sL0Bw "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~30~~ ~~29~~ 24 bytes ``` ÄF„--Nׄ/\N>×}).C∊2ä¹0‹è ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cIvbo4Z5urp@h6cDaf0YP7vD02s19ZwfdXQZHV5yaKfBo4adh1f8/69rCgA "05AB1E – Try It Online") **Explanation** ``` ÄF # for N in [0 ... abs(input-1)] do: „--N× # push the string "--" repeated N times „/\N>× # push the string "/\" repeated N+1 times } # end loop ) # wrap stack in a list .C # pad strings on both sides to equal length ∊ # vertically mirror the resulting string 2ä # split in 2 parts ¹0‹ # push input < 0 è # index into the the list with the result of the comparison ``` [Answer] # [PHP](https://php.net/), 125 bytes input negative leading newline input positive trailing newline ``` for($s=str_pad;++$i<$b=2*abs($argn);)$t.=$s($s("",2*ceil($i/2),["-","/\\"][1&$i]),$b," ",2)." ";echo$argn>0?$t:$t=strrev($t); ``` [Try it online!](https://tio.run/##HY3RCoIwFEDf/Yq4XGJXl9Z6ay4/RCWmzTaIHNvo95f5eOBwjrc@t523vkAdXh8FV5B5WQPDqGIKD6@fsqrQtTgpUeopst0jSZhqhRtGBsBFORv3ZugaQbyHE3BohgHG/nJENxLHicNh06iGAqSZ7bpn7ucO0w3TfxXMl2EimfMP "PHP – Try It Online") # [PHP](https://php.net/), 130 bytes ``` for(;++$i<$b=2*abs($a=$argn);)echo($s=str_pad)($s("",2*abs(($a<0?$a:$i&1)+($i/2^0)),["-",["/\\","\/"][0>$a]][1&$i]),$b," ",2)." "; ``` [Try it online!](https://tio.run/##Jc5BDsIgFATQfU9hfn4avkWhTdxIsQdp0YBVYWMJeH8kupnM4mUy0ccyTtHHBm16vTWcQJXnlpjqOgwjOj3srcsMrf4BUvS4@41h1vmTbtGuVDsD4H9X4SgntGcMbU8dwyCGqyTiMxyghlgW4LAIMLO8oDVm7lsMhjg6Dru6Qkdo6oXyBQ "PHP – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 39 bytes ``` |:"G|@-:~'/\'G0<?P]@E:)htg45*c]xXhG0<?P ``` [**Try it online!**](https://tio.run/##y00syfn/v8ZKyb3GQdeqTl0/Rt3dwMY@INbB1UozoyTdxFQrObYiIgMs@P@/rikA "MATL – Try It Online") ### Explanation ``` | % Implicitly input, N. Absolute value :" % For k from 1 to that G| % Push absolute value of N again @- % Subtract k : % Range [1 2 ... N-k] ~ % Convert to vector of N-k zeros '/\' % Push this string G0< % Is input negative? ? % If so P % Reverse that string (gives '\/') ] % End @E % Push 2*k : % Range [1 2 ... 2*k] ) % Index (modularly) into the string: gives '/\/\...' or '\/\/...' h % Horizontally concatenate the vector of zeros and the string. Zeros % are implicitly converted to char, and will be shown as spaces t % Duplicate g % Convert to logical: zeros remain as 0, nonzeros become 1 45*c % Multiply by 45 (ASCII for '=') and convert to char ] % End x % Delete (unwanted last string containing '=') Xh % Concatenate into a cell array G0< % Is input negative? ? % If so P % Reverse that cell array % Implicit end. Implicit display ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 169 ~~171~~ ~~173~~ ~~160~~ ~~164~~ bytes ``` #define F(A,B,C)for(i=A;B--;)printf(C); #define P puts("");F(y,i," ")F(abs(n)-y s,i,x,y;f(n){x=n<0;for(s=x?1-n:n;s--;){y=x?-n-s:s;P,i,x?"\\/":"/\\")y+=x;P,s>x&&i,"--")}} ``` +13 bytes for negative case bug. [Try it online!](https://tio.run/##NY7BCsIwEETv@YqwguxiFvUgQmMVFXruB/SitZEcjKVRSCj99poKvb0Zdmem5mddj@Pi0RjrGlngWV3Ulcy7Q5uf9YVZU9tZ9zF4JS3mu1K2349HANIFRmUVSKACb3ePjjgKn6ygojZJ9iF3h42eIn0eTlt2mdN@Cu5j0uzYZ16X08cJqmoNGayrCiiu8pBsfwzLZSpgBhqG8XWzDkn0QkppkHdp1J82M@wTDGL8AQ "C (gcc) – Try It Online") Ungolfed (207 bytes after removing all spaces and newline): ``` s, i, x, y; f(n) { x = n < 0; for (s = x ? 1 - n : n; s--;) { y = x ? - n - s : s; puts(""); for (i = y; i--;) printf(" "); for (i = abs(n) - y; i--;) printf(x ? "\\/" : "/\\");; y += x; puts(""); for (i = y; i--;) printf(" "); for (i = abs(n) - y; s > x && i--;) printf("--");; } } ``` [Answer] ## Charcoal, ~~31~~ ~~28~~ 27 bytes ``` FI⊟⪪θ-«←ι↓→/…\/ι↙»‖M¿‹N⁰‖T↓ ``` [Try it online!](https://tio.run/##VY6xDoIwEIZneIqm05HQYOKGoy4m1BB0ZKnYSpPSYltwMD57LQnGeNt99/@Xr@uZ7QxTIQhjEeyZ81CbEc6jkh4eOcIEZ3HQK01qK7WHsuLC50hmuzShZuZQHsxTL9t6b@S9jwFc4B@kRt0At22Bl@Z/dfkXyTttuFC881RaayxEJAWCijsHRz1O/jQNVx55jjbRZw1fLNMuqg9fjRDINpA5EKc@ "Charcoal – Try It Online") Link is to verbose version of code. I had about 4 different 32 byte answers then found this. Edit: Saved ~~3~~ 4 bytes by performing the `abs` using string manipulation. Explanation: ``` ⪪θ- Split the input (θ = first input) on - ⊟ Take the (last) element I Convert it to a number i.e. abs(θ) F « Repeat that many times ←ι Print half of the -s ↓ Position for the /\s →/ Print the first / …\/ι Print half of any remaining \/s ↙ Position for the next row of -s » End of the loop ‖M Mirror everything horizontally ¿‹N⁰ If the input was negative ‖T↓ Reflect everything vertically ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~40~~ 38 bytes *-2 bytes thanks to @Shaggy* ``` o½½@aXc)ç +"--/\\\\/"ò gYv *Ug)pXc a÷ ``` [Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=b729yGMgYVUg5yArIi0tL1xcXFwvIvIgZ7BZdSAqVWcpcFhjIGHDtw==&input=NQ==) ## Explanation ``` o½½@aXc)ç +"--/\\\\/"ò gYv *Ug)pXc a÷ // implicit: U = input integer o.5,.5,XYZ{UaXc)ç +"--/\\\\/"ò gYv *Ug)pXc a} qR // ungolfed o.5,.5, // array [.5,U] with step size .5 XYZ{ } // mapped by the function: (X = value, Y = index) UaXc) // absolute diff between U and ceil(X) ç // " " times that value +"--/\\\\/"ò g ) // plus ["--","/\","\/"].get(... Yv // if Y is even, 1, else 0 *Ug // times sign(U) pXc a // repeated abs(ceil(X)) times qR // all that joined with newlines ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), 21 [bytes](https://github.com/splcurran/Gaia/blob/master/codepage.md) ``` :┅“/\\“--”צ¦_€|ḣ¤ọ×ṣ ``` ### Explanation ``` : Push 2 copies of the input ┅ Get the range to the input. If positive: [1 .. n]. If negative: [-1 .. n]. If zero: [0]. “/\\“--” Push ["/\", "--"] צ¦ Repeat both of those strings by each number in the range. Strings go in reverse order when repeated a negative number of times. _ Flatten the list €| Centre-align the rows of the list ḣ Remove the last row (the "--"s on the bottom) ¤ Swap (bring input back to the top) ọ Sign: -1 for negative, 0 for 0, 1 for positive × Repeat the list that many times; (-1 × list) reverses it ṣ Join with newlines and implicitly output ``` [Answer] # Mathematica, 140 bytes ``` (T=Table;z=Column;B[a_]:=""<>"/\\"~T~a;If[#>0,m=0,m=Pi];z[Join[z/@T[{B@i,""<>"--"~T~i},{i,Abs@#-1}],{B@Abs@#}],Alignment->Center]~Rotate~m)& ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~116~~ ~~111~~ 105 bytes *this got way too long :/* ``` \d+ $* +`^~?( *1*)1 $1¶$&¶_$& .*$ +`(_.*)1 $1-- 1 /\ Ts`/\\`\\/`.*~.* +`(.*)¶((.*¶)*)(~.*) $2$4¶$1 ~|_ ``` [Try it online!](https://tio.run/##FYwxDsIwEAT7fUWKU3S@KLYOQc0nKE/YkUJBQwGUyM/yA/wxc6lW2hnN@/F9vrYxbF9AgqXc65UnUQmKibQ3mnvLNCMKwTHneCDSdYUiGW6fksyKWSpRajwS7Epv7NNbkMD@BtCJzl5T1F/GGPXyBw "Retina – Try It Online") negative input is denoted as `~n` [Answer] # [Perl 5](https://www.perl.org/), 100 + 1 (-n) = 101 bytes ``` $/=$_>0?'/\\':'\\/';push@r,$_=$"x--$q.$/x$_,y|/\\|-|r for 1..($q=abs);pop@r;say for$_<0?reverse@r:@r ``` [Try it online!](https://tio.run/##FcpLCsIwEADQqxQZiELz6SKbxthcoDcIhAoRBWnSiUoLObtTXb@XIz41EUgL4aIGJr1nPfNeMpPf5e6whWDhsHIOiwC5Qmi3@kuVV2xuCZtOiCMsdrqWk8kpOzRl2v4C4awGjJ@IJTrsHRLpb8qvR5oL8VEL1Sni8w4 "Perl 5 – Try It Online") ]
[Question] [ Your task is simple: write a program (or function) that takes no input and outputs (or returns) its source code. The catch is that when the program is wrapped in `"quotes"` (Unicode character 34), it should again output its (now quoted) source code. Standard rules for quines apply. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program (in bytes) wins. [Answer] # Python ~~2~~ 3, ~~181~~ ~~152~~ ~~130~~ ~~124~~ ~~122~~ ~~100~~ ~~98~~ ~~96~~ 84 bytes *-12 bytes thanks to Jakque.* ``` a=1;""";a=0;" """;p='"a=1;""";a=0;" """;p=%r;print(p[a:~a]%%p)#".';print(p[a:~a]%p)# ``` [Try it online!](https://tio.run/##pU9BDoIwELzzimYNKQQkEm80fYQXL0jIAlWbNG0DJdGLX0cQOWg46WV3Mju7M2vv7mr0fmjEmdhWahdgmF2UqVAR0zvbOzY3jqwsq14qJ3VXlski9mrTCE4pHZCnDAAY8h0DMiHLKayxfsvmdZtj9sDC9224gYR@sSM5jIdnh6nkabZNC28lxzQNmbiJ@g1XNHDopRbkiEo2GcTzW0nbuVbaAE4aQv5y@aCW/4BGE4hG4DVCERvjHzmME@SnNMMT) The TIO comes with a header and footer that automatically test the validity of the quine. You can clear them to just run the quine. This code works by (ab)using the triple-quoted strings and string literal concatenation in Python. * `";b=""";b=" """;` ignores `';b='` and sets `b` to `' '`. * `"";b=""";b=" """;` ignores the empty string and sets `b` to `';b=" '`. The rest of the code then implements the traditional Python quine using `%r` string formatting, with some additional code that strips the extra quotes depending on `b`. ## Older version from 2017, 122 bytes ``` """ """>" "or exec("oct=0");p='"""" """>" "or exec("oct=0");p=%r;a=oct==0;print(p[a:~a]%%p)#".';a=oct==0;print(p[a:~a]%p)# ``` [Try it online!](https://tio.run/nexus/python3#nU/LCoMwELz7FWGLxGAr9mpI/6GXXqxI1LQEggkxQk/9dZsoHoQ@oId9zjIz24kbMlb2LuGkuCvdcIX06Mzo6FIYp3XdjFI52Q91na3HUas7wTDGEwAgHyeftUXiIdoEdOtYDoQahuE7HlvKWRhZThduU/Liyas4NmQHGf4Ee3Ty8ouPkMpjcThW0SwQZvLOOJxH2Qt04Up2BeyXHzM7OCtNAtceCJvJNqv1WcBpaFLfRMHTht8vfmtrJ9BfDqYX) `""" """` is equal to `' '` and `"""" """` is equal to `'" '`. The code does use `exec`, but not for the "non-quiney" way of executing data as code, just for setting a variable from inside an expression. The `exec` is properly encoded in the data, too. The first statement compares the string, possibly with a quote prepended, to `" "`, and sets the variable `oct` accordingly. (The variable could've been any short builtin.) The final part then checks if `oct` is unchanged. An alternative version using the "cheaty" `exec` comes in at 126 bytes with less repeated code: ``` """ """>" "and exec("oct=0");s='"""" """>" "and exec("oct=0");s=%r;p=%r;exec(p)#".';p='a=oct!=0;print(s[a:~a]%(s,p))';exec(p)# ``` [Try it online!](https://tio.run/nexus/python3#nU9BCsIwELz3FXFF0tBa9JoQ/@DFSy0ltlECJQlNCp78ek1aKhQEwUMmu7PD7kwr78j2SvtUEProzE10yAzeDp7NHxesrm@D6rzSrq6LRZw0ppUcYzwCAArvFFDoFsmnbFIwjecHIMxxDD8Eu57ZCBNvyRYKHAgseJBs@IHNF10p6EtUu9TllhD8UY/BwuwlQnmk@2OVTMPYk2/m4TwoLdFFdKqlkM85i975XtkUrhoIn5atqCUw4CwWWSiSmGG1PxC/bxsv0V8Oxjc) [Answer] # [StandardML](https://en.wikipedia.org/wiki/Standard_ML), ~~182 176~~ 108 bytes ``` ";str(chr 34)^it;(print(it^it);fn x=>print(x^it^x^it))";str(chr 34)^it;(print(it^it);fn x=>print(x^it^x^it)) ``` Unquoted version: [Try it on codingground.](http://www.tutorialspoint.com/execute_smlnj_online.php?PID=0Bw_CjBb95KQMckU4eUxMVV9VLW8) Quoted version: [Try it on codingground.](http://www.tutorialspoint.com/execute_smlnj_online.php?PID=0Bw_CjBb95KQMbWdVdVk5bWs3Njg) Note that the output looks something like this ``` > val it = "{some string}" : string > val it = "{some string}" : string {output to stdout}> val it = fn : string -> unit ``` because the code is interpreted declaration by declaration (each `;` ends a declaration) and shows the value and type of each declaration. --- ### Background In SML there is a quine of the form `<code>"<code in quotes>"`: ``` str(chr 34);(fn x=>print(x^it^x^it))"str(chr 34);(fn x=>print(x^it^x^it))" ``` and one in the form `"<code in quotes>"<code>`: ``` ";str(chr 34)^it;print(it^it)";str(chr 34)^it;print(it^it) ``` Both rely on the fact that the `<code>`-part contains no quotes and can thus be quoted with out the need for escaping anything, the `"` needed to output the quine are given by `str(chr 34)`. They also heavily rely on the implicit identifier `it` which is used when no explicit identifier is given in a declaration. In the first quine `str(chr 34);` binds `it` to the string containing `"`, `fn x=>` starts an anonymous function taking one argument `x`, then concatenates `x^it^x^it` and prints the resulting string. This anonymous function is directly applied to a string containing the program code, so the concatenation `x^it^x^it` yields `<code>"<code>"`. The second quine starts with just the program code as string `";str(chr 34)^it;print(it^it)";` which is bound to `it`. Then `str(chr 34)^it;` concatenates a quote to the start of the string and as again no explicit identifier is given, the resulting string `"<code>` is bound to `it`. Finally `print(it^it)` concatenates the string with itself yielding `"<code>"<code>` which is then printed. --- ### Explanation ***Edit:** No longer up to date with the 108-byte version, however one might understand it too after reading this explanation.* The quote-safe quine combines both of the above approaches and is itself of the form `"<code>"<code>`. Putting this in again in quotes yields `""<code>"<code>"`, so we get an empty string and then a quine of the other form. That means the program is either given its own source in the form `"<code>` by the identifier `it`, or `it` is just `"` and we are given our own source `<code>` as argument and must thus be a function which handles such an argument. ``` (if size it>1then(print(it^it);fn _=>())else fn x=>print(it^it^x^it^x^it)) ``` To identify in which case we are, we check whether the size of `it` is larger than 1. If not then `it` is `"` and we are in the second case, so the `else`-part returns an anonymous function `fn x=>print(it^it^x^it^x^it)` which is then called because its followed by source as string. Note the leading `it^it^` which is needed for the empty string at the start of the of the program. If `size it` is larger than 1 we are in the `then`-part and just perform `print(it^it)`, right? Not quite, because I neglected to tell you that SML is strongly typed which means that a conditional `if <cond> then <exp_1> else <exp_2>` must always have the same type which again means that the expressions `<exp_1>` and `<exp_2>` need to have the same type. We already know the type of the `else` part: An anonymous function which takes a string and then calls `print` has type `string -> <return type of print>`, and `print` has type `string -> unit` (`unit` is in some way similar to `void` in other languages), so the resulting type is again `string -> unit`. So if the `then` part was just `print(it^it)` which has type `unit`, we would get a type mismatch error. So how about `fn _=>print(it^it)`? (`_` is a wildcard for an argument that is not used) This anonymous function on its own has type `'a -> unit` where `'a` stands for an arbitrary type, so in the context of our conditional which enforces a `string -> unit` type this would work. (The type variable `'a` gets instantiated with type `string`.) However, in this case we would not print anything as the anonymous function is never called! Remember, when we go in the `then`-part the overall code is `"<code>"<code>`, so the `<code>`-part evaluates to a function but, as nothing comes after it, its not called. Instead we use a sequentialisation which has the form `(<exp_1>; ...; <exp_n>)` where `<exp_1>` to `<exp_n-1>` may have arbitrary types and the type of `<exp_n>` provides the type of the whole sequentialisation. From a functional point of view the values of `<exp_1>` to `<exp_n-1>` are simply discarded, however SML also supports imperative constructs so the expressions may have side effects. In short, we take `(print(it^it);print)` as the `then`-part, thus printing first and then returning the function `print` which has the correct type. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~27~~, 23 bytes ``` éPñi"éP241"qpá"lxx|xÿ ``` [Try it online!](https://tio.run/nexus/v#@394ZcDhjZlKQErMyMRQWqmw4PBCpZyKipqKw/v//wcA "V – TIO Nexus") Since this contains some unprintable characters, here is a readable version: ``` éPñi"éP<C-v>241<esc>"qpá"lxx|xÿ ``` and here is a hexdump: ``` 00000000: e950 f169 22e9 5016 3234 311b 2271 70e1 .P.i".P.241."qp. 00000010: 226c 7878 7c78 ff "lxx|x. ``` So the very first thing we need to do is to determine if the first character is a quote. `éP` inserts a 'P' character, but `"éP` is a NOOP. After that, we run a slight modification on the standard extendable quine, which is: ``` ñi<C-v>241<esc>"qpÿ ``` We're going to do it slightly differently though. First off we need to insert the starting "éP" text. So we do ``` ñ " Start recording into register 'q' i " Enter insert mode "éP<C-v>241<esc> " Enter the following text: '"éPñ' "qp " Paste the text in register 'q' á" " Append a '"' ``` Here is where the branching happens. The text currently in the buffer is ``` "éPñi"éP<C-v>241<esc>"qpá"P Cursor is here ----------^ ``` Unless we wrapped it in quotes, in that case the 'P' would never have been inserted, and the buffer is: ``` "éPñi"éP<C-v>241<esc>"qpá" Cursor is here ----------^ ``` Since we are still recording, we can do whatever we want here, and it will get added to the buffer when the `"qp` happens. So from here it's pretty easy to conditionally delete the quotes: ``` l " Move one character to the right. If there is no character to the right, " then this is effectively a "break" statement, stopping playback of the recording xx " Delete two characters (the '"P') | " Move to the first character on this line x " Delete one character ÿ " End the program ``` [Answer] # [Noodel](https://tkellehe.github.io/noodel/), ~~9~~ 7 [bytes](https://tkellehe.github.io/noodel/docs/code_page.html) This version works the same way as the other, just that I forgot that *Noodel* has a way to run a block of code once and I made the language... ~~`Ḷ1ḥ-Ð1ḥ@€`~~ ``` ḷḥ-Ðḥ@ḅ ``` [Try it:)](https://tkellehe.github.io/noodel/editor.html?code=%E1%B8%B7%E1%B8%A5-%C3%90%E1%B8%A5%40%E1%B8%85&input=&run=false) --- ### How it Works ``` ḷḥ-Ðḥ@ḅ # Single statement that builds itself as a string. ḷ # Loop the following block of code unconditionally. ḥ- # Push the string literal of the token preceding this one which pushes "ḷ" onto the stack. Ð # Push the stack as an array to stdout (since is an array it is done by reference). ḥ@ # Push the string literal for this block of code which pushes "ḥ-Ðḥ@ḅ" onto the stack. ḅ # Break out of the given loop. (The stack is now ["ḷ", "ḥ-Ðḥ@ḅ"]). # The top of the stack is popped off and displayed which modifies the array to produce {["ḷ"], "ḥ-Ðḥ@ḅ"} in stdout. ``` --- ### Quote-Safety Placing the `"` character before and after the program works because *Noodel* has a set of of characters dedicated to what I call *printables*. These are immediately parsed as string literals when placed by themselves and allow for easily printing something to the screen. So unlike most languages, *Noodel* sees the normal *ASCII* set that is considered print worthy as direct string literals (except for space and line feed) therein quoting the code is merely seen as pushing on strings. ``` "ḷḥ-Ðḥ@ḅ" " # Pushes on the string literal "\"" onto the stack. ḷḥ-Ðḥ@ḅ # Same execution as before, simply builds the Quine for this loop. ḷ # Loop the following block of code unconditionally. ḥ- # Push the string literal of the token preceding this one which pushes "ḷ" onto the stack. Ð # Push the stack as an array to stdout (since is an array it is done by reference). ḥ@ # Push the string literal for this block of code which pushes "ḥ-Ðḥ@ḅ" onto the stack. ḅ # Break out of the given loop. (The stack is now ["\"", "ḷ", "ḥ-Ðḥ@ḅ"]). " # Pushes on the string literal "\"" onto the stack. # The top of the stack is popped off and displayed which modifies the array to produce {["\"", "ḷ", "ḥ-Ðḥ@ḅ"], "\""} in stdout. ``` ["Try it:)"](https://tkellehe.github.io/noodel/editor.html?code=%22%E1%B8%B7%E1%B8%A5-%C3%90%E1%B8%A5%40%E1%B8%85%22&input=&run=false) --- ### Snippets ``` <div id="noodel" code='ḷḥ-Ðḥ@ḅ' input="" cols="10" rows="1"></div> <script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script> <script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script> ``` --- ``` <div id="noodel" code='"ḷḥ-Ðḥ@ḅ"' input="" cols="10" rows="1"></div> <script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script> <script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script> ``` [Answer] # JavaScript (ES6), ~~239~~ 237 bytes ``` Set=``;eval(";a='Set=``;eval(~;a=1;S=String.fromCharCode;q=S(34);r=Set&&q;s=S(39);alert(r+a.replace(/[^ -}]/g,q).replace(1,s+a+s)+r);~)';S=String.fromCharCode;q=S(34);r=Set&&q;s=S(39);alert(r+a.replace(/[^ -}]/g,q).replace(1,s+a+s)+r);") ``` Take care to try each version in a fresh environment (e.g., a new browser tab) There has got to be at least one way to simplify this... [Answer] # [Perl 5](https://www.perl.org/), 59 bytes ``` ";$\=q;";;$_=q(print$\,'";$\=q;";;$_=q('."$_);eval#");eval# ``` [Try it online!](https://tio.run/##K0gtyjH9/1/JWiXGttBaydpaJd62UKOgKDOvRCVGRx1NXF1PSSVe0zq1LDFHWQlK//8PAA "Perl 5 – Try It Online") ## Quoted ``` "";$\=q;";;$_=q(print$\,'";$\=q;";;$_=q('."$_);eval#");eval#" ``` [Try it online!](https://tio.run/##K0gtyjH9/19JyVolxrbQWsnaWiXetlCjoCgzr0QlRkcdTVxdT0klXtM6tSwxR1kJRv//DwA "Perl 5 – Try It Online") ## Explanation In the original, there is an unused string `";$\=q;"` separated by `;;` before the standard quine body which first `print`s `$\` (which is empty by default) followed by the unused string and the body followed by `#`. In the quoted string, there is an unused string `""`, separated by `;` then `$\` is set to `q;";` which is Perl's custom quotes `q;...;` wrapping the double-quote char. Then the quine body is built and `$\` is automatically `print`ed after all content adding the final `"` in the quoted string. [Answer] # [Python 2](https://docs.python.org/2/), 68 bytes & [Python 3](https://docs.python.org/3/), 70 bytes ## Python 2, 68 bytes: ``` x=""#";x='"' s='x=""#";x=\'"\'\ns=%r;print x+s%%s+x#';print x+s%s+x# ``` [Try it online!](https://tio.run/##TY1BCoMwEEX3OcUwEn4luLDLypyk6UoDuomSuJiePo0KxeV7fN7fvvu8xmcZ1ymQUAJQVJgbHlTAMFnwZw/28DGLTcOWlriTumxtdtrgJg4uNfTuX13/MUHD@Dj6rTk3l6htcnTeOqrQlh8 "Python 2 – Try It Online") ## Python 3, 70 bytes: ``` x=""#";x='"' s='x=""#";x=\'"\'\ns=%r;print(x+s%%s+x)#';print(x+s%s+x)# ``` [Try it online!](https://tio.run/##K6gsycjPM/6fnJ@SqmCrUKSurv6/wlZJSVnJusJWXUmdq9hWHc6PUVeKUY/JK7ZVLbIuKMrMK9Go0C5WVS3WrtBUVkcSAQv8BxoVbWilaxjLlVqRmqwBskGTC6JIEyIENF9BWwFstbYCkKP5HwA "Python 3 – Try It Online") ## How does it work? : * Without quotes: `x=""#";x='"'` will stop the execution at the coment `#` char => `x=""` * With quotes: `"x=""#";x='"'` have just 2 string concatened `"x="` and `"#"` which don't do anything, and an assignation : `x='"'` Now `x` is filled with the good char (quote or empty). We use then the standard python quine : `s='s=%r;print(s%%s)';print(s%s)` adding a few extras to make it work here, for example `#` at the end to avoid an EOF Error when a `"` is added at the end of the program Then, we just print our quine adding `x` at the start and at the end of the string [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `D`, 29 bytes ``` `Dqp^≈[_\\"pǏ]₴`Dqp^≈[_\"pǏ]₴ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=D&code=%60Dqp%5E%E2%89%88%5B_%5C%5C%22p%C7%8F%5D%E2%82%B4%60Dqp%5E%E2%89%88%5B_%5C%22p%C7%8F%5D%E2%82%B4&inputs=&header=&footer=) Explained: ``` `...`Dqp^≈[_\"pǏ]₴ `...` Push half the source code D Make 3 copies of the source code qp Uneval the first copy (quote, escape) and prepend it to the second ^ Reverse the stack ≈[_\"pǏ] Execute if all elements are the same. Since this is not the case, it just pops the third copy of the source code ₴ Print the source ``` Quoted version: ("[Try it Online!](http://lyxal.pythonanywhere.com?flags=D&code=%22%60Dqp%5E%E2%89%88%5B_%5C%5C%22p%C7%8F%5D%E2%82%B4%60Dqp%5E%E2%89%88%5B_%5C%22p%C7%8F%5D%E2%82%B4%22&inputs=&header=&footer=)") ``` "`...`Dqp^≈[_\"pǏ]₴" " Push the set [0, 0] `...` Push the source code D Make 3 copies of the source code qp Uneval the first copy and prepend it to the second ^ Reverse the stack, putting [0, 0] on the top ≈[ ] Execute if all elements of the top of the stack are the same. This is the case because of the [0, 0] pushed by " _ Remove the third copy of the source from the stack \" Push `"` pǏ Prepend and enclose the source with `"` ₴ Print the source " Push [0, 0], having no effect because the source is already printed ``` [Answer] # [Haskell](https://www.haskell.org/), 142 bytes ``` --"#p=p['"']>>"--\""#p k#p=p x>>print x>>p k;main="--"#putStr;x="--\"#p=p['\"']>>\"--\\\"\"#p\nk#p=p x>>print x>>p k;main=\"--\"#putStr;x=" -- ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/X1dXSbnAtiBaXUk91s5OSVc3RgkowJUNElSosLMrKMrMKwEzFLKtcxMz82yVwFpKS4JLiqwrbME6ICbEgI2IAYnExCiBRGPy8JgTA9UKN4lLV/f/fwA "Haskell – Try It Online") ``` "--"#p=p['"']>>"--\""#p k#p=p x>>print x>>p k;main="--"#putStr;x="--\"#p=p['\"']>>\"--\\\"\"#p\nk#p=p x>>print x>>p k;main=\"--\"#putStr;x=" --" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/X0lXV0m5wLYgWl1JPdbODsiNUQIKcGWDBBUq7OwKijLzSsAMhWzr3MTMPFuIltKS4JIi6wpbsA6ICTFgI2JAIjExSiDRmDw85sRAtcJN4gIa/P8/AA "Haskell – Try It Online") This uses a pretty simple detection method. The first line is normally a comment. ``` --"#p=p['"']>>"--\""#p ``` However when a quote is added to the front ``` "--"#p=p['"']>>"--\""#p ``` It becomes the declaration of an operator `(#)`. So what this program does is defines `(#)` such that it prints the normal source for when called with `"--"#putStr`, however when the quotes appear the new definition supersedes it and prints the source with quotes. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `D`, ~~18~~ 17 bytes ## Normal ``` `q‛:Ė+$[‛""$j,`:Ė ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiYHHigJs6xJYrJFvigJtcIlwiJGosYDrEliIsIiIsIiJd) ## Quoted ``` "`q‛:Ė+$[‛""$j,`:Ė" ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiXCJgceKAmzrEliskW+KAm1wiXCIkaixgOsSWXCIiLCIiLCIiXQ==) ## Explanation : ``` # Normal `q‛:Ė+ ` # structure for a quine => [ <quine> ] :Ė # add a copy of the structure on the stack and exec it q # push the quoted string on the stack => [ `<quine>` ] ‛:Ė+ # add ':Ė' to the string on the stack => [ `<quine>`:Ė ] $ # swap the two values on top of he stack => [ `<quine>`:Ė , 0 ] [ # pop and check if it is nul (it is) => [ `<quine>`:Ė ] ‛""$j, # irrevelent here # implicit output # Quoted " # listify the two elements on top of the stack => [ [0,0] ] `q‛:Ė+ ` # structure for a quine => [ [0,0] , <quine> ] :Ė # add a copy of the structure on the stack and exec it q # push the quoted string on the stack => [ [0,0] , `<quine>` ] ‛:Ė+ # add ':Ė' to the string on the stack => [ [0,0] , `<quine>`:Ė ] $ # swap the two values on top of he stack => [ `<quine>`:Ė , [0,0] ] [ # pop and check if it is nul (it is not as it's a list) => [ `<quine>`:Ė ] ‛"" # add `""` to the stack => [ `<quine>`:Ė, `""` ] $j # swap the two elements and join => [ "`<quine>`:Ė" ] , # print => [] " # listify the two elements on top of the stack => [ [0,0] ] # no implicit output as it has already printed via , ``` [Answer] # [Zsh](https://www.zsh.org/), 76 bytes ``` : "||z=\" #" s=': "||z=\" #" s=\47%s\47 printf $z$s$z $s ' printf $z$s$z $s ``` [Try it online!](https://tio.run/##qyrO@P/fSkGppqbKNkZJQVmJq9hWHY0fY2KuWgwkuAqKMvNK0hRUqlSKVaoUVIq51DGF/v8HAA "Zsh – Try It Online") ["Try it online!"](https://tio.run/##qyrO@P9fyUpBqaamyjZGSUFZiavYVh2NH2NirloMJLgKijLzStIUVKpUilWqFFSKudQxhZT@/wcA "Zsh – Try It Online") Note the trailing newline. Without the quotes, the first line is a call to the built-in no-op `:`, which ignores its string argument `||z=" #`. The variable `z` remains empty. With quotes, the first line is: * `": "`: execute `:` (note the space), which is a non-existent command * `||`: if this fails (which it will, since `:` doesn't exist), then: * `z=\"`: set the variable `z` to a single double-quote `"` * `#"`: comment; ignored The extra `"` on the last line is unmatched, but zsh helpfully ignores that until after the program has executed because it's a separate command line. The rest is a pretty standard shell quine, but we surround the string with `$z` so it gets double quotes if necessary. ]
[Question] [ ### Golf Challenge Given the below ASCII "Green". ``` | | | |> | | | | | O | | | | | | | | | | | | | ``` Let `|` Denote a wall Let `|` Denote half the flag pole Let `>` Denote the flag on the pole Let `O` Denote the hole Let `o` Denote the ball The dimensions of the "Green" is 10x10. There are ten spaces between the two walls `|`. There are also ten spaces, empty or not between the top and the bottom of the green. ### Challenge Input an x and y value or generate two random numbers to "shoot" a golf ball onto the green. If the x, y generated does not touch the hole or the flag pole/flag output "Try Again!" If the x, y generated hits the hole output "Hole in One!" if the x, y generated hits the pole output "Lucky Shot!" if the x, y generated hits the flag output "Close One!" After the shot, output the location of the ball on the green with a `o`, replacing any character it hit. Also output the respective saying above. Examples: ``` //Hole in one example, the O was replaced with a o Randomed x = 3 Randomed y = 4 "Hole in One!" | | | |> | | | | | o | | | | | | | | | | | | | //Clone example, the top half of the pole was replaced with a o Randomed x = 3 Randomed y = 2 "Lucky Shot!" | | | o> | | | | | O | | | | | | | | | | | | | //Lucky Shot example, the > was replaced with a o Randomed x = 4 Randomed y = 2 "Close One!" | | | |o | | | | | O | | | | | | | | | | | | | //Try Again example, the <space> was replaced with a o Randomed x = 5 Randomed y = 1 "Try Again!" | o | | |> | | | | | O | | | | | | | | | | | | | ``` Have fun and good luck and as this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest code wins! [Answer] # JavaScript (ES6) ~~210~~ ~~208~~ ~~193~~ 184 bytes ``` f=(a,b)=>((s=[...(` | |`).repeat(10)])[17]=s[30]='|',s[18]='>',s[43]=0,s[a+=1+b*13]='o',(a-17&&a-30?a-18?a-43?'Try Again!':'Hole in One!':'Close One!':'Lucky Shot!')+s.join``) ``` * -9 bytes thanx to [Hedi](https://codegolf.stackexchange.com/users/58765/hedi) # [Demo](https://jsfiddle.net/0hsgso10/5/) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 78 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ċЀ®Ḍị“ȷþḄ7Ẋ“þẹƊ⁴ḳL&Ṛ“qĠṂ®““ÞzḊṁġ“»;”!Ṅṛ ⁶ẋ“€¡®µC‘ż“|>|O”©F”o⁸¦Ç ṭḌ‘Çs⁵j@€⁾||Y ``` Play a **[Skill-Game](http://jelly.tryitonline.net/#code=xIvDkOKCrMKu4biM4buL4oCcyLfDvuG4hDfhuorigJzDvuG6ucaK4oG04bizTCbhuZrigJxxxKDhuYLCruKAnOKAnMOeeuG4iuG5gcSh4oCcwrs74oCdIeG5hOG5mwrigbbhuovigJzigqzCocKuwrVD4oCYxbzigJx8PnxP4oCdwqlG4oCdb-KBuMKmw4cK4bmt4biM4oCYw4dz4oG1akDigqzigb58fFk&input=&args=Mg+Mw)** or a **[Crap-Shoot](http://jelly.tryitonline.net/#code=xIvDkOKCrMKu4biM4buL4oCcyLfDvuG4hDfhuorigJzDvuG6ucaK4oG04bizTCbhuZrigJxxxKDhuYLCruKAnOKAnMOeeuG4iuG5gcSh4oCcwrs74oCdIeG5hOG5mwrigbbhuovigJzigqzCocKuwrVD4oCYxbzigJx8PnxP4oCdwqlG4oCdb-KBuMKmw4cK4oG1WOKAmeG5reKBtVjigJnCpOG4jOKAmMOHc-KBtWpA4oKs4oG-fHxZ&input=)** at **TryItOnline!** (Crap-shoot cost more bytes). ### How? ``` ṭḌ‘Çs⁵j@€⁾||Y - Main link: x, y (0-based) ṭ - tack -> [y, x] Ḍ - cast to decimal -> 10y+x ‘ - increment -> 10y+x+1 Ç - call last link (1) as a monad s⁵ - split into chunks of size 10 (rows of green display) ⁾|| - literal ['|','|'] j@€ - join €ach with reversed @rguments (make the border) Y - join with line feeds - implicit print ⁶ẋ“€¡®µC‘ż“|>|O”©F”o⁸¦Ç - Link 1, Make green & place the ball: decimal 1-based location “€¡®µC‘ - code page indexes -> [12,0,8,9,67] ⁶ - literal ' ' ẋ - repeat (vectorises) ż - zip with “|>|O” - literal ['|','>','|','O'] © - and place the flag parts into the register F - flatten list ¦ - apply to index at ⁸ - input value ”o - literal 'o' Ç - call the last link (2) as a monad ċЀ®Ḍị“ȷþḄ7Ẋ“þẹƊ⁴ḳL&Ṛ“qĠṂ®““ÞzḊṁġ“»;”!Ṅṛ - Link 2, Print message: green with ball ® - read register (the flag parts) | > | O ċЀ - count occurrences e.g. HoleInOne: [2,1,2,0] Ḍ - cast to decimal ->2120 ị - index into (1-based & modular) 2120 % 6 = 2 “ȷþḄ7Ẋ“þẹƊ⁴ḳL&Ṛ“qĠṂ®““ÞzḊṁġ“» - compressed list of (6) strings: ...["Lucky Shot","Hole in One","Try Again","","Close One",""] ; - concatenate with ”! - literal '!' Ṅ - print with linefeed ṛ - yield right argument (the green) ``` [Answer] # Python 2, ~~290~~ ~~264~~ ~~262~~ ~~252~~ ~~248~~ 245 bytes It's not pretty and it's not short but I'm tired and its the ~~first~~ only Python answer. Enter shot in x,y format. **Edit** Golfed off 26 by redefining the way the list is built. Still no luck with the long if statement though. -2 by replacing the long if with a dictionary and a shorter if. -10 with thanks to @Noodle9 - I'd missed that one :) -4 - thanks again :) Another 3 off. Thanks. ``` x,y=input();a=[' ']*120;a[15]=a[27]='|';a[16],a[39],b='>','0',x+y*12 a[b],k='o',"Lucky Shot!";l={16:"Close One!",15:k,27:k,39:"Hole in One!"} print l[b]if b in l else"Try Again!" for z in range(10):c=z*12;a[c]=a[c+11]='|';print''.join(a[c:c+12]) ``` For anyone who is interested in the logic, ungolfed with comments (1316 bytes but still easily fits on a 3.5" disk if anyone remembers them): ``` x,y=input() #Get the input as a tuple a=[' ']*120 #Create a great big list of spaces for the whole green a[15]=a[27]='|' #Put the flag pole in place a[16]='>' #Add the flag a[39]='0' #Add the hole b=x+y*12 #Get the absolute position in the list of the input tuple a[b]='o' #Place the ball on the green k="Lucky Shot!" #Set a variable for k because it is long and we're going to use it twice l={16:"Close One!",15:k,27:k,39:"Hole in One!"} #Create a dictionary of the comments (using k) print l[b]if b in l else"Try Again!" #If the absolute index is in the dict then print it otherwise print the default for z in range(10): #Loop through the length of the green c=z*12 #Set a variable for the start point of each line a[c]=a[c+11]='|' #Add the left and right walls print''.join(a[c:c+12]) #Print each line in turn. Because this is in a for loop then Python will deal with newlines ``` Definitely the first time for me that a dictionary has been the best data format in a golf challenge. [Answer] # C, 236 bytes ``` n,m;char*a[]={"Try Again!","Hole in One!","Lucky Shot!","Close One!"};f(x,y){n=130;m=142-y*13-x;puts(a[(m==87)+2*(m==113|m==100)+3*(m==112)]);while(n--)putchar(m==n?111:n%13?n%13==1|n%13==12|n==113|n==100?124:n==112?62:n==87?79:32:10);} ``` Ungolfed: ``` n,m; char*a[]={"Try Again!","Hole in One!","Lucky Shot!","Close One!"}; f(x,y){ n=130; m=142-y*13-x; puts(a[(m==87) + 2*(m==113|m==100) + 3*(m==112)]); while(n--) putchar(m==n?111:n%13?n%13==1|n%13==12|n==113|n==100?124:n==112?62:n==87?79:32:10); } ``` [Answer] # Scala, 238 bytes ``` (x:Int,y:Int)=>{val r="< |\n" ('"'+(if(x==2&y==3)"Hole in One!"else if(x==2&(y==1|y==2))"Lucky Shot!"else if(x==3&y==1)"Close One!"else "Try again!")+"'",(r+"| |> |\n| | |\n| O |\n"+r*6)updated(1+x+13*y,'o'))} ``` Using zero-indexing. This is way too readable :( Explanation: ``` (x:Int,y:Int)=>{ //define an anonymous function val r="| |\n" //a shortcut for an empty row ( //return a tuple of '"'+ //a double quote (if(x==2&y==3)"Hole in One!" //plus the correct string else if(x==2&(y==1|y==2))"Lucky Shot!" else if(x==3&y==1)"Close One!" else "Try again!" )+"'" //and another quote , //and (r+"| |> |\n| | |\n| O |\n"+r*6) //the field updated(1+x+13*y,'o') //with the (1+x+13*y)th char replaced with a ball ) } ``` I've used the formula `1+x+13*y` to calculate the correct index, since each row is 13 chars long (2 borders, a newline and 10 spaces) plus an offset of one because (0,0) should be the second char. [Answer] # Perl, ~~225~~ 209 bytes ``` $_="|".$"x10 ."| ";$_.=sprintf("| %-8s| "x3,"|>","|",O).$_ x6;$d="Try Again!";($x,$y)=@ARGV;say$x==3?$y~~[2,3]?"Lucky Shot!":$y==4?"Hole in One!":$d:$x==4&&$y==2?"Close One!":$d;substr($_,$y*13-13+$x,1)=o;say ``` The two literal newlines each save one byte. Pretty standard. Prints the declaration, then the game board. [Answer] ## [Charcoal](http://github.com/somebody1234/Charcoal), 99 bytes ``` NαNβ× ⁵↑¹⁰‖C←J⁴¦²←>↓²OM⁴↖P⁺⎇∧⁼α³⁼β⁴Hole in One⎇∧⁼α³⁼¹÷β²Lucky Shot⎇∧⁼α⁴⁼β²Close One¦Try Again¦!Jαβo ``` Takes 1-based input, space-separated, on stdin. Most of the code is for printing (one of) the four messages. [Try it online!](http://charcoal.tryitonline.net/#code=77yuzrHvvK7OssOXIOKBteKGkcK54oGw4oCW77yj4oaQ77yq4oG0wqbCsuKGkD7ihpPCsk_vvK3igbTihpbvvLDigbrijofiiKfigbzOscKz4oG8zrLigbRIb2xlIGluIE9uZeKOh-KIp-KBvM6xwrPigbzCucO3zrLCskx1Y2t5IFNob3TijofiiKfigbzOseKBtOKBvM6ywrJDbG9zZSBPbmXCplRyeSBBZ2FpbsKmIe-8qs6xzrJv&input=MyAz) Note: Charcoal is still a work in progress. This code works as of [the current commit](https://github.com/somebody1234/Charcoal/commit/a148001cce2b2e4eb46fb56b03503b4de922d3fc). If it stops working in the future (in particular, if the TIO link doesn't work as expected), ping me and I'll try to add a non-competing updated version that works. ### Explanation ``` NαNβ Read two inputs as numbers into variables α and β Construct the green and flag: × ⁵ Print to canvas 5 spaces ↑¹⁰ Print 10 | characters going up ‖C← Reflect and copy leftward At this point, borders of green are complete; cursor is above left wall J⁴¦² Jump 4 units right and 2 down ←> Print the flag, going leftward ↓² Print the pin (2 | characters), going downward O Print the hole The last print was rightward by default, which means we're now at (4,4) M⁴↖ Move 4 units up and left; cursor is above left wall again Add the proper message: ⎇∧⁼α³⁼β⁴ If α is 3 and β is 4 (in the hole): Hole in One ⎇∧⁼α³⁼¹÷β² Else if α is 3 and β is 2 or 3 (hit the pin): Lucky Shot ⎇∧⁼α⁴⁼β² Else if α is 4 and β is 2 (hit the flag): Close One Else: ¦Try Again ⁺...¦! Concatenate a ! to the string P Print it without changing the cursor position Overwrite the appropriate spot with o: Jαβ Jump α units right and β units down o Print o ``` [Answer] # [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak), 1466 ~~1938~~ bytes ``` (<()>)<>((()()()()()){}){({}[()]<(((((((()()()()()){})){}{}()){}){})<((()()()()()){}){({}[()]<(((((()()){}){}){}){})>)}{}>)((()()()()()){})>)}{}((((()()){}){}){}()){({}[()]<({}<>)<>>)}{}{}{}(((((()()()()()){})){}{}()){})(((((((()()()()()){})){}{}()){}){})<(((()()()){}){}()){({}[()]<({}<>)<>>)}{}{}>)(((()()()){}){}()){({}[()]<({}<>)<>>)}{}{}(((((()()()){}){}){}){}){<>({}<>)}(<>{}((((({}[()])){}){})){}{}{}()<>{}){({}[()]<({}<>)<>>)}{}({}<(((((((()()()){}){})){}{}())){}{}){<>({}<>)}>)(({}<((({}(((()()){}){}){}()){})[()])>)[((((()()){}){}){}){}]){({}[(((()()){}){}){}]){({}[((()()()){}()){}]){{}{}(((((((((()()()){}()){}){}()){}){})[()()()()()])[(()()()){}()])<(((((()()()()()){}){}){}()){}())(((((()()){}){}){}){})>(((()()){}){}){}())(([((()()()){}()){}](({})<>)<>)[((()()){}){}])((<>{}<>[()()()()])[(((()()()()()){}){}){}()])<>}{}{{}((((((((((()()()){}){}){}()){}){}())<>)<>((()()())){}{})[(((()()()()()){})){}{}()])<(((((()()){}){}){}){})((((<>{}<>)((()()()){}()){})[()()()()])[()()()])>[((()()()){}){}])<>}}{}{{}((((((((()()()){}){}){}()){}){}())((()()())){}{})[(((()()()()()){})){}{}()])((((((()()){}){}){}){})<(((((()()()()()){}){({}[()])}{}){})[()()()()()])>)((((((((()()()){}){}){}()){}){}())(()()()){}())()()())((((((()()()){}){}){})){}{})<>}{}}{}{{}(((((((()()()()()){}){({}[()])}{}){})[()()()()()])[((()()){}){}])(()()()){})(((((((((((()()){}){}){}){})))({}<({}{}())>)[()()()()]){}())[(()()()){}()])[(((()()()()()){})){}{}])<>}<>(((((()()){}){}){}()){}) ``` [Try it online!](http://brain-flak.tryitonline.net/#code=KDwoKT4pPD4oKCgpKCkoKSgpKCkpe30peyh7fVsoKV08KCgoKCgoKCgpKCkoKSgpKCkpe30pKXt9e30oKSl7fSl7fSk8KCgoKSgpKCkoKSgpKXt9KXsoe31bKCldPCgoKCgoKCkoKSl7fSl7fSl7fSl7fSk-KX17fT4pKCgoKSgpKCkoKSgpKXt9KT4pfXt9KCgoKCgpKCkpe30pe30pe30oKSl7KHt9WygpXTwoe308Pik8Pj4pfXt9e317fSgoKCgoKCkoKSgpKCkoKSl7fSkpe317fSgpKXt9KSgoKCgoKCgoKSgpKCkoKSgpKXt9KSl7fXt9KCkpe30pe30pPCgoKCgpKCkoKSl7fSl7fSgpKXsoe31bKCldPCh7fTw-KTw-Pil9e317fT4pKCgoKCkoKSgpKXt9KXt9KCkpeyh7fVsoKV08KHt9PD4pPD4-KX17fXt9KCgoKCgoKSgpKCkpe30pe30pe30pe30pezw-KHt9PD4pfSg8Pnt9KCgoKCh7fVsoKV0pKXt9KXt9KSl7fXt9e30oKTw-e30peyh7fVsoKV08KHt9PD4pPD4-KX17fSh7fTwoKCgoKCgoKCkoKSgpKXt9KXt9KSl7fXt9KCkpKXt9e30pezw-KHt9PD4pfT4pKCh7fTwoKCh7fSgoKCgpKCkpe30pe30pe30oKSl7fSlbKCldKT4pWygoKCgoKSgpKXt9KXt9KXt9KXt9XSl7KHt9WygoKCgpKCkpe30pe30pe31dKXsoe31bKCgoKSgpKCkpe30oKSl7fV0pe3t9e30oKCgoKCgoKCgoKSgpKCkpe30oKSl7fSl7fSgpKXt9KXt9KVsoKSgpKCkoKSgpXSlbKCgpKCkoKSl7fSgpXSk8KCgoKCgoKSgpKCkoKSgpKXt9KXt9KXt9KCkpe30oKSkoKCgoKCgpKCkpe30pe30pe30pe30pPigoKCgpKCkpe30pe30pe30oKSkoKFsoKCgpKCkoKSl7fSgpKXt9XSgoe30pPD4pPD4pWygoKCkoKSl7fSl7fV0pKCg8Pnt9PD5bKCkoKSgpKCldKVsoKCgoKSgpKCkoKSgpKXt9KXt9KXt9KCldKTw-fXt9e3t9KCgoKCgoKCgoKCgpKCkoKSl7fSl7fSl7fSgpKXt9KXt9KCkpPD4pPD4oKCgpKCkoKSkpe317fSlbKCgoKCkoKSgpKCkoKSl7fSkpe317fSgpXSk8KCgoKCgoKSgpKXt9KXt9KXt9KXt9KSgoKCg8Pnt9PD4pKCgoKSgpKCkpe30oKSl7fSlbKCkoKSgpKCldKVsoKSgpKCldKT5bKCgoKSgpKCkpe30pe31dKTw-fX17fXt7fSgoKCgoKCgoKCkoKSgpKXt9KXt9KXt9KCkpe30pe30oKSkoKCgpKCkoKSkpe317fSlbKCgoKCkoKSgpKCkoKSl7fSkpe317fSgpXSkoKCgoKCgoKSgpKXt9KXt9KXt9KXt9KTwoKCgoKCgpKCkoKSgpKCkpe30peyh7fVsoKV0pfXt9KXt9KVsoKSgpKCkoKSgpXSk-KSgoKCgoKCgoKCkoKSgpKXt9KXt9KXt9KCkpe30pe30oKSkoKCkoKSgpKXt9KCkpKCkoKSgpKSgoKCgoKCgpKCkoKSl7fSl7fSl7fSkpe317fSk8Pn17fX17fXt7fSgoKCgoKCgoKSgpKCkoKSgpKXt9KXsoe31bKCldKX17fSl7fSlbKCkoKSgpKCkoKV0pWygoKCkoKSl7fSl7fV0pKCgpKCkoKSl7fSkoKCgoKCgoKCgoKCgpKCkpe30pe30pe30pe30pKSkoe308KHt9e30oKSk-KVsoKSgpKCkoKV0pe30oKSlbKCgpKCkoKSl7fSgpXSlbKCgoKCkoKSgpKCkoKSl7fSkpe317fV0pPD59PD4oKCgoKCgpKCkpe30pe30pe30oKSl7fSk&input=Mwoy&args=LUE) --- Did I win? [Answer] # TI-Basic, 183 [bytes](http://tibasicdev.wikidot.com/tokens) ``` Input X Input Y X+1➡X ClrHome For(I,1,10 Output(I,1,"| Output(I,12,"| End Output(2,4,"|> Output(3,4,"| Output(4,4,"O Output(Y,X,"o 13 Output(1,Ans,"TRY AGAIN! If X=4 and Y=4 Output(1,Ans,"HOLE IN ONE! If X=5 and Y=2 Output(1,Ans,"CLOSE ONE! If Y=2 or Y=3 and X=4 Output(1,Ans,"LUCKY SHOT! ``` Thank goodness TI-Basic uses tokens. The `|` cannot normally be typed, but it is in the character set. Please let me know if the result of the shot absolutely has to be lowercase. I will add a screenshot of an example program result later. [Answer] # Groovy - 235 bytes My first attempt - A groovy closure accepting 2 integers from 0 to 9 as the X and Y coordinates for the shot. ``` {j,k->j++;c='';b='|';f='>';h='O';s=' ';v=[2:b,3:b,4:h];(0..9).each{y->l=(b+s*10+'|\n').chars;l[3]=v[y]?:s;l[4]=y==2?f:s;if(k==y){m=[(s):'Try Again!',(b):'Lucky Shot!',(f):'Close One!',(h):'Hole In One!'][""+l[j]];l[j]='o'};c+=l};c+=m} ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 147 (or 127) [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Takes (y,x) as argument. ``` {G←10 10⍴'' G[⍳4;3]←' ||O' G[2;4]←'>' G[⊃⍵;⊃⌽⍵]←'o' ⍝ G[y;x]← ⎕←'|',G,'|' ⍝ Print G with sides 4 3≡⍵:'Hole in One!' ⍝ If (y,x) ≡ (4,3) (⊂⍵)∊2 3∘.,3:'Lucky Shot!' ⍝ If (y,x) ∊ {(2,3), (2,3)} 2 4≡⍵:'Close One!' 'Try Again!'} ⍝ Else ``` From version 16.0, we can almost halve the byte-count with the new `@` operator; `@` puts the left operand into the right-operand positions in the right argument: `NewChars @ Positions ⊢ Data` ``` {⎕←'|','|',⍨' ||O>o'@((2 4)⍵,⍨3,⍨¨⍳4)⊢10 10⍴'' 4 3≡⍵:'Hole in One!' (⊂⍵)∊2 3∘.,3:'Lucky Shot!' 2 4≡⍵:'Close One!' 'Try Again!'} ``` Slightly modified code to make permissible in TryAPL: [Hole in One](http://tryapl.org/?a=%7BG%u219010%2010%u2374%27%27%20%u22C4%20G%5B%u23734%3B3%5D%u2190%27%20%7C%7CO%27%20%u22C4%20G%5B2%3B4%5D%u2190%27%3E%27%20%u22C4%20G%5B%u2283%u2375%3B%u2283%u233D%u2375%5D%u2190%27o%27%20%u22C4%20%u2206%u2190%27%7C%27%2CG%2C%27%7C%27%20%u22C4%204%203%u2261%u2375%3A%u2206%27Hole%20in%20One%21%27%20%u22C4%20%28%u2282%u2375%29%u220A2%203%u2218.%2C3%3A%u2206%27Lucky%20Shot%21%27%20%u22C4%202%204%u2261%u2375%3A%u2206%27Close%20One%21%27%20%u22C4%20%u2206%27Try%20Again%21%27%7D%204%203&run), [Lucky Shot 1](http://tryapl.org/?a=%7BG%u219010%2010%u2374%27%27%20%u22C4%20G%5B%u23734%3B3%5D%u2190%27%20%7C%7CO%27%20%u22C4%20G%5B2%3B4%5D%u2190%27%3E%27%20%u22C4%20G%5B%u2283%u2375%3B%u2283%u233D%u2375%5D%u2190%27o%27%20%u22C4%20%u2206%u2190%27%7C%27%2CG%2C%27%7C%27%20%u22C4%204%203%u2261%u2375%3A%u2206%27Hole%20in%20One%21%27%20%u22C4%20%28%u2282%u2375%29%u220A2%203%u2218.%2C3%3A%u2206%27Lucky%20Shot%21%27%20%u22C4%202%204%u2261%u2375%3A%u2206%27Close%20One%21%27%20%u22C4%20%u2206%27Try%20Again%21%27%7D%202%203&run), [Lucky Shot 2](http://tryapl.org/?a=%7BG%u219010%2010%u2374%27%27%20%u22C4%20G%5B%u23734%3B3%5D%u2190%27%20%7C%7CO%27%20%u22C4%20G%5B2%3B4%5D%u2190%27%3E%27%20%u22C4%20G%5B%u2283%u2375%3B%u2283%u233D%u2375%5D%u2190%27o%27%20%u22C4%20%u2206%u2190%27%7C%27%2CG%2C%27%7C%27%20%u22C4%204%203%u2261%u2375%3A%u2206%27Hole%20in%20One%21%27%20%u22C4%20%28%u2282%u2375%29%u220A2%203%u2218.%2C3%3A%u2206%27Lucky%20Shot%21%27%20%u22C4%202%204%u2261%u2375%3A%u2206%27Close%20One%21%27%20%u22C4%20%u2206%27Try%20Again%21%27%7D%203%203&run), [Close One](http://tryapl.org/?a=%7BG%u219010%2010%u2374%27%27%20%u22C4%20G%5B%u23734%3B3%5D%u2190%27%20%7C%7CO%27%20%u22C4%20G%5B2%3B4%5D%u2190%27%3E%27%20%u22C4%20G%5B%u2283%u2375%3B%u2283%u233D%u2375%5D%u2190%27o%27%20%u22C4%20%u2206%u2190%27%7C%27%2CG%2C%27%7C%27%20%u22C4%204%203%u2261%u2375%3A%u2206%27Hole%20in%20One%21%27%20%u22C4%20%28%u2282%u2375%29%u220A2%203%u2218.%2C3%3A%u2206%27Lucky%20Shot%21%27%20%u22C4%202%204%u2261%u2375%3A%u2206%27Close%20One%21%27%20%u22C4%20%u2206%27Try%20Again%21%27%7D%202%204&run), [Random](http://tryapl.org/?a=%7BG%u219010%2010%u2374%27%27%20%u22C4%20G%5B%u23734%3B3%5D%u2190%27%20%7C%7CO%27%20%u22C4%20G%5B2%3B4%5D%u2190%27%3E%27%20%u22C4%20G%5B%u2283%u2375%3B%u2283%u233D%u2375%5D%u2190%27o%27%20%u22C4%20%u2206%u2190%27%7C%27%2CG%2C%27%7C%27%20%u22C4%204%203%u2261%u2375%3A%u2206%27Hole%20in%20One%21%27%20%u22C4%20%28%u2282%u2375%29%u220A2%203%u2218.%2C3%3A%u2206%27Lucky%20Shot%21%27%20%u22C4%202%204%u2261%u2375%3A%u2206%27Close%20One%21%27%20%u22C4%20%u2206%27Try%20Again%21%27%7D%20%3F2/10&run) [Answer] # [Turtled](https://github.com/Destructible-Watermelon/turtl-d/), 164 bytes Once again, showcasing Turtlèd's balance between golfiness and verbosity for the simplest things (like incrementing a number), Turtlèd beats all but the golfing langs. ``` 6;11[*'|:'|>;<u]'|rrr'O8:'|u'|>;'|ddd'|l'|uuu<"|>":l'|u'|>11;'|?<:?;( #Try Again!#)(>#Close One!#)(|#Lucky Shot!#)(O#Hole in One!#)'o[|r][ u]dl[|l][ u]u@"-,r["+.r_] ``` ### [Try it online](http://turtled.tryitonline.net/#code=NjsxMVsqJ3w6J3w-Ozx1XSd8cnJyJ084Oid8dSd8PjsnfGRkZCd8bCd8dXV1PCJ8PiI6bCd8dSd8PjExOyd8Pzw6PzsoICNUcnkgQWdhaW4hIykoPiNDbG9zZSBPbmUhIykofCNMdWNreSBTaG90ISMpKE8jSG9sZSBpbiBPbmUhIyknb1t8cl1bIHVdZGxbfGxdWyB1XXVAIi0sclsiKy5yX10&input=Mwo0) Note that it is half zero indexed and half one indexed; x is one indexed, y is zero indexed; 3,3 is a hole in one [Answer] # R, ~~230~~ 226 bytes ``` M=matrix("|",10,10);M[2:9,]=" ";M[34]="0";M[4,2:3]="f";M[15]=">";function(x,y){m=switch(M[y,x],">"="Close One","f"="Lucky Shot","0"="Hole In One","Try again");M[y,x]="o";cat(m,"!\n",sep="");cat(gsub("f","|",M),sep="",fill=10)} ``` Thanks to @billywob for -2 bytes, noticing `M[a,b]` is equivalent to `M[c]` in a couple of cases. Annoyingly, the two `cat` calls (!) can't be con`cat`enated into one, since the `fill` argument messes up the message. Argh! ]
[Question] [ I have a simple task that should be relatively easy to implement by means of code. **Your goal** is to write a program that will output the time written in Spanish, given the time in HH:MM format. Many people likely don't know *how* to do this, so I will elaborate. Time in Spanish is fairly logical. It usually follows the pattern of "Es la/Son las (hour) y (minutes)." Hours are in a 12-hour format, and "Es la" is **only used** if the hour is 1 (i.e. one o'clock). The minutes are a different story. If the minute is less than 30, then it is represented as shown above. If the minute is over 30, however, then the hour is rounded up and the minute is subtracted. For example, 7:35 is translated to the equivalent of "8 hours minus 25 minutes." Some more examples will be given below. The list of Spanish numbers that are necessary can be found [here](http://www.spanishclassonline.com/vocabulary/numbers0to30.htm). There are accents on some numbers, but these are not necessary. **Note:** The source says "uno," but to be grammatically correct it should be "una." This shouldn't affect any answers so far. **Note 2:** Also, "cero" is not necessary. If your program outputs "Es la una" or "Son las tres," that is fine with me. Sorry for these rule changes. ## Rules * Input will be provided through STDIN or the equivalent in your language. * No reading from outside libraries. * Your code can do anything with invalid input. ## Bonuses * -10 if your code adds these extra phrases - "y cuarto" for :15, "y media" for :30, and "menos cuarto" for :45 (rounded up). * -15 if your code can handle A.M. and P.M., responding with "de la mañana" and "de la tarde," accordingly. * -15 if your code can translate the current time if no input is provided. ## Scoring * This is a code-golf challenge, and it will be scored by bytes, not characters. ## Examples Input: `8:10` Output: `Son las ocho y diez.` Input: `6:45` Output: `Son las siete menos quince (or cuarto).` Input: `1:29` Output: `Es la una y veintinueve.` Input: `12:55` Output: `Es la una menos cinco.` Let me know if there is anything to specify here. This is my first question, so it is definitely not perfect. [Answer] # JavaScript (ES6) 308 ~~316~~ **Edit2** bug fix **Edit** forgot to claim the bonus As a program with I/O via popup ``` s='media0uno0dos0tres0cuatro0cinco0seis0siete0ocho0nueve0diez0once0doce0trece0catorce0cuarto0dieci0veint'.split(0), N=n=>n<16?s[n]:n<20?s[16]+s[n-10]:n>29?s[0]:s[17]+(n>20?'i'+s[n-20]:'e'), [h,m]=prompt().split(':'), alert(((h=(10-~h+(m>30))%12)?'Son las '+N(1+h):'Es la una')+(m>30?' menos '+N(60-m):-m?' y '+N(~~m):'')) ``` As a testable function ``` F=t=>( s='media0uno0dos0tres0cuatro0cinco0seis0siete0ocho0nueve0diez0once0doce0trece0catorce0cuarto0dieci0veint'.split(0), N=n=>n<16?s[n]:n<20?s[16]+s[n-10]:n>29?s[0]:s[17]+(n>20?'i'+s[n-20]:'e'), [h,m]=t.split(':'), ((h=(10-~h+(m>30))%12)?'Son las '+N(1+h):'Es la una')+(m>30?' menos '+N(60-m):-m?' y '+N(~~m):'') ) ``` **Test** In FireFox/FireBug console ``` for(i=0;i<13;i++) { console.log(F(i+':'+i)+'. '+F(i+':'+(i+15))+'. '+F(i+':'+(i+30))+'. '+F(i+':'+(i+45))) } ``` *Output* ``` Son las doce. Son las doce y cuarto. Son las doce y media. Es la una menos cuarto Es la una y uno. Es la una y dieciseis. Son las dos menos veintinueve. Son las dos menos catorce Son las dos y dos. Son las dos y diecisiete. Son las tres menos veintiocho. Son las tres menos trece Son las tres y tres. Son las tres y dieciocho. Son las cuatro menos veintisiete. Son las cuatro menos doce Son las cuatro y cuatro. Son las cuatro y diecinueve. Son las cinco menos veintiseis. Son las cinco menos once Son las cinco y cinco. Son las cinco y veinte. Son las seis menos veinticinco. Son las seis menos diez Son las seis y seis. Son las seis y veintiuno. Son las siete menos veinticuatro. Son las siete menos nueve Son las siete y siete. Son las siete y veintidos. Son las ocho menos veintitres. Son las ocho menos ocho Son las ocho y ocho. Son las ocho y veintitres. Son las nueve menos veintidos. Son las nueve menos siete Son las nueve y nueve. Son las nueve y veinticuatro. Son las diez menos veintiuno. Son las diez menos seis Son las diez y diez. Son las diez y veinticinco. Son las once menos veinte. Son las once menos cinco Son las once y once. Son las once y veintiseis. Son las doce menos diecinueve. Son las doce menos cuatro Son las doce y doce. Son las doce y veintisiete. Es la una menos dieciocho. Es la una menos tres ``` [Answer] Yes, the least expected language to appear on a golf contest, coded by the world's worst golfer, is back! ## Java - 676 bytes (716-10-15-15) Golfed: ``` class A{void main(String[]a){java.util.Calendar c=java.util.Calendar.getInstance();int h,m;String s="";h=c.get(c.HOUR);m=c.get(c.MINUTE);String[]e={"doce","una","dos","tres","quatro","cinco","ses","siete","ocho","nueve","diez","once","doce","trece","catorce","quarto","çseís","çsiete","çocho","çnueve","xe","xiuno","xidós","xitrés","xiquatro","xicinco","xiséis","xisiete","xiocho","xinueve","media"};for(int i=0;++i<30;e[i]=e[i].replace("ç","dieci"),e[i]=e[i].replace("x","vient"));s+=(h==1&m<30|h==12&m>30)?"Es la ":"Son las ";s+=(m<=30)?e[h]:(h==12&m>30)?e[1]:e[h+1];s+=(m==0)?" certas":(m<=30)?" y "+e[m]:" menos "+e[60-m];s+=(c.get(c.AM_PM)==0)?" de la mañana.":" de la tarde.";System.out.println(s);}} ``` Ungolfed: ``` public class A { public static void main(String[] a) { java.util.Calendar c = java.util.Calendar.getInstance(); int h, m; String s = ""; h = c.get(c.HOUR); m = c.get(c.MINUTE); String[] e = {"doce", "una", "dos", "tres", "quatro", "cinco", "ses", "siete", "ocho", "nueve", "diez", "once", "doce", "trece", "catorce", "quarto", "çseís", "çsiete", "çocho", "çnueve", "xe", "xiuno", "xidós", "xitrés", "xiquatro", "xicinco", "xiséis", "xisiete", "xiocho", "xinueve", "media"}; for (int i = 0; ++i < 30; e[i] = e[i].replace("ç", "dieci"), e[i] = e[i].replace("x", "vient")); s += (h == 1 & m < 30 | h == 12 & m > 30) ? "Es la " : "Son las "; s += (m <= 30) ? e[h] : (h == 12 & m > 30) ? e[1] : e[h + 1]; s += (m == 0) ? " certas" : (m <= 30) ? " y " + e[m] : " menos " + e[60 - m]; s += (c.get(c.AM_PM) == 0) ? " de la mañana." : " de la tarde."; System.out.println(s); } } ``` Deals with the `quarto` and `media`, with the AM/PM and has no input. So I can claim all the bonuses, even though that, if I didn't implement those features, I'd have an even lower score, lol. *facepalms* [Answer] ## Python 3: 294 chars - 10 = 284 ``` h,m=map(int,input().split(':')) t="y" d="yunoydosytresycuatroycincoyseisysieteyochoynueveydiezyonceydoceytreceycatorceycuarto".split(t)*2 if m>30:h=h%12+1;m=60-m;t="menos" print(["Es la una","Son las "+d[h]][h>1],t,[d[m]or"cero",["dieci","veint"+'ei'[m>20],"media"][m//10-1]+d[m%10]][m>15]+".") ``` This gets the ten-point bonus for using "cuarto" and "media" We read the hours and minutes as `int`s. If the minutes are above 30, we move to the next hour, measure minutes away from 60, and change the conjunction to "menos". The list `d` has translations of Spanish numbers up to 15. We make `d[0]` be `''` to prevent things like "diecicero". This is done by awkwardly calling `split(' ')` with an initial space; the regular `split` would just ignore it. The zero-minute case is handled later. To get numbers above 15, we combine the tens-digit string with the appropriate one-digit string. `15` and `30` are written as "media" and "cuarto" at no cost. Python 3 saves one char net over Python 2: -4 for `input` instead of `raw_input`, +2 for parens in print, +1 for `//`. [Answer] # PHP, ~~351~~ ~~349~~ 360 - 15 = 345 Bytes ``` <?$a=split(~ß,~œšßБߛŒß‹šŒßœŠž‹ßœ–‘œßŒš–ŒßŒ–š‹šßœ—ß‘Šš‰šß›–š…ß‘œšß›œšß‹šœšßœž‹œšßŽŠ–‘œšß›–šœ–߉𖑋–ߋ𖑋ž)?><?=preg_filter(~Ð×ÑÔÖÅ×ÑÔÖК,'(($h=($1-($k=$2<31))%12+1)>1?~¬‘ß“žŒß:~ºŒß“žß).$a[$h].($k?~߆ß:~ß’š‘Œß).(($m=$k?$2+0:60-$2)<16?$a[$m]:($m<20?$a[16].$a[$m%10]:($m<21?viente:($m<30?$a[17].$a[$m%10]:$a[18])))).~Ñ',$_GET[0]?:date(~·Å–)); ``` This program is not command line: it takes input via $\_GET[0]. You may have to disable notices in your php.ini. Now comes with auto time with no input, thanks to Niet the Dark Absol. **Tricks used:** `~(...)` saves one byte by bitwise inverting a string, as you don't need quote marks as PHP usually assumes all ASCII from 0x80 to 0xFF is a string. `<?=preg_filter(...,...)`: The `<?=` is a shortcut for writing `<? echo`. `preg_filter()` usually applies replacements on a string using a regex, but we can use the depreciated /e modifier to evaluate the resulting string as PHP code. Hence, instead of having to split the input string into two separate variables, we can use backreferences ($1 and $2) on the matched input string, saving large amounts of bytes. [Answer] # C++: ~~474~~ ... ~~422~~ 411 bytes This version is redeeming the cuarto/media bonus (-10). ``` #include<cstdlib> #include<cstdio> int main(int u,char**v){char*b[]={"cero","una","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","once","doce","trece","catorce","cuarto","dieci","veinti","media",0,"veinte"};int h=atoi(v[1]),m=atoi(v[1]+2+(v[1][2]>57)),n=m>30,o;h=n?h%12+1:h;m=o=n?60-m:m;if(u=m>15&m!=20)o=m%10;printf("%s %s %s %s%s",h>1?"Son las":"Es la",b[h],n?"menos":"y",u?b[m/10+15]:"",b[o?o:m]);} ``` My first attempt ever at code golfing! Will try to improve it this weekend. Ungolfed: ``` #include<cstdlib> #include<cstdio> int main(int u,char**v) { char*b[]={"cero","una","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","once","doce","trece","catorce","cuarto","dieci","veinti","media",0,"veinte"}; int h=atoi(v[1]),m=atoi(v[1]+2+(v[1][2]>57)),n=m>30,o; h=n?h%12+1:h; m=o=n?60-m:m; if(u=m>15&m!=20)o=m%10; printf("%s %s %s %s%s",h>1?"Son las":"Es la",b[h],n?"menos":"y",u?b[m/10+15]:"",b[o?o:m]); } ``` [Answer] # Lua, 450 - 10 (cuarto/media) - 15 (manana/tarde) = 425 ``` n={'uno','dos','tres','cuatro','cinco','seis','siete','ocho','nueve','diez','once','doce','trece','catorce','cuarto',[20]='veinte',[30]='media'}for i=1,9 do n[i+10]=n[i+10]or'dieci'..n[i]n[i+20]='veinti'..n[i]end H,M=io.read():match('(%d+):(%d+)')H,M=H+0,M+0 X,Y='tarde',' y 'if H<12 then X='manana'end if M>30 then H,M,Y=H+1,60-M,' menos 'end H=(H-1)%12+1 S=H==1 and'es la una'or'son las '..n[H]if M>0 then S=S..Y..n[M]end S=S..' de la '..X print(S) ``` * Dropped 12 bytes by rewriting the generator for 21-29. * Dropped 1 more by replacing `H>=12` with `H<12` and switching the dependent expression around. * Dropped 4 more by polluting the global namespace from a function (evil, but in the interest of golfing :). * Fixed the regex, I forgot the colon. Doesn't change the byte count, however. * Fixed the case of zero minutes, swapped `table.concat` out for string ops, and added @edc65's suggestion, ultimately adding 22 bytes. * I am shamed. Pulling the `function` body out into the main chunk reduced the length by a whopping *15 bytes*. [Answer] # D - 484 bytes ``` import std.stdio,std.conv,std.string;void main(){auto n="cero una dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciséis diecisiete dieciocho diecinueve e iuno idos itres icuatro icinco iseis isiete iocho inueve treinta".split;auto p=stdin.readln()[0..$-1];int b=to!int(p[0..$-3]),a=to!int(p[$-2..$]);auto c=a;b=a>30?b+1:b;b%=12;a=a>30?60-a:a;writefln("%s %s %s %s", b==1||b==12?"Es la":"Son las",n[b],c>30?"menos":"y",(a/10==2?"vient":"")~n[a]);} ``` [Answer] # Python 3, 409 bytes ``` d='cero uno dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciseis diecisiete dieciocho diecinueve veinte xuno xdos xtres xcuatro xcinco xseis xsiete xocho xnueve treinta';d=str(d.replace('x','veinti')).split();t=input().split(':');i=int(t[1]);j=int(t[0]);print(["Son las","Es la"][1<(2*j+i/30)%24<=3],[d[[j%12+1,j][i<31]],'una'][j==1],'y'if i<31 else'menos',d[min(i,60-i)]) ``` [Answer] # Ruby, 313 (338 - 15 - 10) This solution translates the current time when no input was given and adds the three phrases "y cuarto", "y media" and "menos cuarto". ``` require'time' t,x,s=Time,$*[0],%w[cero una dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce cuarto] 1.upto(9){|i|i>5?s[10+i]="dieci"+s[i]:0;s[20+i]="veinti"+s[i]} s[20]="veinte" s<<"media" c=x ?t.parse(x):t.new h,m=c.hour%12,c.min m<31?(a=" y "):(h,m,a=h+1,60-m," menos ") $><<(h<2?"Es la ":"Son las ")+s[h]+a+s[m] ``` [Answer] # Bash 423 (433 - 10 = 423, removing diacritics and cuarto we could go down to 381) ``` IFS=: read h m s=y m=${m#0} [ $m -gt 30 ]&&h=$(($h+1))&&s=menos [ -z ${m%0} ]&&s=en&&m=punto n[0]=0 o[0]=0 S=" séis siete ocho nueve" n=(punto una dos trés cuatro cinco $S diez {on,do,tre,cator,quin}ce ${S// / dieci} veinte) n=($(eval echo "${n[@]}" veinti\$\{n[{1..9}]\})) n[3]=tres;n[6]=seis n=(${n[@]} media\ $(tac -s' '<<<${n[@]})) o=("${n[@]/q*/cuarto}") a=Son\ las [ $h = 1 ]&&a=Es\ la echo $a ${n[$h]/p*/cero} $s ${o[$m]/%a/o} ``` [Answer] # Perl - 297 - 10 + 1 = 288 (counting the `p` flag) Edit: thanks to @guifa, I can now claim a bonus :) ``` #!/usr/bin/perl -p sub n{($_=shift)%10?(once,doce,trece,catorce,cuarto)[$_>9?$_-11:5]||('',dieci,veinti)[$_/10].(0,un.pop,dos,tres,cuatro,cinco,seis,siete,ocho,nueve)[$_%10]:(cero,diez,veinte,media)[$_/10]}/:/;$a=$`%12;$b=$';$c=$b>30?(++$a,$b=60-$b,menos):'y';$_=($a-1?'Son las ':'Es la ').n($a,a)." $c ".n($b,o).'.' ``` Here is the same code in multiple lines for readability: ``` sub n { ($_ = shift) % 10 ? (once, doce, trece, catorce, cuarto)[$_ > 9 ? $_ -11 : 5] || ('', dieci, veinti)[$_ / 10] . (0, un.pop, dos, tres, cuatro, cinco, seis, siete, ocho, nueve)[$_ % 10] : (cero, diez, veinte, media)[$_ / 10] } /:/; $a = $` % 12; $b = $'; $c = $b > 30 ? (++$a, $b = 60 - $b, menos) : 'y'; $_ = ($a - 1 ? 'Son las ' : 'Es la ') . n($a, a) . " $c " . n($b, o) . '.' ``` [Answer] ## Scala 652 bytes - 25 ``` import java.util.Scanner object S extends App{val s=new Scanner(System.in).useDelimiter("[:\n]") var h=s.nextInt var m=s.nextInt if(m>30)m-=60 else h-=1 val n=m.abs h%=24 val p=h%12 val l=List("una","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","once","doce","trece","catorce","cuarto") val k=List("úno","dós","trés",l(3),l(4),"séis",l(6),"ócho",l(8)) println(s"""${if(p==0)"Es la"else"Son las"} ${l(p)} ${if(m>0)"y "else if(m<0)"menos "}${if(n==1)"uno"else if(n==0)""else if(n<=15)l(n-1) else if(n==30)"media"else if(n<20)"dieci"+k(n-11)else if(n==20)"veinte"else"veinti"+k(n-21)} de la ${if(h<12)"mañana"else"tarde"}.""")} ``` [Answer] # [Pyth](http://pyth.herokuapp.com): 277 a bunch more 234 - 10 (cuarto/media bonus) = 224 bytes Now reduced over 50 bytes from original! ``` =H" y "ANkmsdcz\:Kc"cero uno dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce cuarto veinte"dI>k30=k-60k=H" menos "=N?1qN12+N1)++?+"Son las "@KN>N1"Es la una"H??eKqk20?@Kk<k16+?"dieci"<k21+PeK\i@K%kT<k30"media" ``` Insanely long for Pyth but that's because there's some raw data. Can probably be golfed even further. Uses obvious technique of splitting task up into hours, y/menos, tens digit of minutes, and ones digit of minutes and then translates numbers using translation array and everything else using a crap-ton of ternaries. ``` =H" y " Set H to " y " A Double Assignment Nk The variables N and k (hours and mins) m cz\: Map input split by ":" sd Make both int Kc"..."d Set K to string split by spaces I>k30 If k>30 =k-60k Set k to 60-k =H" menos " Set k to menos instead of y =N Set N ? qN12 If N=12 1 Go back to one +N1 Increment N ) Close entire if block + Concat of hours and minutes + Concat hours and y/menos ? >N1 If hour greater than one + Concat of son las and hour "Son las " "Son las " @KN Index translation array for hour "Es la una" Else es la una H " y " or " menos " ? <k30 If minutes less than 30 ? qk20 If minutes is 20 ek Last element of array (veinte) ? <k16 Else check if minutes<16 @Kk Get minutes directly from array + Else tens and ones sum ? <k21 If minutes<21 "dieci" "dieci" +PeK\i Else get veinti from veinte @K%kT Ones digit of minutes "media" Else get "media" ``` ## Golfing History * 10 bytes - bonus, quince and trienta can just be replaced in translation array so no changes required except translation essay and its same size. * 6 bytes - reorganized ternaries - unfortunately this removed the 4 consecutive ternary operators :( * 6 bytes - other various golfing * 6 bytes - golfed initial hour/min assignment * +3 bytes - fixed uno/una * 3 bytes - constructed veinti from veinte, not hardcoded * 18 bytes - extracted dieci from teens<16 * 2 bytes - removed some spaces in there for no reason * 2 bytes - used \ for one char strings ]
[Question] [ # Task A date can be compactly represented in a 6-character string in the format `ddmmyy` where the first two characters (`dd`) represent a day, the 3rd and 4th characters (`mm`) represent a month and the last two characters (`yy`) represent a `20XX` year. Given a string with 6 characters in `[0-9]` determine if it represents a valid date. But because today (the day this was posted) is April Fools' day, we will have a twist in the way dates work: ## April Fools' dates We will pretend every 30-day month has 31 days and every 31-day month has 30 days. Furthermore, in years when February is supposed to have 29 days we will pretend February only has 28 days and in all the other years we will pretend February has 29 days; i.e.: * months `01`, `03`, `05`, `07`, `08`, `10` and `12` have `30` days; * months `04`, `06`, `09` and `11` have `31` days; * February has `28` days if the year `yy` is a multiple of `4`, otherwise February has `29` days (let us assume we are in the year `20yy`); # Input An integer in `[0 - 311299]` or a 0-padded string representation of such an integer. # Output A Truthy value if the input corresponds to a date as per the April Fools' dates, Falsy otherwise. # Test cases [Python naïve implementation](https://tio.run/##ZZRRb5swFIXf@RVXVNOIRCXbQMDRUmkvlfbet7SKSHAKkoHINu1Q1d@eXTv0ttukBI4@m3N9Lsbn2bXjkF0ujTpBZ/ed2xtVaz3vm9qpxK42EUADW@gGl9jdRjytEPQExCYPZCaSbwLA3w08tJ2FZlR2@O5AvagBjmOv4KhHq8CNcFDd8Aw1aPVca/AVfbnuBMPosOpo8HIHGffKo96LHhEXfiKAUW4yA9zX2qpoKamMwiQ4HytPBwceXF17@LHFR6EeGjRGLaq/bB7MtLj86s9a9Wpw4FoFr6ozDZhJKwvq91l3x87p@cNziz4bfOaEazupg5lqM391PYyjTpImzJOrUDyZ4RvkK98npYNJN8COp5ClUKRQplClwBn@xdOHtV/IZCf/brAjt009Qz8OrrVfa4VUGQu@VvlHX1vs6osyviVandy/eS9OWbc/1hazbWEX3QDDFzHbKGaMFZzHaVDroG7gp9ZL2RTa7rmFWdXGTy4YlzJMLpiQ1aIyWQa1ZrlcB1WyQhZBcbaWuVecsVJmQRWsksIrwZiUobgoOJMsjFacV9caGRdVFRZ03w1h68wp1LS2KM7QlAX3oIpFcWKcmCAmiGXEMmI5sZxYQawgtia2JlYSK4lVxCpikpj8YJxycMrBKQenHJxycMrBKQenHJxy8GsO7OGya8HvBWyeqLAVoeVBcVKCVEYqJ1WQWpMqSYUtISQ5S3KW5CzJWZKzJGdJzpKc5eL8FEVu3NvRONzF/qaaZJf8f6D5hKs0XK9fFSr/8X1@BXh6@YFxcikOnMPg1dmfFWfjT7lT/Bi/4eD7Ywy3d/CGk9/j1eUP) for your convenience. ``` "000511" -> False "000611" -> False "290200" -> False "290204" -> False "290208" -> False "310004" -> False "310005" -> False "310104" -> False "310105" -> False "310204" -> False "310205" -> False "310304" -> False "310305" -> False "310504" -> False "310505" -> False "310704" -> False "310705" -> False "310804" -> False "310805" -> False "311004" -> False "311005" -> False "311204" -> False "311205" -> False "311304" -> False "311305" -> False "311404" -> False "311405" -> False "010694" -> True "031288" -> True "050199" -> True "050298" -> True "050397" -> True "060496" -> True "070595" -> True "100793" -> True "150892" -> True "181189" -> True "200991" -> True "251090" -> True "280200" -> True "280201" -> True "280202" -> True "280203" -> True "280204" -> True "280205" -> True "280206" -> True "280207" -> True "280208" -> True "290201" -> True "290202" -> True "290203" -> True "290205" -> True "290206" -> True "290207" -> True "310404" -> True "310405" -> True "310604" -> True "310605" -> True "310904" -> True "310905" -> True "311104" -> True "311105" -> True ``` This challenge was inspired by [this one](https://codegolf.stackexchange.com/q/200086/75323). --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your feedback. Happy golfing! [Answer] # JavaScript (ES6), ~~62 60~~ 59 bytes Takes input as a 0-padded string. Returns \$0\$ for *false* or a positive integer for *true*. ``` s=>(m=s[2]+s[3])<13&31-(m^2?~m%9%2:s%4?1:2)>(s/=1e4)&&~~s*m ``` [Try it online!](https://tio.run/##jdPfSgJBFAbwe59iEnR3S23O/NmdY60SVBAFPcC2gdhairqxY1366mYSFc130dXCj4@POXtmFpP3iZ8289dNf10/VbtZvvP5KF7lvlDliS90mZyT7mrqx6tHNd6uOtxRQ98xYxqqZBT705wqk3S7260/Xu3OipYQhWhLKS1Ruydmk6WvRNn75hQw7f3/LK0k5j1vmrdK/GbFDrHmLORUGk5DzqRlGzLJlE3A@wNmrEO20rEKWEnJTCFbkizDEkfkwJSalAun1J//ygS/6sAWMeE04bTCaYXTGqc1Thtp0DhGWsQWd1vcneLuFHdnuDvD3Q6nHU4zPgnDkxDeJeFdEsFuItyNd0l4l4R3SXiXZHDagLRy@@sTXvsDE2aFWWM2mC3mFHOGOXyAir/G@TMl43EYj8N4HIYP8MAWp1PMGWb3090qW4NZ3VxNpi9xXPieaMpE5CMxrde@XlaDZf184Fnsk544Ovr8ijwXjRiL6P42EkMRXV/c3F1dRuVgUc/XcfSwiZIk2X0A "JavaScript (Node.js) – Try It Online") or [Check all possible outputs](https://tio.run/##VU/LbsIwELzzFUMkUruYEDu05WW4cewlR0SlNHGACifIDqWogl@nCxKHHnZ3drSj2fnKvjOfu@2@6VV1Ya6lvno9Y1b7pVp1/TJZ8alMwkT2mP1Q84vtjDpq7DuDuRwrPmO@r6UZ8DC8XPyzvS6g4aFn@G0BS4FCwAqcVkT3WRTxR/Uj82Ny5nlksz17P9hP4/iENM40B1fBYoYYYUhgqiHVDRYPrrhxzEJrKMxxQgcDmmqEMdSQWmWOSE3DllIgEXgReBMYCsiYSq14tMk8s5w0SUzniSTrc6tV1o5V9Gk8QXWzSKRUoxEt3S6/B6JkqKKmThu3rdaMR/usSJvMNexV4Cl@uifYlqzdLika2hoLmqRFXle@3ploV69ZsMi2O1OA7BCgC88naDauPiIwztUumOBM7/yTpIc8N963A379Aw) against an ungolfed implementation ### Commented ``` s => // s = input string (m = s[2] + s[3]) // m = month, as a string < 13 & // make sure that m is less than 13 31 - ( // compute the upper bound for this month: m ^ 2 ? // if the month is not February: ~m % 9 % 2 // use either 31 or 32 : // else: s % 4 ? // if this is not a leap year: 1 // use 30 : // else: 2 // use 29 ) // end of upper bound computation > (s /= 1e4) // make sure that it's greater than the day && ~~s * m // and finally make sure that day * month is not zero ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~77~~ ~~67~~ ~~65~~ ~~62~~ 61 bytes *-2 bytes thanks to @Bubbler* *-3 bytes thanks to @xnor* *-1 byte thanks to @PoonLevi's mod by float trick* ``` lambda s:13>(m:=s//100%100)>0<s//1e4<30-[s%4<1,m%-1.76][m!=2] ``` [Try it online!](https://tio.run/##ZdPBjtowEIDhe57CtYQWpMB67NixEeHYJ@iNcmAhqJFIsOIgdVX12akT1NaZOSCRLz92xgr@c/hx75T1/fNafX/eTu3H5cTCFtR@2W6r8P4OQiziZ7UXu/GqLnZKrA9hUewgbxdr2JTmeGi/VPL4bFp/7wcWPkOW@b7phiVvOv8YGFvv2f0xxK@H@qevz0N9OfJVdr337NZ0NWu68UebMFyabpsxFnJ2ZhVrT34Zhj563/h8SjfB35q47rgiX63GNobhlSzf@NtIr73jInysclZ3l4rzv/F07392jRc5u/LDr/Pv@FBPLoTQANMOX0@3UGejmLlIJ6QQRAoiNhUVz3HeTKKRAGmANJI0kjSKNIo0mjSaNCVpStJY0ljcAJkdyOxA5gIyF5C5gMwFBWmKeRPP1LhX861/jKBAWpuCFuDcHKRDhXJlCkYUzqQQT8rpBOLIpVMpaGGdTMEC2HTb@KI5ByloEE6kYP@9jQkABolBYSgwaAwGQ4khPaDpLwAYJAaFQWMwGNJt48tWzB59Aj0HgwuDC4cLhwoAVAAkxR8 "Python 3.8 (pre-release) – Try It Online") **Input**: Date as an integer. **Output**: `True` or `False` if the date is valid or invalid respectively. **How**: Overall approach: return `13 > m > 0 < d < max_date_of_month` where `d, m` are date and month respectively. The max date of month `m` is calculated as: * If `m==2`: `30-(s%4<1)` evaluates to `29` if the year is divisible by 4, and `30` otherwise. Since the year is the last 2 digits of the input, input mod 4 is the same as the year mod 4. * If `m!=2`: `30-m%-1.76` evaluates to `31.xxx` or `30.xxx` --- ### Old solution ### [Python 3.8](https://docs.python.org/3.8/), ~~86~~ ~~83~~ 71 bytes ``` lambda s:13>(m:=s//100%100)>0<s//1e4<29+[s%4>0,([3,2]*7)[m+m//8]][m!=2] ``` [Try it online!](https://tio.run/##ZdPRbpswFIDhe57Cs1QVVtr42BjsqORyT7A7ykWWEA0pEISJtKrqs6eGaJs55yJS@PhjcywyvE@/L70yw3g7lW@38777ddwztwW1i7tt6TYbEOLBf5KdeJ2vmuxV2qfKPWQ7kcaVSmX9vUiq7qnbbExdV923Uta3thsu48Tcu4uiYWz7KeZtP1wnxp537HKd/Neq@TM0h6k51jyJTpeRndu@YW0//@jFTce230aMuZQdWMm6/RC7afQ@tkO6pC9uOLd@3XlFniRz60N3T@JH/jjTfW@/CJ@rlDX9seT8b7zc@5@d/EXKTrz6OHz6h7pxIYQGWHb4sT@7JpolX4u0QgpBJCNiQlH@RNfNIhoJkAZII0kjSaNIo0ijSaNJU5CmII0hjcENkNmBzA5kLiBzAZkLyFyQkSZbN/5Mc3tvfo7XGRRIY0LQAqxdg7SoULYIIReZzUPwJ2V1AH7kwqoQtDBWhmAATLitf9GshRA0CCtCMP/exgAAg8SgMGQYNIYcQ4EhPKDlLwAYJAaFQWPIMYTb@pctWz36AnoNOS5yXFhcWFQAoAIgKL4A "Python 3.8 (pre-release) – Try It Online") **Input**: Date as an integer. **Output**: `True` or `False` if the date is valid or invalid respectively. **How**: `([3,2]*7)[m+m//8]` first creates a list storing the `max_date + 1` for each month (except February) by repeating `[3, 2]` a few times. If the month is August or after, the pattern switches, so we add 1 to the index. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~96~~ ~~93~~ ~~91~~ 81 bytes ``` ^(?!(..)?00|..[2-9]|..1[3-9]|31(?!0[469]|11)|3002|2902([02468][048]|[13579][26])) ``` [Try it online!](https://tio.run/##RZG7TsUwEER7/wUFUlIQzaxfu9Ut@QgrCAoKGgpEmX@/2AwS1fFRMtaR/PX@/fH5dn/cnl/vL9vtYTuO/QZcxzHsKc5JjrwOmfMrRmnzTO5XBuyygG0DVpqfA8XPazDXHuewdu77/Q6gkmmiTXDyH6hgxIKFL@ToCQ0lWkJHjZpAtChr0CMnVnhYMiCCySoRSHTS5y2Z5p7yursIdYEyykxmsizLsiIrsiqrsiZrsi7rMpe5LGTxa1QL1UK1UC1UC9VCtVAtVAtXi/nMhUDBhCwU4e/PJnTB03qhNQ/NQ/PQPDQPzUPz0HzBfwA "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 3 bytes thanks to @mathjunkie. Saved 2 bytes thanks to @ThomasAyoub. Saved a further 10 bytes thanks to @ThomasAyoub for noting that the day cannot be greater than 31. Explanation: ``` ^ ``` Match only at the beginning of the string. ``` (?!...) ``` Invert the condition so we're now looking for invalid dates. The invalidity conditions (separated by `|` in the original code) are as follows: ``` (..)?00 ``` Either the day or month are zero. ``` ..[2-9] ``` The month is 20 or higher. ``` ..1[3-9] ``` The month is between 13 and 19. ``` 31(?!0[469]|11) ``` The day is 31 and the month is not 4, 6, 9 or 11. ``` 3002 ``` February 30th. ``` 2902([02468][048]|[13579][26]) ``` February 29th on a leap year. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ɠ⁽¿ÇB31_+2¦4ḍ~ƊR;€"J$ḅ³Fċ:³$ ``` A full program accepting a single integer from STDIN which prints a `1` or `0` to STDOUT. **[Try it online!](https://tio.run/##ATsAxP9qZWxsef//xpPigb3Cv8OHQjMxXysywqY04biNfsaKUjvigqwiSiThuIXCs0bEizrCsyT//zI5MDIwNw "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##LZA9ToMxEER7HwOlo9lZ/@1CR0FByQWoaFAuQIMEAiEFUXEDCiq6NKFAkQzKPb5c5MPOUNjPT7J2NXNzvVzezvPubX//3bY/z2cRV8faPtK0eb3brS5P9w@fRxeLafPU1ue/LydtvZjb@/T1uEDbzhkIpR91UREiERYiRLodkAdAA01pSou0SMu0TKu0SjOaHQzcAG4AZ4IzwZngTCRa6gYpPkTNQha491t9vKPXUCR5CX2bj59SPQZkMdcAA8xDj@reQ2eI99DG7AMglIhEIjJRiEoYy/pvUIlIZKIQdYRmBklsotAKzWnOtOy6I/8B "Jelly – Try It Online"). ### How? ``` Ɠ⁽¿ÇB31_+2¦4ḍ~ƊR;€"J$ḅ³Fċ:³$ - Main Link Ɠ - set the chain's left argument, N, to evaluated STDIN ⁽¿Ç - base 250 integer = 3765 B - to binary = [1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1] 31_ - 31 minus = [30,30,30,31,30,31,30,30,31,30,31,30] Ɗ - last three links as a monad - f(N): 4ḍ - four divides (N)? ~ - bitwise NOT (0 becomes -1 and 1 becomes -2) ¦ - sparse application... 2 - ...to indices: [2] + - ...action: add i.e. x=9 or 8: [30,2x,30,31,30,31,30,30,31,30,31,30] R - range (vectorises) = [[1,2,...30],...] $ - last two links as a monad - f(that): J - range of length = [1,2,...,12] " - zip with: ;€ - concatenate each -> [[[1,1],[2,1],...,[30,1]],...] ḅ - convert from base (vectroises): ³ - 100 -> [[101,201,...,3001],...] F - flatten ċ - count occurrences of: $ - last two links as a monad - f(N): : - (N) integer divide: ³ - 100 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2ô¨Ðθ©13‹sĀPr`2QiI4Ö≠ë®7(%ÉÌ}29+‹P ``` Just an initial answer. Can definitely be golfed by a few bytes. Inspired by both [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/202893/52210) and [*@SurculoseSputum*'s Python answer](https://codegolf.stackexchange.com/a/202915/52210), so make sure to upvote them!! [Try it online](https://tio.run/##AUAAv/9vc2FiaWX//zLDtMKow5AxM@KAuXPEgMKrUHNgw5AyUWlJNMOW4omgPsOrOSXDiX0zMc6x4oC5UP//MDEwNjk0) or [verify all test cases](https://tio.run/##PZG9SgNREIVfJSwIiilm5v5OlVeItQoqWKQSDAS2EFIJAQuxsLZUBCsLbfda@xD7Iuud3Ry7j487nLlnbtaXV6vrYdMumll//zRrFu0g5bN7LY@/X90bu377vf7ZLm8v5GTV@vLc717Ke/eRDg/KrjzciR7XF8thfnQ2nDZEFJibuUEcQZSECOABuYLj@soDwgQMwzACIzAOxsEEmACTYBJMhsl7w0hnpDOyGFmMLEYWexg/mrpoVDPkWLL9qy7BqhOI7o3TZBDJazSoa6mN1@ykziBQVjHIzNnGa2@qY4eBSccOM8o0YIAAHMADAiACEiDjFv9nEoADBEAEpKlDlEAe9UaYCKMwiupwXLbjnv8B). **Explanation:** ``` 2ô # Split the (implicit) input in parts of size 2: ddmmyy → [dd,mm,yy] ¨ # Remove the last item (the year): [dd,mm] Ð # Triplicate this # STACK: [[dd,mm],[dd,mm],[dd,mm]] θ # Pop and push the last item # STACK: [[dd,mm],[dd,mm],mm] © # Store the month in variable `®` (without popping) 13‹ # Check that it's smaller than 13 # STACK: [[dd,mm],[dd,mm],mm<13] s # Swap to get the triplicate value again # STACK: [[dd,mm],mm<13,[dd,mm]] ĀP # Check for both that they're not 0 # STACK: [[dd,mm],mm<13,(dd!=0)*(mm!=0)] r # Reverse the stack # STACK: [(dd>0)*(mm>0),mm<13,[dd,mm]] ` # Push both values separately to the stack # STACK: [(dd>0)*(mm>0),mm<13,dd,mm] 2Qi # If the month is 2: I4Ö≠ # Check that the input is NOT divisible by 4 # STACK: [(dd>0)*(mm>0),mm<13,dd,input%4>0] ë # Else: ®7(%É # Check that the month (from variable `®`) modulo -7 is odd # STACK: [(dd>0)*(mm>0),mm<13,dd,mm%-7%2>0] Ì # And increase this by 2 # STACK: [(dd>0)*(mm>0),mm<13,dd,(mm%-7%2>0)+2] }29+ # After the if-else: add 29 to this value # STACK: [(dd>0)*(mm>0),mm<13,dd,(input%4>0)+29] if mm == 2 # STACK: [(dd>0)*(mm>0),mm<13,dd,(mm%-7%2>0)+31] if mm != 2 ‹ # Check that the dd is smaller than this value # STACK: [(dd>0)*(mm>0),mm<13,dd<(input%4>0)+29] if mm == 2 # STACK: [(dd>0)*(mm>0),mm<13,dd<(mm%-7%2>0)+31] if mm != 2 P # And take the product of the stack to check if all are truthy # STACK: [(dd>0)*(mm>0)*(mm<13)*(dd<(input%4>0)+29)] if mm == 2 # STACK: [(dd>0)*(mm>0)*(mm<13)*(dd<(mm%-7%2>0)+31)] if mm != 2 # (after which this is output implicitly as result) ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~136~~ \$\cdots\$~~93~~ 78 bytes Takes the date as an integer and returns Truthy or Falsy. ``` lambda s,h=100:13>(m:=s//h%h)>0<s//h//h<(30-(s%4<1),31+(m in(4,6,9,11)))[m!=2] ``` [Try it online!](https://tio.run/##hZRPb@IwEMXv@RRepApbm6oz/hcPIhz7CXpre2B3QVQqFCXhUCE@O01ou8J5h0o5WD@/vHkej7x/7zZvO5f2zXldP51fl9s//5aqLTc1E83YLfR2Vrd3d5ubjVnQfFj131w7utXtjZ@zKR3/1lv1stO@jKWUzMaYx@2v2j6fu1XbtapWutATIgrMk1LdL1/blSk/URyhvir9jCgQi/TooTn8J1bSiDipMhLJS8xIRUFCRpii@GvSl6/EZSRQEntNLJEIZyQwCWV/JeaUZ3ZsU5bZDWf12VEvKIwRo4pRZVFlUeVQ5VDlyY@SegojEtApoFMEpwhOFTpV6JRQlVAlUE/G9Ri7zth15rETMzhhzxl7zthzxp6zR5UfqWzqrzSbswthIBaIA@KBBCARSAUkm2krXwmvQgtEFIgoEFFgoC8ogCgCqYCkKyNTNPVx2J6pw/TpYCt206/db@L/Tk/F@q1RXbnq3zp1edlmhRpet7V@2XW6M6ZQ@2ZYrifH7qRuF@rYntSxeWzrevV8mpjzBw "Python 3.8 (pre-release) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `Mbigint -p`, ~~76~~ 75 bytes ``` /(..)(..)/;$_=$1>0&&$1<substr 113130-($_%4?0:1).31323132313132313231,2*$2,2 ``` [Try it online!](https://tio.run/##ZZNbS8NAEIXf/RUlREklaWb2kuwYLwhSEBQEfbOltBCkUGptUtA/b9zWKpuZhyWbb8@eOZnsburtynbxtm52q/YqHr9mOK2afHKX529VvFxvdp7Oqi5PRqPhfuRVPLuK8RrOzmK8bHaLpt0OEDVqyJJ4dmpu4AKHI/@ujuN/lqrzWKWqq5r5V5Rlk/Wv/6Q9lveT/VhM2ihNxrf3D@nT7fPz8PW4PKg/kvF81dRp8rLd1cNPrfzabDpNo4uo6iKwgETRILse7NdP9kCR6wNNZQgKMFSEoARLNgQIBZkAIEBJOgQWHKkAKAAiDIFFIAi3OETXS6pRuTCp9mXgt@zhk4/EMoJCg0KjhEYJjRYaLTQGTD@gAdsHVrhY4VJwl4K7lMKlFC5OaJzQEK9ErBKKDqPoMCJzQeQuor8o@ouivyj6i0ZoTF@jnP9z4TE6AORAcaA5MBxYDgoOSg7Cw6roP9hfVOLJiCcjnoz4ST0QyyUFByUHLjTxl6ZHvt837fJ93XTZox352@Kfi@Xbct122WbVZfMf "Perl 5 – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 74 bytes ``` n->{int m=n/100%100;return(m==2?n%4<1?2:1:~m%9%2)<31-(n/=1e4)&13>m&n*m>0;} ``` [Try it online!](https://tio.run/##LZLBbqMwEIbvfQqrEhVUhHpsDDgp6XkPK63UY9UDm0BFNpgITKVVlH317AA/kv3pG@EZe@xT9V1tTsc/97a79IMXJ/Zk8u05aSZ38G3vkufdZfp9bg/icK7GUfysWndFZPSVZ3z37VF0HA/f/dC6r4/Pavgao@sP538N9bE9VL4WTXl3m/21dV50pXshKQMeu6H20@DCrizVmwvSV3pTW9r@6wIbqOhV0yZ0LyXVafREet89ueduL3e3@@5B8MfJPj59PfqxvBqiOOOhrFRSrkhjsbCIheZisy80CwlOcAVXcA3XcAM38Byewwt4sTqhHqEeIT8hPyE/IT@l8HR2QTKz7BxQBe9fGEnWLlR2dW1zZiZTmzF5F5bXcbXcaqaRhVXMgqjgddwTa4lpSFrJLJY2rSRQgRpMQQNmYA4W6C@BCtSgATMwX/qDc8oUfcvgGdzCLfqCe2IacVsvvukHEc5Pab787TKP0fvf0ddd0k8@ufAz9E34GMjsuBXBGLjHeP4pbpIZ4TxF0Zzr9nC7/wc "Java (JDK) – Try It Online") ## Credits * -1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) * -3 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~95~~ \$\cdots\$ ~~71~~ 65 bytes Saved ~~3~~ 4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! Saved a whopping 15 bytes thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%c3%a9goire)!!! Saved 6 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! Takes the date as an integer and returns \$0\$ or \$1\$. ``` m;f(s){m=s/100%100;s=m<13&(m-2?~m%9%2-1:s%4<1)+(s/=1e4)<30&&s*m;} ``` [Try it online!](https://tio.run/##jZPNboMwEITveQorEhFuQPEaDN4C7YO0OVT5qTiQRHEOVaP01dOFTKtUVX8kw/jD6/HYMov0ebE4n7tqHQd97JowI2MiearQdDVlk7hL7f1bF3FkU7oNUV6TnsZh1tAq13VmJpNw01Wnc/fUbmJ9HLWbgzqswiE8zFWjjo4oUUX/Ek9zrc4Qcy@WfS8Zl1Jpci4SVRrHri8tOB9mlJyJOuPZJsoawywO1pFhI989kRerjKz3vcgKOdQNSmACW7AFZ@AMnINzsAM7cAEuwCW4BHuwBzOYL0zIR8hHyEfIR8hHyEfIR8hHyEdDPutlHwZKUAvNoDn0o76AllA5N8vwYfgwfBg@DB@GD8OH4dOrP1Wj4Q6sXnaXGyCOn43@0cwP7Xr0e@Xvo3@ubn7q99tZb/dxv6VWtmMqkVqF9nW1XcfDRdczkNToSk2nrR6p3V5oHY@jpUrvlLzjaKkfN@MEP0c7TxTmS19/AdU0w/FJtxqdzu8 "C (gcc) – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, ~~86~~ ~~85~~ ~~83~~ 82 bytes ``` a=0424343443434;fold -2|xargs|(read d m y;date -d${a:${m#0}:1}/$d/0$[!(${y#0}%4)]) ``` [Try it online!](https://tio.run/##XZFdb9owFIbv8yveQYZAaotPvohb0V3ttqp2h7pKdbFLokGCklBApb@d2Q5nk6pI0ZMnjt/jN6@qLc5D/DJKw6hlgc60Hcpqu@ugKo2uMFjWTWPabV3pslpBm7ZsjEa96@yimyAI9kW5NmjcFgccA0DX9gaYZVFjEB4GOOG3N8A4CGzarvIbb5t61agN6v7xf/TNWc1FEiWxvfzt7q1ea1xHp4NqVu1p7MM0NjjeadUZXOvwQ92GH5uh@Lylz2mopyJ8@jYOP47WfE8mz5NzP8AEo3tMtXmfVrv12k3z2JRV92UAhIcrr/pTIvxx5etYTB/wqlp3/Ar7wtglDR9F75b/asFGdcvCtP7d18aG@OmaXpeVQVvUO3syY/fel10BhQXKN5h30xy7wvVdttjXzR@Ltuv@DFws5vd2Mrw8ITxi7vAZo1H/eoHTqaeHl4H/J5UJzkKIlAgUWMg8RFJEQjAkDLmFmOyqhCHtgdgQm4hNxCZmE7NJ2aRsZmxmbHI2@cUQpxOnE2cRZxFnEWdRwibxxg6ayQQiEDFFee4gFSRlD5G8mFjOHGQikZkDO5ZMLdjsmYwdpCKXkYOcKHef296kJAcpCSkc5L7MCxBDxBAzJAwpQ8YwY3CD@X9BDBFDzJAyZAzuc9th4iM8pD1kbDI2ko28GKKLIfLmLw "Bash – Try It Online") Input is on stdin. Output is the exit code: `0` for truthy, `1` for falsey. --- I thought I'd do a solution based on a date built-in, since I don't think anyone else has done that yet. This program takes the input string \$x\$ and computes another string \$y\$ with the property that \$x\$ is a valid "April Fools date" iff \$y\$ is a valid normal date. So GNU date applied to \$y\$ will give the desired answer. [Answer] # [Swift](https://swift.org) ~~279~~ ~~277~~ ~~272~~ ~~264~~ ~~262~~ ~~257~~ ~~256~~ ~~254~~ 252 bytes ``` func v(s:String)->Int{let m=Int(s.suffix(4).prefix(2))!;switch m{case 0,13...:return 0;case _:switch Int(s.prefix(2))!{case 1...28:return 1;case 29,30:return Int(s.suffix(4))!%4==0&&m==2 ?0:1;case 31:return[4,6,9,11].contains(m) ?1:0;case _:return 0}}} ``` My first and most probably failed attempt at code golf. Please be nice! Here is a more readable version: ``` func validDate(s :String) -> Int { let mm = Int(s.suffix(4).prefix(2))! switch mm { case 0,13...: return 0 case _: switch Int(s.prefix(2))! { case 1...28: return 1 case 29, 30: return Int(s.suffix(4))! % 4 == 0 && mm == 2 ? 0: 1 case 31: return[4,6,9,11].contains(mm) ? 1:0 case _: return 0 } } } ``` Any constructive feedback is welcome, negative feedback not so welcome. Link to project with swift tests on [Github](https://github.com/johannwerner/AprilFoolsGolfChallenge) **Updated solution** to make it work for console input # ~~288~~ ~~251~~ 249 bytes ``` let s=readLine()!;let m=Int(s.suffix(4).prefix(2))!;let d=Int(s.prefix(2))!;if m<0||m>13{print(0)};if(1...28).contains(d){print(1)}else if d==29||d==30{print(!(Int(s.suffix(4))!%4==0&&m==2))}else if d==31{print([4,6,9,11].contains(m))}else{print(0)} ``` [Try it online](https://tio.run/##XY7RCsIgFIZfZbtoeGCIbhZJ2X3QG0QXkQ6EaWMaBblnNwfCqqtz@M73c3731J1nMfbKF06M6ipP2ioE5W4mRhytRw67R9fpF2KAh1HNWwPZkNn45rorzJ6EYA60fQ@jTgKBKWFEMcbNFvDtbv1VW4ckZIHCpHqnipSVQjQ8hDRakq8l@usB5YoJQarKJBl@si3NoTOrNzWvKb0s/0x2l1oxkjWhnH8A) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 53 bytes ``` s=>`2${s&3&&1}2323223232`[s[2]+s[3]-1]>s/1e4-29&s>1e4 ``` [Try it online!](https://tio.run/##jdRvS8JQFAbw936Ka4TbSO2e@2e7p5gRZBAFfYA1UGyWIi52rTfRZ7c5IqT7vAhB5cfDwz0729bzj7lfNKu33WhbP1f7Zb73@WSmTj/9QA8G9KV0@@m@ZoUvVHnmC12OqJz4c6rMSPHAT9o/@8uiJ0QhTqSUluhkKJbzja9EOfzlFDC1/n@WVhJzy7vmvRLHrNgh1pyFnErDaciZtGxDJpmyCbg9YMY6ZCsdq4CVlMwUsiXJMixxRA5MqUm5cEp9uFYmuFQdW8SE04TTCqcVTmuc1jhtpEHjGGkRW9xtcXeKu1PcneHuDHc7nHY4zfgkDE9CeJeEd0kEu4lwN94l4V0S3iXhXZLBaQPSyrW3T3jbd0yYFWaN2WC2mFPMGebwAVT8M86fKRmPw3gcxuMwfAA7tjidYs4wu/Ade3hxHHGv7I2XdTOdL17juPBD0ZSJyCdiUW99vanGm/ql42Xsk6Ho9w@/Is9FI65E9HgfiQsR3V7fPUxvonK8rlfbOHraRUmS7L8B "JavaScript (Node.js) – Try It Online") [Answer] # [Raku](https://raku.org) (raku -n file-with-one-line) 118 Bytes ``` /(..)(.)(.)(..)/;$!=10*$1+$2;die if 12 <$!||1>$!;$!=7.5-abs(7.5-$!);$!=($!+|4)+^1 if $!!= 2;Date.new($3%4??0!!1,$!,$0) ``` Result as exit code (0: ok, 1: error) ]
[Question] [ Take a string, `s` containing printable ASCII-characters as input, and output its "binary split sum". Need an explanation? **How do you get the binary split sum?** We'll use the string `A4` as an example in the following explanation. * Convert the characters to binary, treating each letters as a 7-bit ASCII character ``` A -> ASCII 65 -> 1000001 4 -> ASCII 52 -> 0110100 ``` * Concatenate the binary numbers into a new binary number ``` A4 -> 1000001 & 0110100 -> 10000010110100 ``` * Split the new binary number into chunks, where no `1` can have a `0` to its left. You should not split consecutive `1`s. ``` 10000010110100 -> 100000, 10, 110, 100 ``` * Convert these binary numbers to decimal ``` 100000, 10, 110, 100 -> 32, 2, 6, 4 ``` * Take the sum of these numbers: ``` 32 + 2 + 6 + 4 = 44 ``` So, the output for the string `A4` should be `44`. --- **Test cases:** ``` a 49 A4 44 codegolf 570 Hello, World! 795 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~86~~ ~~81~~ 76 bytes -5 bytes thanks Adnan -5 bytes thanks xnor ``` s=0 for c in input():s=s*128+ord(c) print eval(bin(s).replace('01','0+0b1')) ``` [Try it online!](https://tio.run/nexus/python2#DcJBCoAgEADAu6/wtrsZodEhAg89Rc1AEBW1vm8NM5qW7M6VOx7Svzwd6Wi6TWrdRa4XOmKlhtS5f01EGxI2Wqov0TiPIBXMIIW0CojGgHODDw "Python 2 – TIO Nexus") `for c in input():s=s*128+ord(c)` to do the ASCII conversion numerically, where `*128` is used to left shift `s` 7 times (steps 1 and 2) `eval(('0'+new_bin).replace('01','0+0b1'))` to split and sum (steps 3, 4 and 5) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` Oḅ128BŒg;2/ḄS ``` [Try it online!](https://tio.run/nexus/jelly#@@//cEeroZGF09FJ6dZG@g93tAT/P9z@qGmN9///6onqOgrqjiYgMjk/JTU9PycNxPZIzcnJ11EIzy/KSVFUBwA "Jelly – TIO Nexus") ### How it works ``` Oḅ128BŒg;2/ḄS Main link. Argument: s (string) O Ordinal; map characters to their code points. ḅ128 Unbase 128; convert the resulting list from base 128 to integer. B Binary; Convert the resulting integer to base 2. Œg Group consecutive, equal bits. ;2/ Concatenate all non-overlapping pairs. Ḅ Unbinary; convert from base 2 to integer. S Take the sum. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 14 bytes ``` YB!'1+0*'XXZBs ``` [Try it online!](https://tio.run/nexus/matl#@x/ppKhuqG2gpR4REeVU/P@/enJ@Smp6fk6aOgA "MATL – TIO Nexus") ### Explanation Consider input `'A4'` as an example. ``` YB % Implicit input. Convert to binary using characters '0' and '1'. % Gives a char matrix, where each row corresponds to a number % STACK: ['1000001'; '0110100'] ! % Transpose. This is necessary because MATL uses column-major % order when linearizing a matrix into a vector % STACK: ['10'; '01'; '01'; '00'; '01'; '00'; '10'] '1+0*' % Push this string: regexp pattern % STACK: ['10'; '01'; '01'; '00'; '01'; '00'; '10'], '1+0*' XX % Regexp. Linearizes the first input into a row (in column-major % order), and pushes a cell array of substrings that match the % pattern given by the second input % STACK: {'100000'; '10'; 110'; '100'} ZB % Convert each string into a decimal number. Gives numeric vector % STACK: [32; 2; 6; 4] s % Sum. Implicitly display % STACK: 44 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes Code: ``` Çžy+b€¦JTR021:2¡CO ``` Explanation: ``` Ç # Take the ASCII value of each character žy+ # Add 128 to each value (to pad each with enough zeros) b # Convert to binary €¦ # Remove the first character J # Join the array TR021: # Replace 01 by 021 2¡ # Split on the number 2 C # Convert from binary to decimal O # Sum them all up ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@3@4/ei@Su2kR01rDi3zCgkyMDK0Mjq00Nn//3@P1JycfB2F8PyinBRFAA "05AB1E – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` Çžy+b€¦Jγ2ôJCO ``` A port of [my Jelly answer](https://codegolf.stackexchange.com/a/120601/53748), using the 128 offset from [Adnan's 05ab1e answer](https://codegolf.stackexchange.com/a/120594/53748) (rather than the 256 in the Jelly answer I wrote). **[Try it online!](https://tio.run/nexus/05ab1e#@3@4/ei@Su2kR01rDi3zOrfZ6PAWL2f///@T81NS0/Nz0gA "05AB1E – TIO Nexus")** ### How? ``` Çžy+b€¦Jγ2ôJCO Ç - to ordinals + - add žy - literal 128 b - to binary € - for each ¦ - dequeue J - join γ - group into chunks of equal elements ô - split into chunks of 2 - literal 2 J - join C - from binary O - sum ``` [Answer] ## JavaScript (ES6), ~~97~~ 92 bytes ``` s=>eval(s.replace(/./g,c=>(128+c.charCodeAt()).toString(2).slice(1)).replace(/1+/g,'+0b$&')) ``` Edit: Saved 5 bytes with some help from @ConorO'Brien. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~18~~ 12 bytes ``` c_¤ùT7Ãò< xÍ c_ // Firstly, take the input and map over it as charcodes. ¤ // Take the binary representation of each item ùT7 // and left-pad it with zeroes to standardize the items. à // After all of the above, ò< // partition the result where ever a 0 precedes a 1. xÍ // Then sum the numbers from base 2. ``` Takes input as a single string. I also tried out the 128 or 256 addition used by other answers, but 0-padding was shorter to use. Shaved off a whole whopping 6 bytes thanks to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions) and [Oliver](https://codegolf.stackexchange.com/users/61613/oliver). [Try it out here.](https://ethproductions.github.io/japt/?v=1.4.5&code=Y1+k+VQ3w/I8IHjN&input=IkE0Ig==) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to Dennis (no need to flatten by 1 when a full flatten is fine - replace `;/` with `F`) ``` O+⁹Bṫ€3FŒg;2/ḄS ``` **[Try it online!](https://tio.run/nexus/jelly#ASYA2f//TyvigblC4bmr4oKsM0bFkmc7Mi/huIRT////ImNvZGVnb2xmIg)** ### How? ``` O+⁹Bṫ€3FŒg;2/ḄS - Main link: list of characters, s e.g. "A4" O - cast to ordinal (vectorises) [65,52] ⁹ - literal 256 + - add (vectorises) [321, 308] B - convert to binary (vectorises) [[1,0,1,0,0,0,0,0,1],[1,0,0,1,1,0,1,0,0]] ṫ€3 - tail €ach from index 3 [[1,0,0,0,0,0,1],[0,1,1,0,1,0,0]] F - reduce with concatenation [1,0,0,0,0,0,1,0,1,1,0,1,0,0] Œg - group runs of equal elements [[1],[0,0,0,0,0],[1],[0],[1,1],[0],[1],[0,0]] ;2/ - pairwise reduce with concatenation [[1,0,0,0,0,0],[1,0],[1,1,0],[1,0,0]] Ḅ - convert from binary (vectorises) [32,2,6,4] S - sum 44 ``` [Answer] # PHP, 116 Bytes ``` for(;$c=ord($argn[$i++]);)$r.=sprintf("%07b",$c);$t=mb_split("(?<=0)(?=1)",$r);echo array_sum(array_map(bindec,$t)); ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/2430f87c492fe9886e8ace92c12115099adeac35) # PHP, 117 Bytes ``` for(;$c=ord($argn[$i++]);)$r.=sprintf("%07b",$c);$t=preg_split("#0\K(?=1)#",$r);echo array_sum(array_map(bindec,$t)); ``` [Try it online!](https://tio.run/nexus/php#JckxCsIwFADQvaeQNEI@LVInhxg6SAcRdHFTCWmapoE2Cb9xcPHqVXR78PZ1HGJmEANKNDFgct6ydyPPl@vx0ADPqELrBdGhMzaMPeFLH5BxqkXAjv32Rl1RPIADxY2YIzqfekbW1a4lJdXAaRIRjZVzHF1iJK/uJ1aLLeTfRuBGD2GlENVLzs@J/TWpyFrnO6NLmgD4snwA "PHP – TIO Nexus") # PHP, 120 Bytes ``` for(;$c=ord($argn[$i++]);)$r.=sprintf("%07b",$c);preg_match_all("#1+0+#",$r,$t);foreach($t[0]as$b)$s+=bindec($b);echo$s; ``` [Try it online!](https://tio.run/nexus/php#HcyxCsMgFEDRPZ9hX0ExlHTqYKVDydClXbqFIMYYFVKVp3N/PQ0dLwfu9ZZ9bixiQoU2J6whOvrt1fP1ftx7JhrQ6KIkJs3WpXUhYlsSUgFGJpzpXwcInI9MMMCTLBlDrAslx@4ykRYMExmtUx9djVd6XSk5nHnHD7thC5WJ/We18RTq0I26wMSgcDmFOFtD9xLW@ARFbNsP "PHP – TIO Nexus") or ``` for(;$c=ord($argn[$i++]);)$r.=sprintf("%07b",$c);preg_match_all("#1+0+#",$r,$t);echo array_sum(array_map(bindec,$t[0])); ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 21 bytes It's too long... ``` siR2:.BiCMQ128"1+0+"1 ``` [Test suite.](http://pyth.herokuapp.com/?code=siR2%3A.BiCMQ128%221%2B0%2B%221&test_suite=1&test_suite_input=%22a%22%0A%22A4%22%0A%22codegolf%22%0A%22Hello%2C+World%21%22&debug=0) [Answer] # [F#], ~~249~~ 245 bytes ``` open System let rec c a=function|[]->[a]|'0'::'1'::y->(a+"0")::(c""('1'::y))|x::y->c(a+string x)y let x i=c""(String.Join("",(Seq.map(fun c->Convert.ToString(int c,2).PadLeft(7,'0'))i))|>Seq.toList)|>Seq.map(fun c->Convert.ToInt32(c,2))|>Seq.sum ``` [Try it online!](https://tio.run/nexus/fs-mono#bZFRa8IwFIXf/RV3gWHC2uKcInZYkL1sw4dBhT2ID1l6K4GYdE0cEfrfu7QVhrg8BHK/c@894ZgKNeRn6/A4UuhA6urkLKxg14zg@hBOIpgtn2/q61kHZrdAmAIPRpUBzxeTW/6KSpkIPk2tirsgWizn15pm33amahQggK/KkxZOGt3s9nG24/tmPBmn6fgxXN7GGeUPZEJYmlJBCL2UGWv8gEXg1tVSH8Azb/vvepCrTpz39eTdSE0JiWiO38mRVzRsBBFnL0b/YO2SrRmEVGoHIpqy5IMXGywdXUTBC2MyrMu6Zmc20rrL499Jb9o9TWk35KKyp2O7rmt@TkpTc6Wg76F9IhGgr1A4LBjEGVA/BMVCUH9gyG7UZFAFk67UQLZoQ5oVtxaLFO6/SNu2vw "F# (Mono) – TIO Nexus") Note: the version on tio.run has "open System" in the header, I've added its count to the code above. I'm not sure what the rules are on imports. # Ungolfed ``` let rec convert acc = function | [] -> [acc] | '0'::'1'::xs -> (acc + "0") :: (convert "" ('1'::xs)) | x::xs -> convert (acc + string x) xs let calculateSum input = let binary = Seq.map (fun x -> Convert.ToString(int x, 2).PadLeft(7, '0')) input String.Join("", binary) |> Seq.toList |> convert "" |>Seq.map (fun x -> Convert.ToInt32(x, 2)) |>Seq.sum ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 60 bytes ``` ->s{s.bytes.map{"%07b"%_1}.join.scan(/1+0*/).sum{_1.to_i 2}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3bXTtiquL9ZIqS1KL9XITC6qVVA3Mk5RU4w1r9bLyM_P0ipMT8zT0DbUNtPQ19YpLc6vjDfVK8uMzFYxqayFmrCxQcItWcjRRioXwFyyA0AA) [Answer] # [Perl 6](http://perl6.org/), 62 bytes ``` {sum map {:2(~$_)},.comb».ord».fmt('%07b').join~~m:g/11*0*/} ``` [Answer] # [J](http://jsoftware.com/), 34 bytes ``` [:+/@(,#.;.1~1,1=2#.\,)(7#2)#:3&u: ``` [Try it online!](https://tio.run/nexus/j#@5@mYGulEG2lre@goaOsZ61nWGeoY2hrpKwXo6OpYa5spKlsZaxWasXFlZqcka@QpqCeqA5nOpog2Mn5Kanp@TlpCBGP1JycfB2F8PyinBRF9f//AQ "J – TIO Nexus") ## Explanation ``` [:+/@(,#.;.1~1,1=2#.\,)(7#2)#:3&u: Input: array of characters S 3&u: Get ASCII values of each character (7#2) Array with 7 copies of the value 2 #: Convert each value to a base 2 array with length 7 [: ( ) Operate on those binary values , Flatten it 2 \ For each infix of size 2 #. Convert it to decimal from binary 1= Test each value for equality to 1 1, Prepend a 1 , The flattened binary values ;.1~ Chop that at each occurrence of a 1 #. Convert each chop from binary to decimal +/@ Reduce by addition ``` [Answer] ## mathematica 193 bytes ``` f=FromDigits;l=Flatten;(S=Split@l@Table[PadLeft[IntegerDigits[ToCharacterCode@#,2][[k]],7],{k,StringLength@#}];Plus@@Table[f[RealDigits@f@Join[S[[i]],S[[i+1]]],2],{i,1,Length@S-1,2}]+Last@l@S)& ``` [Answer] # [J](http://jsoftware.com/), 40 bytes ``` +/>#.&.>(1,}.|.1 0 E.|.b)<;.1 b=.,#:a.i. ``` usage: ``` +/>#.&.>(1,}.|.1 0 E.|.b)<;.1 b=.,#:a.i.'A4' ``` returns 44 [Answer] ## Clojure, 150 bytes ``` #(loop[[c & C](for[i % j[64 32 16 8 4 2 1]](mod(quot(int i)j)2))p 0 r 0 R 0](if c(if(=(dec c)p 0)(recur C c 1(+ R r))(recur C c(+(* 2 r)c)R))(+ R r))) ``` Well I was hoping the conversion from ASCII to bytes was shorter than this. The actual loop body is quite short, using `r` to accumulate the current result and `R` to accumulate the total result. If the previous bit `p` is `0` and the current bit `c` is `1` then we split a new chunk and accumulate to `R`, otherwise we update the `r` and keep `R` as it was. [Answer] # **Python** 123 bytes ``` lambda w:sum(map(lambda x:int(x,2),"".join(map(lambda x:bin(ord(x))[2:].zfill(7),list(w))).replace("01","0:1").split(":"))) ``` Updated, thanks to Martin Ender. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 31 bytes **Solution:** ``` +/2/'_[;x]&x&~~':x:,/(7#2)\'`i$ ``` [Try it online!](https://tio.run/##y9bNz/7/X1vfSF89Ptq6IlatQq2uTt2qwkpHX8Nc2UgzRj0hU0UpOT8lNT0/J03p/38A "K (oK) – Try It Online") **Examples:** ``` +/2/'_[;x]&x&~~':x:,/(7#2)\'`i$,"a" 49 +/2/'_[;x]&x&~~':x:,/(7#2)\'`i$"A4" 44 +/2/'_[;x]&x&~~':x:,/(7#2)\'`i$"codegolf" 570 +/2/'_[;x]&x&~~':x:,/(7#2)\'`i$"Hello, World!" 795 ``` **Explanation:** Convert to ASCII values, convert to 7-bit binary, flatten, find where differs, and against original list to find where `1`s differ. Cut at these indices, convert back to decimal and sum up: ``` +/2/'_[;x]&x&~~':x:,/(7#2)\'`i$ / the solution `i$ / convert to integer (7#2) / draw from 2, 7 times => 2 2 2 2 2 2 2 \' / decode each (convert to binary) ,/ / flatten x: / save as x ~~': / not-not-each previous (differ) & / and with x / x & / indices where true _[;x] / projection, cut x at ... 2/' / encode each (convert from binary) +/ / sum up ``` **Bonus** Managed a **31 byte** version in [K4](http://kx.com/download/) too, but as there's no TIO for it I'm posting my oK solution. ``` +/2/:'_[;x]@&x&~~':x:,/1_'0b\:' ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 30 bytes ``` {+/2⊥¨(1∘+⊆⊢)∊¯7↑¨2⊥⍣¯1¨⎕UCS⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqbX2jR11LD63QMHzUMUP7UVfbo65Fmo86ug6tN3/UNvHQCpDso97Fh9YbHlrxqG9qqHPwo96ttUDNCuqJ6lxA0tEETCXnp6Sm5@ekgTkeqTk5@ToK4flFOSmK6gA "APL (Dyalog Unicode) – Try It Online") **How?** `⎕UCS⍵` - Unicodify `2⊥⍣¯1¨` - encode each in binary `¯7↑¨` - and pad to the left with zeros to 7 places `∊` - flatten `1∘+⊆⊢` - partition by self increased by one `2⊥¨` - decode each from binary `+/` - sum [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 73 bytes ``` [ [ "%07b"sprintf ] map-concat R/ (?<=0)(?=1)/ re-split [ bin> ] map Σ ] ``` [Try it online!](https://tio.run/##ZY/BSgMxEIbveYppQGjB3a6wZWlrWzypFw@KeCg9pOnsGoxJnEyhIj6N7@Mrrak5WPC/zA/fDPP/rdLsqX98uL27nkHr6VUxG9dBms9lUBSRst87o/0OIRAyvwcyjoGww0OAiG97dBrjnyvxwKQizIX4EJAklYRTDaBYQj3N7KqW/1md2fFp520rT9ikqTK8QWv9OTx5sruBzLCZTsSn6NewBnlWNVsZf8O2sElFQqG904rhfgzD1eWiGg1Xi4vROFUpYrCG09XWuGVehu8v2PRHE1npl7L/AQ "Factor – Try It Online") * `[ "%07b"sprintf ] map-concat` Convert each code point in the input string to a 7-bit binary number string and join them all together. * `R/ (?<=0)(?=1)/ re-split` Split into a sequence of strings down the middle of every `01`. * `[ bin> ] map Σ` Convert each from binary string to decimal integer and sum. ]
[Question] [ # Challenge Description You have to show a simulation of rain in terminal. In the example given below its adding 100 raindrops at random (use the default random function which your language offers) coordinates, waiting for 0.2 seconds and then redrawing again until the given time expires. Any character can be used for representing the raindrop. ### Parameters * Wait time between redrawing in seconds. * Time for which the rain will be visible. This is just an integer representing the number of iterations. [So, the net time for which the rain will be visible is this integer multiplied by the wait time] * Message to be displayed when the rain ends. (This has to be centered) * Number of raindrops to be displayed on the screen. ### Rules * A single byte should be used for representing a rain drop, and it can be anything, even cats and dogs. * It doesn't have to be responsive to terminal size which means you don't have to handle the bug for varied terminal sizes. You can specify the terminal width and height on your own. * Standard rules of golfing apply. # Code Sample and Output This is an ungolfed version written in python 2.7 using ncurses. ``` import curses import random import time myscreen = curses.initscr() curses.curs_set(0) # no cursor please HEIGHT, WIDTH = myscreen.getmaxyx() RAIN = '/' # this is what my rain drop looks like TIME = 10 def make_it_rain(window, tot_time, msg, wait_time, num_drops): """ window :: curses window time :: Total time for which it rains msg :: Message displayed when it stops raining wait_time :: Time between redrawing scene num_drops :: Number of rain drops in the scene """ for _ in range(tot_time): for i in range(num_drops): x,y=random.randint(1, HEIGHT-2),random.randint(1,WIDTH-2) window.addstr(x,y,RAIN) window.refresh() time.sleep(wait_time) window.erase() window.refresh() window.addstr(HEIGHT/2, int(WIDTH/2.7), msg) if __name__ == '__main__': make_it_rain(myscreen, TIME, 'IT HAS STOPPED RAINING!', 0.2, 100) myscreen.getch() curses.endwin() ``` Output - [![enter image description here](https://i.stack.imgur.com/7Nn4x.gif)](https://i.stack.imgur.com/7Nn4x.gif) [Answer] # [MATL](https://github.com/lmendo/MATL), 52 bytes ``` xxx:"1GY.Xx2e3Z@25eHG>~47*cD]Xx12:~c!3G80yn-H/kZ"why ``` Inputs are, in this order: pause between updates, number of drops, message, number of repetitions. The monitor has size 80×25 characters (hard-coded). GIF or it didn't happen! (Example with inputs `0.2`, `100`, `'THE END'`, `30`) [![enter image description here](https://i.stack.imgur.com/QyNGl.gif)](https://i.stack.imgur.com/QyNGl.gif) Or try it at [**MATL Online**](https://matl.io/?code=xxx%3A%221GY.Xx2e3Z%4025eHG%3E%7E47%2acD%5DXx12%3A%7Ec%213G80yn-H%2FkZ%22why&inputs=0.2%0A100%0A%27THE+END%27%0A30%0A&version=19.7.2). ### Explanation ``` xxx % Take first three inputs implicitly and delete them (but they get % copied into clipboard G) :" % Take fourth input implicitly. Repeat that many times 1G % Push first input (pause time) Y. % Pause that many seconds Xx % Clear screen 2e3 % Push 2000 (number of chars in the monitor, 80*25) Z@ % Push random permutation of the integers from 1 to 2000 25e % Reshape as a 25×80 matrix, which contains the numbers from 1 to 2000 % in random positions HG % Push second input (number of drops) >~ % Set numbers that are <= second input to 1, and the rest to 0 47*c % Multiply by 47 (ASCII for '/') and convert to char. Char 0 will % be displayed as a space D % Display ] % End Xx % Clear screen 12:~ % Push row vector of twelve zeros c! % Convert to char and transpose. This will produce 12 lines containing % a space, to vertically center the message in the 25-row monitor 3G % Push third input (message string) 80 % Push 80 yn % Duplicate message string and push its length - % Subtract H/k % Divide by 2 and round down Z" % Push string of that many spaces, to horizontally center the message % in the 80-column monitor w % Swap h % Concatenate horizontally y % Duplicate the column vector of 12 spaces to fill the monitor % Implicitly display ``` [Answer] ## JavaScript (ES6), ~~268~~ 261 bytes ``` t= (o,f,d,r,m,g=(r,_,x=Math.random()*78|0,y=Math.random()*9|0)=>r?g(r-(d[y][x]<`/`),d[y][x]=`/`):d.map(a=>a.join``).join` `)=>i=setInterval(_=>o.data=f--?g(r,d=[...Array(9)].map(_=>[...` `.repeat(78)])):` `+` `.repeat(40-m.length/2,clearInterval(i))+m,d*1e3) ``` ``` <input id=f size=10 placeholder="# of frames"><input id=d placeholder="Interval between frames"><input id=r size=10 placeholder="# of raindrops"><input id=m placeholder="End message"><input type=button value=Go onclick=t(o.firstChild,+f.value,+d.value,+r.value,m.value)><pre id=o>&nbsp; ``` At least on my browser, the output is designed to fit into the Stack Snippet area without having to go "Full page", so if you ask for more than 702 raindrops it will crash. Edit: Saved 7 bytes by using a text node as my output area. [Answer] ## R, 196 192 185 bytes Just a mock version I wrote based on the description. Hopefully it's somewhat what OP was looking for. Saved some bytes thanks to @plannapus. ``` f=function(w,t,m,n){for(i in 1:t){x=matrix(" ",100,23);x[sample(2300,n)]="/";cat("\f",rbind(x,"\n"),sep="");Sys.sleep(w)};cat("\f",g<-rep("\n",11),rep(" ",(100-nchar(m))/2),m,g,sep="")} ``` The arguments: * `w`: Wait time between frames * `t`: Total number of frames * `m`: Custom message * `n`: Number of rain drops **Example** Why does it look like it's raining upwards? Edit: I should mention that this is my customized 23x100 character R-studio console. The dimensions are hardcoded into the function but one could in principle use `getOption("width")` to make it flexible to console size. [![enter image description here](https://i.stack.imgur.com/9yI2l.gif)](https://i.stack.imgur.com/9yI2l.gif) **Ungolfed and explained** ``` f=function(w,t,m,n){ for(i in 1:t){ x=matrix(" ",100,23); # Initialize matrix of console size x[sample(2300,n)]="/"; # Insert t randomly sampled "/" cat("\f",rbind(x,"\n"),sep=""); # Add newlines and print one frame Sys.sleep(w) # Sleep }; cat("\f",g<-rep("\n",11),rep(" ",(100-nchar(m))/2),m,g,sep="") # Print centered msg } ``` [Answer] ## C 160 bytes ``` f(v,d,w,char *s){i,j;char c='/';for(i=0;i<v;i++){for(j=0;j<d;j++)printf("%*c",(rand()%100),c);fflush(stdout);sleep(w);}system("clear");printf("%*s\n",1000,s);} v-Time the raindrops are visible in seconds. d-Number of drops per iteration w-Wait time in seconds, before the next iteration s-String to be passed on once its done ``` Ungolfed version: ``` void f(int v, int d, int w,char *s) { char c='/'; for(int i=0;i<v;i++) { for(int j=0;j<d;j++) printf("%*c",(rand()%100),c); fflush(stdout); sleep(w); } system("clear"); printf("%*s\n", 1000,s); } ``` [![Testcase on my terminal](https://i.stack.imgur.com/JbX1I.gif)](https://i.stack.imgur.com/JbX1I.gif) ``` v - 5 seconds d - 100 drops w - 1 second wait time s - "Raining Blood" :) ``` [Answer] # R, 163 chars ``` f=function(w,t,n,m){for(i in 1:t){cat("\f",sample(rep(c("/"," "),c(n,1920-n))),sep="");Sys.sleep(w)};cat("\f",g<-rep("\n",12),rep(" ",(80-nchar(m))/2),m,g,sep="")} ``` With indents and newlines: ``` f=function(w,t,n,m){ for(i in 1:t){ cat("\f",sample(rep(c("/"," "),c(n,1920-n))),sep="") Sys.sleep(w) } cat("\f",g<-rep("\n",12),rep(" ",(80-nchar(m))/2),m,g,sep="") } ``` It's adapted to a terminal size of 24 lines by 80 columns. `w` is the waiting time, `t` the number of frames, `n` the number of raindrops and `m` the final message. It differs from [@billywob's answer](https://codegolf.stackexchange.com/a/107551/6741) in the different use of `sample`: if the output size is omitted, `sample` gives a permutation of the input vector (here a vector containing the needed number of raindrops and the corresponding number of spaces, thanks to the fact that argument `times` of function `rep` is vectorized). As the size of the vector corresponds exactly to the size of the screen, there is no need to add newlines, or to force-shape it into a matrix. [![Gif of output](https://i.stack.imgur.com/Pm2kB.gif)](https://i.stack.imgur.com/Pm2kB.gif) [Answer] # NodeJS: 691 158 148 Bytes ## Edit As requested, additional features removed and golf'd. ``` s=[];setInterval(()=>{s=s.slice(L='',9);for(;!L[30];)L+=' |'[Math.random()*10&1];s.unshift(L);console.log("\u001b[2J\u001b[0;0H"+s.join('\n'))},99) ``` The rules specify disregard for size, but this version includes a glitch for the first few frames. It is **129 bytes.** ``` s='';setInterval(()=>{for(s='\n'+s.slice(0,290);!s[300];)s=' |'[Math.random()*10&1]+s;console.log("\u001b[2J\u001b[0;0H"+s)},99) ``` --- **Previous answer** Perhaps not the best golfing, but I got a bit carried away. It has optional wind direction and rain factor. `node rain.js 0 0.3` ``` var H=process.stdout.rows-2, W=process.stdout.columns,wnd=(arg=process.argv)[2]||0, rf=arg[3]||0.3, s=[]; let clr=()=>{ console.log("\u001b[2J\u001b[0;0H") } let nc=()=>{ return ~~(Math.random()*1+rf) } let nl=()=>{ L=[];for(i=0;i<W;i++)L.push(nc()); return L} let itrl=(l)=>{ for(w=0;w<wnd;w++){l.pop();l.unshift(nc())}for(w=0;w>wnd;w--){l.shift();l.push(nc())};return l } let itrs=()=>{ if(s.length>H)s.pop();s.unshift(nl());s.map(v=>itrl(v)) } let d=(c,i)=>{if(!c)return ' ';if(i==H)return '*';if(wnd<0)return '/';if(wnd>0)return '\\';return '|'} let drw=(s)=>{ console.log(s.map((v,i)=>{ return v.map( c=>d(c,i) ).join('') }).join('\r\n')) } setInterval(()=>{itrs();clr();drw(s)},100) ``` [See webm of it working here](http://zippy.gfycat.com/RecentBackCockatoo.webm) [Answer] # [Noodel](https://tkellehe.github.io/noodel/), noncompeting 44 [bytes](https://tkellehe.github.io/noodel/docs/code_page.html) I had centering text on my list of things to do since I made the language... But, I was lazy and did not add until after this challenge. So, here I am not competing, but had fun with the challenge:) ``` ØGQÆ×Øæ3/ׯ3I_ȥ⁻¤×⁺Æ1Ḷḋŀ÷25¶İÇæḍ€Æ1uụC¶×12⁺ß ``` The console is size is hard coded to 25x50 which does not look good in the online editor, but does for the snippet. [Try it:)](https://tkellehe.github.io/noodel/editor.html?code=%C3%98GQ%C3%86%C3%97%C3%98%C3%A63%2F%C3%97%C3%863I_%C8%A5%E2%81%BB%C2%A4%C3%97%E2%81%BA%C3%861%E1%B8%B6%E1%B8%8B%C5%80%C3%B725%C2%B6%C4%B0%C3%87%C3%A6%E1%B8%8D%E2%82%AC%C3%861u%E1%BB%A5C%C2%B6%C3%9712%E2%81%BA%C3%9F&input=0.2%2C%2050%2C%20%22Game%20Over%22%2C%2030&run=true) --- ### How It Works ``` Ø # Pushes all of the inputs from the stack directly back into the stdin since it is the first token. GQÆ×Ø # Turns the seconds into milliseconds since can only delay by milliseconds. GQ # Pushes on the string "GQ" onto the top of the stack. Æ # Consumes from stdin the value in the front and pushes it onto the stack which is the number of seconds to delay. × # Multiplies the two items on top of the stack. # Since the top of the stack is a number, the second parameter will be converted into a number. But, this will fail for the string "GQ" therein treated as a base 98 number producing 1000. Ø # Pops off the new value, and pushes it into the front of stdin. æ3/ׯ3I_ȥ⁻¤×⁺ # Creates the correct amount of rain drops and spaces to be displayed in a 50x25 console. æ3 # Copies the forth parameter (the number of rain drops). / # Pushes the character "/" as the rain drop character. × # Repeats the rain drop character the specified number of times provided. Æ3 # Consumes the number of rain drops from stdin. I_ # Pushes the string "I_" onto the stack. ȥ # Converts the string into a number as if it were a base 98 number producing 25 * 50 = 1250. ⁻ # Subtract 1250 - [number rain drops] to get the number of spaces. ¤ # Pushes on the string "¤" which for Noodel is a space. × # Replicate the "¤" that number of times. ⁺ # Concatenate the spaces with the rain drops. Æ1Ḷḋŀ÷25¬İÇæḍ€ # Handles the animation of the rain drops. Æ1 # Consumes and pushes on the number of times to loop the animation. Ḷ # Pops off the number of times to loop and loops the following code that many times. ḋ # Duplicate the string with the rain drops and spaces. ŀ # Shuffle the string using Fisher-Yates algorithm. ÷25 # Divide it into 25 equal parts and push on an array containing those parts. ¶ # Pushes on the string "¶" which is a new line. İ # Join the array by the given character. Ç # Clear the screen and display the rain. æ # Copy what is on the front of stdin onto the stack which is the number of milliseconds to delay. ḍ # Delay for the specified number of milliseconds. € # End of the loop. Æ1uụC¶×12⁺ß # Creates the centered text that is displayed at the end. Æ1 # Pushes on the final output string. u # Pushes on the string "u" onto the top. ụC # Convert the string on the top of the stack to an integer (which will fail and default to base 98 which is 50) then center the input string based off of that width. ¶ # Push on a the string "¶" which is a new line. ×12 # Repeat it 12 times. ⁺ # Append the input string that has been centered to the new lines. ß # Clear the screen. # Implicitly push on what is on the top of the stack which is the final output. ``` --- ``` <div id="noodel" code="ØGQÆ×Øæ3/ׯ3I_ȥ⁻¤×⁺Æ1Ḷḋŀ÷25¶İÇæḍ€Æ1uụC¶×12⁺ß" input='0.2, 50, "Game Over", 30' cols="50" rows="25"></div> <script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script> <script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script> ``` [Answer] # Ruby + GNU Core Utils, 169 bytes Parameters to the function are wait time, number of iterations, message, and number of raindrops, in that order. Newlines for readability. Core Utils were needed for `tput` and `clear`. ``` ->w,t,m,n{x=`tput cols`.to_i;z=x*h=`tput lines`.to_i t.times{s=' '*z;[*0...z].sample(n).map{|i|s[i]=?/};puts`clear`+s;sleep w} puts`clear`+$/*(h/2),' '*(x/2-m.size/2)+m} ``` [Answer] # Python 2.7, ~~254~~ 251 bytes This is my own try without using ncurses. ``` from time import*;from random import*;u=range;y=randint def m(t,m,w,n): for _ in u(t): r=[[' 'for _ in u(40)]for _ in u(40)] for i in u(n):r[y(0,39)][y(0,39)]='/' print'\n'.join(map(lambda k:' '.join(k),r));sleep(w);print '<esc>[2J' print' '*33+m ``` Thank to @ErikTheOutgolfer for correcting and saving me bytes. [Answer] # SmileBASIC, 114 bytes ``` INPUT W,T,M$,N FOR I=1TO T VSYNC W*60CLS FOR J=1TO N LOCATE RND(50),RND(30)?7; NEXT NEXT LOCATE 25-LEN(M$)/2,15?M$ ``` Console size is always 50\*30. [Answer] ## Perl 5, 156 bytes **154 bytes code + 2 for `-pl`.** ``` $M=$_;$W=<>;$I=<>;$R=<>;$_=$"x8e3;{eval'$-=rand 8e3;s!.{$-}\K !/!;'x$R;print;select$a,$a,$a,$W;y!/! !;--$I&&redo}$-=3920-($l=length$M)/2;s;.{$-}\K.{$l};$M ``` Uses a fixed size of 160x50. [See it online!](https://asciinema.org/a/1uVVjQCOFhecO1aNfjh3rtfBg) --- ## Perl 5, 203 bytes **201 bytes code + 2 for `-pl`.** ``` $M=$_;$W=<>;$I=<>;$R=<>;$_=$"x($z=($x=`tput cols`)*($y=`tput lines`));{eval'$-=rand$z;s!.{$-}\K !/!;'x$R;print;select$a,$a,$a,$W;y!/! !;--$I&&redo}$-=$x*($y+!($y%2))/2-($l=length$M)/2;s;.{$-}\K.{$l};$M ``` Uses `tput` to determine the size of the terminal. ]
[Question] [ The presents have been opened. The mince-pies have been eaten. The Star Wars have been watched. The Christmas Season is beginning to wind down. By now you may well have pulled a few [Christmas Crackers](https://en.wikipedia.org/wiki/Christmas_cracker). If you're lucky, instead of the usual useless plastic toys, you may have won a **Mystery Calculator** with which you can *amaze your friends and relatives*. [![enter image description here](https://i.stack.imgur.com/5NAPr.jpg)](https://i.stack.imgur.com/5NAPr.jpg) This trick consists of 6 cards each with a 4x8 grid of numbers printed on it. Each card contains a different subset of the integers `[1,63]`. The magician will ask you to pick a number from one card and keep that number secret. The magician will then ask which cards have that number. With that knowledge, the magician will *magically* be able to determine and disclose the original number guessed. --- Output the full set of 6 Mystery Calculator cards exactly as follows: ``` 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 - - - - - - - - - - - 2 3 6 7 10 11 14 15 18 19 22 23 26 27 30 31 34 35 38 39 42 43 46 47 50 51 54 55 58 59 62 63 - - - - - - - - - - - 4 5 6 7 12 13 14 15 20 21 22 23 28 29 30 31 36 37 38 39 44 45 46 47 52 53 54 55 60 61 62 63 - - - - - - - - - - - 8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 31 40 41 42 43 44 45 46 47 56 57 58 59 60 61 62 63 - - - - - - - - - - - 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 - - - - - - - - - - - 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 ``` Output may or may not contain one final trailing newline. There must be no trailing whitespace. Each card is separated by 11 `-` perforations. * md5sum with final newline: `7aa2d9339b810ec62a2b90c5e11d6f4a` * md5sum without final newline: `e9abe4e32dca3e8fbfdaa4886fc5efd2` For those of you of more of a windows orientation, I will also allow `CRLF` style line endings. In that case, the md5s are: * md5sum with final newline: `e4f16ff9752eee2cedb5f97c7b5aec6d` * md5sum without final newline: `78c560eed3b83513e3080117ab5dc5fa` [Answer] # [Python 2](https://docs.python.org/2/), ~~99~~ ~~96~~ ~~93~~ 91 bytes ``` k=1 while 1:print('%2d '*7+'%2d\n')*4%tuple(n for n in range(64)if k&n),11/(k<32)*' -';k*=2 ``` Exits with an error, which is [allowed by default](http://meta.codegolf.stackexchange.com/a/4781/12012). [Try it online!](https://tio.run/nexus/python2#FcbRCkAwFADQd19xX7jbkDaisD/xogxr69KafP7kPJ3ktMze03oDcryDpcgwVxugGMo/CyEXXR6f2xtGsF8BCCxBWOkwrO@43cEVxCspG@bmVnGBUOPkhFYpfQ "Python 2 – TIO Nexus") or [verify the MD5 hash](https://tio.run/nexus/bash#FcxLDoIwFAXQuau4E@xHTdOKmijsxIlJizSFR1OKxsS9F52d0Snxk/uJoKx7qTlbT/hitKd5GUsJrd68ez846GtMnjJnlbFg8rL7405MyLrKSxwcJ3RTAuEXpAc9HT/XwncIWxJ7rRUPzdEIyXBgtyBbswI "Bash – TIO Nexus"). ### How it works After initializing **k** as **1**, we enter an infinite loop that executes the following code. ``` print('%2d '*7+'%2d\n')*4%tuple(n for n in range(64)if k&n),11/(k<32)*' -';k*=2 ``` `tuple(n for n in range(64)if k&n)` creates a tuple of all non-negative integers below **64** that have there **j**th bit set, where **j** is the iteration count of the loop, i.e., **2j = k**. `('%2d '*7+'%2d\n')*4` first creates the format string `'%2d %2d %2d %2d %2d %2d %2d \n'`, then repeats it four times. This is a template for each card, which pads each integer in the tuple to two characters (prepending spaces), separates each group of **8** integers by spaces, and the groups themselves by linefeeds. Now, [Python 2's `print` statement](https://docs.python.org/2/reference/simple_stmts.html#print) is a curious beast. It takes several expressions, separated by commata, and prints them one by one. It evaluates the first expression, prints it, evaluates the next expressions, prints it, etc. until no more expressions are left. Unless the last expression is followed by a comma, it appends a linefeed to it. Also, it prepends a space to all expressions, unless they are printed at the beginning of a line. In each iteration, we first print the result of applying the format string to the tuple. We're at the beginning of a line, so no space is prepended. Then, we (attempt to) print the result of `11/(k<32)*' -'`. If **k < 32**, this expressions evaluates to `' - - - - - - - - - - -'`. Again, we're at the beginning of a line, so no space is prepended. There is no comma after this expression, so `print` appends a linefeed. However, in the sixth iteration, **k = 25 = 32**, so trying to evaluate `11/(k<32)*' -'` raises an uncaught *ZeroDivisionError*. This breaks out of the loop and ends the program immediately. [Answer] # C (gcc), 105 bytes ``` o;main(i){for(;i<384;i++%64||puts(" - - - - - - - - - - -"))i&1<<i/64&&printf("%2d%c",i%64,++o%8?32:10);} ``` [Answer] # Python 2, 132 bytes ``` for c in range(6):s=" ".join("%2d"%n for n in range(64)if n&1<<c);print"\n".join([s[24*i:24*i+23]for i in range(4)]+[" -"*11]*(c<5)) ``` Splitting sequences is annoying in Python. [Try it online](https://tio.run/nexus/python2#TctBCoMwEEDRqwwDSiZiIWl0YdOTpFmUVMu4GCX2/ikBod381X9l2TIkYIH8lPesRpqOOwJe1o1FYWNf2AjUSf4mR7yAtMb7RLc9s3zwIacJR7BO81TT2Wusln/WUewCQo/amKhV8gNRKV8). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 26 bytes ``` Ts8GW ⁾ -ẋ11W 63RBUz0Ñ€j¢Y ``` [Try it online!](https://tio.run/nexus/jelly#@x9SbOEezvWocZ@C7sNd3YaG4VxmxkFOoVUGhyc@alqTdWhR5P//AA "Jelly – TIO Nexus") or [verify the MD5 hash](https://tio.run/nexus/bash#@6@fX1Cin5Wak1MJIRXSShX0U1LL9ItLUjLzFGoUclNMi0tz//8PKbZwD@d61LhPQffhrm5Dw3AuM@Mgp9Aqg8MTHzWtyTq0KBIA "Bash – TIO Nexus"). ### How it works ``` 63RBUz0Ñ€j¢Y Main link. No arguments. 63R Range 63; yield [1, ..., 63]. B Binary; convert each integer to base 2. U Upend; reverse the binary representations. z0 Zip with filler 0; transpose rows and columns, filling gaps in the (non-rectangular) matrix with zeroes. Ñ€ Map the first helper link over the new rows. ¢ Yield the return value of the second helper link. j Join the left result, separating by the right result. Y Join the results, separating by line feeds. Ts8G First helper link. Argument: A (array of 1's and 0's) T Truth; get all indices of 1's. s8 Split the indices into chunks of length 8. G Grid; convert the 2D array into a string, separating row items by spaces, rows by linefeeds, and left-padding each integer with spaces to equal lengths. W Wrap the generated string in an array. ⁾ -ẋ11W Second helper link. No arguments. ⁾ - Yield " -". ẋ11 Repeat the string 11 times. W Wrap the generated string in an array. ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~49~~ ~~48~~ 44 bytes 43 bytes of code, +1 for `-S` flag. ``` Fi,6{IiP" -"X11P(sX2-#_._M2**iBA_FI,64)<>8} ``` [Try it online!](https://tio.run/nexus/pip#@@@WqWNW7ZkZoKSgqxRhaBigURxhpKscrxfva6SllenkGO/mqWNmomljZ1H7//9/3WAA "Pip – TIO Nexus") ### Explanation ``` s is space (preinitialized) Fi,6{ } For i in range(6): Ii If i is nonzero (i.e. all except 1st loop): P" -"X11 Print hyphens FI,64 Range(64), filtered on this function: 2**iBA_ 2**i bitwise AND with argument (is nonzero) M To each remaining number, map this function: 2-#_ 2-len(argument) sX ^ that many spaces ._ prepended to argument ( )<>8 Group list into length-8 sublists P Print (-S flag joins on space then newline) ``` [Answer] # Ruby, 90 bytes ``` 1.upto(383){|i|print (j=i%64)<1?' -'*11+$/:"%2d%s"%[j,j+1&15>>i/256>0?' ':$/]*(j>>i/64&1)} ``` **Ungolfed** Fairly straightforward. The only thing that may require additional explanation is when to follow a number with a newline rather than a space. This happens when `j+1%16==0` in the first four cards and `j+1%8`==0 in the last two. Hence the expression `15>>i/64/4` or equivalently `15>>i/256`is ANDed with `j` to determine whether space or newline is required. ``` 1.upto(383){|i| #Count starting at 1 instead of 0 to supress - - before 1st card print (j=i%64)<1? #j=number to consider for card. If 0, ' -'*11+$/: #print - - -... else print "%2d%s"%[j,j+1&15>>i/256>0?' ':$/]* #j formatted to 2 spaces followed by a space (or if j+1 divisible by 16 or 8 depending on card, a newline.) (j>>i/64&1) #only print appropriate numbers for this card, i.e. when this expression evaluates to 1 } ``` [Answer] ## JavaScript (ES6), 150 bytes ``` f= _=>[1,2,4,8,16,32].map(m=>[...Array(64)].map((_,i)=>` ${i}`.slice(-2)).filter(i=>i&m).join` `.replace(/(.{23}) /g,`$1 `)).join(` ${` -`.repeat(11)} `) ;document.write(`<pre>`+f()) ``` [Answer] # [Perl 6](https://perl6.org), ~~194 116~~ 86 bytes ``` put join "\n{' -'x 11}\n",map {join "\n",.[^32].rotor(8)».fmt('%2s')},(1,3...63),(2,{|($_ X+1,4)}...*),(4,{|($_ X+1,2,3,8)}...*),(8,{|((1...7,16)X+$_)}...*),(16,{|((1...15,32)X+$_)}...*),32..63 ``` [Try it](https://tio.run/nexus/perl6#dVPNTttAEL7nKQaa1jY4bmzHjmNKkQockFohoSIhNS1a744bV846steUKqQP0x77CIgLL8Qj0PFfCAcOtjzzzfftfDPrskC48i2@1@vNf8H0iqWJgH0oUMG7HsCYMUdMXHcSBfYQue8wJ5oMuYe2Lfx4xKgEJyzCEbqO4MzFII5iwdgoCPyYymLhVCWj2PbjeDL2HER0OIrIo4iPI4@RqKgOCrjnDxGFGwWuZ7voDoOhbY9Z5Anuxaz3njrkKSsKOEq@Y6EGn448WBJzxgroby3yjDx0UY5FmSpiABRlNEc1ywR8OD/5eAS6UZGgpZDVvJRw/w8WmKegDeaNehiS/P5ceJczvNZggKCVUmCs998ae4s8kQpaEHJkIk0kanB/a0KYSHplpaqaWdHTHs6EAB2mhcrBgGV7upVIqxbTKW9AEnddbRAbK@u2c1RlLtcWG05n98lXpczTrMAu2Zbvdzh1aBVpmS8GhCg9rIsNK@XPCY2LVX05@uSYBJ7Gb0n8STN@BeQAc44LBWqGwFmagsrg4e5Pbe7h7i8wKeq4rCMCWVpkVSUvU6aw5lULFbV4j5YGNTemod3wamTUSNWARYMMoWjBm7rdN4enZ8dh2OSa@j3quRYp1cbYn2tQ7jf0d07PP1syHbQr67TKZiek81hp/MgSCdtTuaS7oF2Dba@mctucswUsO2jbtL58c52vVp6pLNcD4/7WiudK1147hWasTN02XcuyfNcwdcdc3uj9S7jYtc2RsaL0DmVHG1nHdM1gjQQVotsUjU3bNy52@5drzPbXoO2ZrvMMdZ3qxMe9Xn/n@OzMIithM4JuvRv55t/XeSaVsVkEBwegHWZ5jlxpsLUF2onkbbghUN@EziN9PnmEtUlKv2CSkBdNVrovmyS0dfkf "Perl 6 – TIO Nexus") ``` for 1..383 {print !($/=$_%64)??"{' -'x 11}\n"!!$/+>($_/64)%2??$/.fmt('%2d')~(($/+1)+&(15+>($_/256))??' '!!"\n")!!''} ``` [Try it](https://tio.run/nexus/perl6#VVPBbptAEL37K4aEZKGpsQGDMa5jqUkOkVpVitRbpGjZHWIkDNayJKks92PaYz@hyiU/lE9IB7Bj9wDSzLz3Zt4M1BXCQ@iIaa@3/AG3DzzPJMygQg2fegBjzj058f1JErlDFKHHvWQyFAG6rgzTEScITniCI/Q9KbiPUZqkkvNRFIUpwVLpNZBR6oZpOhkHHiJ6AmUSUCTGScBJVDaNIhGEQ0TpJ5EfuD76w2joumOeBFIEKe@d04Qi51UFl9k9Vrr/9TKANTEXvALTWKmSPOwihVWda2IAVHWyRL0oJXz@fv3lEiy7IcGWQlZVXcDLH1ihyoH1l516HJP8bCmDuwU@MegjsLqQmFrmwJ6uVFZo2BZBIZd5ViCDl78fIc4KepW1bobZ0LNtzqUEC24rrcCG9ba7kxVOK2ZR3oYs3U11QOysvI@tUNeqeLfYcXZ2974aZZGXFe6SW/hsV6cJnSqv1apPFW3FLdh2cvE/oXOxaT8OkxyTwH79ToGPtONjIAeoBK406AWC4HkOuoTX51@tudfn303I86psaqLOucYW2ZxQtnI9OhN0e91viXo3PR3aXQyUa@953DJLld1nBc@3HGIrckRXIMTpxbebqzjeL3ba27ylpQLXcfzIh3XHMeiWM/PuJBzZ8/nRmo7MnsB1N7fFkWGYg7Nzy7wbUPHEm8/NgZMutcVOPMnsnxYxz1z77NRygw7mBaFNKgyYYRyRgG0YjG3ezA9XNzfOqtZxZ2S304N898NZoiy0fQiC@RzYRakUCs3AMIBdF2IbHghM3/4B "Perl 6 – TIO Nexus") ``` for 1..383 {$_%64||put ' -'x 11;$_+&(1+<($_/64))&&printf "%2d%c",$_%64,++$/%8??32!!10} ``` [Try it](https://tio.run/nexus/perl6#VVPbbptAEH33V4xTbCCOiQGDMW5qqUkeIrWKFDVvkaxld6iRMFjLkqaK049pH/sJVV7yQ/mEdLglzgNIM3PO2XNmoSwQbn2LL3q9zU@4uWVpIuAEClTwsQcwY8wRc9edR4E9Qe47zInmE@6hbQs/njKC4JxFOEXXEZy5GMRRLBibBoEfEywWTgWZxrYfx/OZ5yCiw1FEHlV8FnmMREV1UMA9f4Io3ChwPdtFdxJMbHvGIk9wL2a9T@SQp6wo4Cz5joUafz3z4J6Ya1aA1t/KnDJ0lcSiTBUxAIoy2qBa5wI@X198OQPDrEjQUiiqLDN4@gtblCno402jHoYkf7IR3mqNdzqMEfQyExgb2rG52MokU9AOQSITaZKhDk//jiBMMnrlparMPNDTHs6EAANuCiXBhPv2dCvJrFrMoL4JSdy52iM2UV5tS1SlzF4jNpwu7luuSpmneYFds4WfdHNyaBVpKbdjmigjrMGmlfL3hCbFQ/1xaJSYBN7Wb2X4g3b8ASgBSo5bBWqNwFmagsrh@fF3He758Q@wTNR1WVc0ZGmRV0hepkxhzasuVNTiPbo0qLkxLW3Hq5WRkcqARYsMoWiHu9ru8PTy6jwMm16DX5DnWqRUe2t/r0G9X6AdXl5/s7J03F5Zp1U2d0I6L3EuwbYsN3DhXlsN/OluV8nSV6HfgW0vtNVoaNijj4a2Ovanpjkctu4OBo4Y8IOjmnQ0GmnHg2C5dJ1@3548vGiH51dXFimFjalu4Xv95m80eJ4pcx8EyyXop7mUyJUO/T7oFxlvyz2Bxct/ "Perl 6 – TIO Nexus") (check the *Debug* sections for the MD5 results) The last two were inspired/transcribed from the Ruby and C implementations [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 71 bytes ``` 63L©DÉÏ®À2ô®ÉÏ®ÀÀÀ4ô®ÉÏ®Á8ô®ÈÏ63®Á16ô®ÈÏ63D32sŸ)˜32ôvy8ôvy.B}„ -11×})¨» ``` [Try it online!](https://tio.run/nexus/05ab1e#@29m7HNopcvhzsP9h9YdbjA6vAVIQTkgaIIk0GgB5nQc7jczBnENzRB8F2Oj4qM7NE/PMQYaUVZpASL0nGofNcxT0DU0PDy9VvPQikO7//8HAA "05AB1E – TIO Nexus") This approach, don't try it. Will likely delete this out of shame to be honest. Matrix manipulation is not my strong suit so I tried to brute force generate all 6 sequences and then pump them together sloppily. [Answer] ## Batch, 249 bytes ``` @echo off set s= for %%i in (1 2 4 8 16 32)do for /l %%j in (0,1,63)do call:c %%i %%j exit/b :c if %2==0 if %1 gtr 1 echo - - - - - - - - - - - set/an=%1^&%2 if %n%==0 exit/b set n= %2 set s=%s%%n:~-3% if not "%s:~23%"=="" echo%s%&set s= ``` Outputs a trailing CRLF. [Answer] ## JavaScript (ES6), ~~103~~ 102 bytes ``` f=(k=1,n=z=0)=>n>>6?k>>5?'':' -'.repeat(11)+` `+f(k*2):(n&k?(n>9?'':' ')+n+` `[++z&7&&1]:'')+f(k,++n) ``` *MD5: 7AA2D9339B810EC62A2B90C5E11D6F4A* ### Test ``` f=(k=1,n=z=0)=>n>>6?k>>5?'':' -'.repeat(11)+` `+f(k*2):(n&k?(n>9?'':' ')+n+` `[++z&7&&1]:'')+f(k,++n) console.log(f()) ``` [Answer] # bash / Unix utilities, ~~125~~ 124 bytes ``` b='- - - - ';for ((x=1;x<33;x*=2));{ for n in {0..63};{ ((x&n))&&printf \ %2d $n;};echo $b$b$b;}|fold -w24|sed -e\$d -es/.// ``` *Edit: Removed an unnecessary ^ from the regex at the end; the regex will always match at the beginning of the line anyway.* [Answer] # PHP, 102 bytes ``` for(;$c<6;$n%32||$c+=print str_pad(" ",25," -"),$n%2**$c||$b+=1<<$c)printf(" "[$n++%8]."%3d",++$b%64); ``` prints a leading but no trailing newline, and one leading space in each line. Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/94c095e0787b3be1d7b06d44c0fa07866df22cc9). For PHP<5.6, replace `2**$c` with `(1<<$c)`. PHP 5.5 could use `&~1<<$c?:` instead of `%2**$c||`. For PHP<5.5, replace `"\n"[$n++%8]` with `($n++%8?"":"\n")`. --- Dashes are one character off due to the leading space; append a space to the first `str_pad` parameter (insert a space before the second code line) to fix. Removing the leading space instead requires some fiddling and three additional bytes: `printf("%c%2d",$n++%8?32:10,++$b%64);` and `23` instead of `25`. Turning the leading newline into a trailing one would cost another three bytes: ``` for(;$c<6;$n%32||$c+=print str_pad("",22," -")." ",$n%2**$c||$b+=1<<$c)printf("%2d%c",++$b%64,++$n%8?32:10); ``` --- [Answer] # [Python 2](https://docs.python.org/2/), 89 bytes ``` i=0;exec"print('%2d '*7+'%2d\\n')*4%tuple(j for j in range(64)if j&2**i)+' -'*11;i+=1;"*6 ``` [Try it online!](https://tio.run/##FcZRCoQgEADQqwxBjY4spER9SDfpJzarkWUSMWhP77Lv66VvOS9xtfLc@/CEd5MyS1HYug2QJvPPsghqGtpyp09QEfYrQwQWyKscQY2D5h1i54hYG4QXkrWezWx9Q2OtPw "Python 2 – Try It Online") Explanation: ``` # initialize outer counter variable i=0 # generate a formatting string for a single row of numbers # %2d will left pad an integer with spaces, up to string length 2 # the \\n is so that exec will interpret it as a character rather than a literal line break '%2d '*7+'%2d\\n' # create a formatting string of 4 lines of 8 numbers (.................)*4 # format the string with a generated tuple of numbers that have a 1 in the current bit slot # (or more literally, bitwise j AND 2^i is not zero) %tuple(j for j in range(64)if j&2**i) # add the perforation break +' -'*11 # print the generated string, then increment the counter print..................................................................;i+=1 # execute the following statements 6 times exec"............................................................................."*6 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 63L2вíƶ0ζε0K8ô§2j»}„ -11×¶.øý ``` Port from [*@Emigna*'s 05AB1E answer here](https://codegolf.stackexchange.com/a/184859/52210), after which I added additional code to print it according to the requirements in this challenge. [Try it online](https://tio.run/##ATUAyv9vc2FiaWX//zYzTDLQssOtxrYwzrbOtTBLOMO0wqcyasK7feKAniAtMTHDl8K2LsO4w73//w) or [verify md5sum](https://tio.run/##S0oszvj/PzU5I19BPbWiIDW5JDXFiss8MdEoxdLY2DLJwtAgNdnMKNEoydIg2TTV0DDFLM0kkSsxuaQ0McdKnSu1OLkos6BEQT@/oEQ/vzgxKTMVSinop6SW6ReXpGTmKdQo5KaYFpfm/v9vZuxjdGHT4bXHthmc23Zuq4G3xeEth5YbZR3aXfuoYZ6CrqHh4emHtukd3nF4LwA). **Explanation:** ``` 63L # Create a list in the range [1,63] 2в # Convert each number to binary as lists of 0s and 1s í # Reverse each binary list ƶ # Multiply each binary digit by its 1-based index [1,length] (so [1,63]) 0ζ # Zip/transpose; swapping rows/columns, with "0" as filler ε # Map each inner list to: 0K # Remove all 0s 8ô # Split it into (four) lists of size 8 § # Cast each integer to string (bug, shouldn't be necessary..) 2j # And pad leading spaces to make each string size 2 » # Join the inner lists by spaces, and then all strings by newlines }„ - # After the map: push string " -" 11× # Repeated 11 times to " - - - - - - - - - - -" ¶.ø # Surround it with newlines: "\n - - - - - - - - - - -\n" ý # And join the mapped strings with this delimiter-string # (after which the result is output implicitly) ``` [Answer] # JavaScript, 234 bytes. ``` for(a=[[],[],[],[],[],[]],i=1;i<64;i++)for(j=0;j<6;j++)i&2**j?a[j].push(i<10?" "+i:i):0;for(j=0;j<6;j++){for(s=[],i=0;i<4;)s.push(a[j].slice(i*8,++i*8).join(" "));b=s.join(n="\n");a[j]=b.substr(0,b.length)};a.join(n+" -".repeat(11)+n) ``` I will write explanation later. If `console.log` is required, the byte count would be 247 bytes. ]
[Question] [ A ragged array is an array where each element is an array of unknown number of positive integers. For example, the following are ragged arrays: ``` [[1,2,3],[4],[9,10]] Shape: 3,1,2 [[1],[2],[3]] Shape: 1,1,1 [[1,2,3,4,5,6,8]] Shape: 7 ``` The following are *not* ragged arrays: ``` [1] Each element will be an array [] The array will contain at least 1 element [[1,2,3],[]] Each subarray will contain at least 1 integer ``` **You need to input a ragged array, and return a ragged array with the integers shuffled** * The output array must have the same *shape* as the input array. We define the *shape* of the array as the length of each subarray. * Each integer must have an equally likely chance to appear in each possible location. * You can assume that your language's built-in random is random. For example, if I passed in: `[[4],[1,2,3],[4]]`, then `[[1],[4,4,2],[3]]` would be a valid output, but `[[4,1,3],[3],[4]]` or `[[4],[4],[1,2,3]]` would not. [Answer] # Jelly, 3 bytes in Jelly's codepage ``` FẊṁ ``` Explanation: ``` FẊṁ F flatten list Ẋ shuffle the output from the previous line ṁ unflatten the list, shaping it like… ``` Because the program is incomplete (`ṁ` doesn't have a second argument stated), the default is to use the program input; thus `ṁ` causes the output to have the same sublist pattern as the input. [Try it online!](https://tio.run/nexus/jelly#@@/2cFfXw52N////j4421DGK1Yk2BmITHVMds9hYAA "Jelly – TIO Nexus") [Answer] ## PowerShell v2+, 86 bytes ``` param($n)$a=$n-split'[^\d]'-ne''|sort{random};-join($n-split'\d+'-ne''|%{$_+$a[$i++]}) ``` Works via string manipulation. Input is passed in as a string representing the array, in whatever format works for *your* language. ;-) `-split`s out the input on non-digits, `sort`s them based on the `random` script block (which will assign a different random weight for each input to the sort), stores that into `$a`. We then `split` the input again, this time on digits, and for each one output the current value (usually brackets and commas) string-concatenated with the corresponding number from `$a`. That's `-join`ed together back into a string, and output is implicit. ### Examples ``` PS C:\Tools\Scripts\golfing> .\shuffle-a-ragged-array.ps1 "@(@(1,2,3),4)" @(@(3,2,1),4) PS C:\Tools\Scripts\golfing> .\shuffle-a-ragged-array.ps1 "@(@(1,2,3),4)" @(@(1,2,4),3) PS C:\Tools\Scripts\golfing> .\shuffle-a-ragged-array.ps1 "[[4],[1,2,3],[4]]" [[4],[2,4,3],[1]] PS C:\Tools\Scripts\golfing> .\shuffle-a-ragged-array.ps1 "[[10],[1,2,3],[5]]" [[10],[5,2,1],[3]] PS C:\Tools\Scripts\golfing> .\shuffle-a-ragged-array.ps1 "[[10],[1,2,3],[5]]" [[5],[10,2,1],[3]] ``` [Answer] # [Python 2](https://docs.python.org/2/), 89 bytes ``` from random import* x=input();r=sum(x,[]);shuffle(r) print[[r.pop()for _ in t]for t in x] ``` [Try it online!](https://tio.run/nexus/python2#FcZBCsMgEEDRfU7hUstQYttNCTnJMIRAIhWqDpMRvL1JFp//epCSjKx5uxYTF9HH0OaYuap1k8xHTbYBkpuOXw3hv1txA0vMiihPLmxdKGIWE7NRuqk3G/WO6OEFbwL8XH3Bj0Qn "Python 2 – TIO Nexus") [Answer] # JavaScript (ES6), ~~78~~ 75 bytes ``` x=>x.map(y=>y.map(z=>+s.splice(Math.random()*s.length,1)),s=eval(`[${x}]`)) ``` This is the first time I can remember using `.splice()` in a code-golf challenge... You can golf off two bytes by shuffling the array beforehand: ``` x=>x.map(y=>y.map(z=>s.pop()),s=eval(`[${x}]`).sort(_=>Math.random()-.5)) ``` However, this seems to put the last integer first the majority of the time, so I'm going to assume that the integers aren't uniformly distributed. [Answer] # Ruby, 47 bytes ``` ->a{b=a.flatten.shuffle;a.map{|x|x.map{b.pop}}} ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 17 bytes ``` ˜.r¹vDyg£DˆgF¦}}¯ ˜ Unflatten input .r tmp = shuffle(flattened_input) ¹v For each sub-array Dyg£ Take the first length(current_array) elements from tmp Dˆ Append the result to a global array gF¦} Remove the first elements from tmp } End for ¯ Display the global array ``` [Try it online!](http://05ab1e.tryitonline.net/#code=y5wucsK5dkR5Z8KjRMuGZ0bCpn19wq8&input=W1s0XSxbMSwyLDNdLFs0XV0) I'm waiting for the 05AB1E or 2sable solution using some unflattening/molding built-in I don't know yet :) . [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 17 bytes ``` c@~P,?:{l~l}a.cP, ``` [Try it online!](http://brachylog.tryitonline.net/#code=Y0B-UCw_Ontsfmx9YS5jUCw&input=W1sxOjI6M106WzRdOls5OjEwXV0&args=Wg) ### Explanation We basically create a list of sublists with variable elements that has the same "shape" as the Input, and then state that if we concatenate everything into a single list, it must result in a shuffle of the concatenation of the input into a single list. ``` c@~P, Concatenate the Input into a single list. Shuffle it and call that P. ?:{ }a. The Output is the result of applying this to each element of the input: l~l The Output is a list of same length as the Input. .cP, P is the concatenation of the sublists of the Output. ``` [Answer] # Bash, ~~63~~, 58 bytes EDITS: * Optimized *sed* expression a bit, -5 bytes Note: Bash does not really support multidimensional arrays (they can only be simulated, to some extent), so instead, this program will accept a "serialized" text representation of a rugged array, as depicted in the task description, e.g.: `[[1,2,3],[4],[9,10]]`, and provide output in the same format. **Golfed** ``` printf `sed 's/\w\+/%d/g'<<<$1` `grep -Po '\d+'<<<$1|shuf` ``` **Test** ``` >./shuffle [] [] >./shuffle [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] [11,12,9,5,3,6,1,15,14,2,13,7,10,8,4] >./shuffle [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] [9,15,11,10,7,6,1,14,2,3,12,5,4,13,8] >./shuffle [[1,2,3],[4],[9,10]] [[10,2,4],[9],[3,1]] >./shuffle [[1,2,3],[4],[9,10]] [[3,4,1],[10],[2,9]] ``` A nice bonus is that you can feed it rugged arrays of an arbitrary depth: ``` ./shuffle [[1,[2,[3,[99,101]]],[4],[9,10]] [[9,[4,[1,[101,2]]],[10],[3,99]] ``` and it will still operate correctly. [Try it online !](https://goo.gl/3a3KSg) [Answer] ## Perl, 37 bytes 36 bytes of code + `-p` flag. ``` @n=/\d+/g;s/\d+/splice@n,rand@n,1/ge ``` To run it: ``` perl -pE '@n=/\d+/g;s/\d+/splice@n,rand@n,1/ge' <<< "[[4],[1,2,3],[4]" ``` **Explanations:** ``` @n=/d+/g # store all the integers in @n s/\d+/ # replace each integer with ... splice@n,rand@n,1/ge # a element at a random position of @n (which is deleted from @n) ``` [Answer] # APL, 35 bytes I'm barely even beating Perl, there has to be something I'm missing. ``` {Z[?⍨⍴Z]⊂⍨(⍳⍴Z←∊⍵)∊⊃¨{⍵+⊃⌽⍺}\⍳¨⍴¨⍵} ``` E.g: ``` {Z[?⍨⍴Z]⊂⍨(⍳⍴Z←∊⍵)∊⊃¨{⍵+⊃⌽⍺}\⍳¨⍴¨⍵}(1 2 3)(,4)(9 10) ┌──────┬─┬───┐ │10 3 2│1│9 4│ └──────┴─┴───┘ ``` Explanation: * Find the corresponding indices of the starts of the sub-arrays in a flattened array: + `⍳¨⍴¨⍵`: For each sub-array, get a list of the indices + `{⍵+⊃⌽⍺}\`: Starting with the first sub-array, add the last value in the array to each value in the next array. + `⊃¨`: get the first items of the arrays, which are the starting places + `(⍳⍴Z←∊⍵)∊`: store the flattened array in `Z`. Generate a bit-vector where the ones mark the places where the sub-arrays should start. * Shuffle the flattened array: + `?⍨⍴Z`: generate a random permutation of `Z`. + `Z[`...`]`: permute `Z`. * `⊂⍨`: Split up the permutation in sub-arrays according to the bit-vector. [Answer] # Pyth, 15 bytes ``` tPc.SsQ.u+NlYQ0 ``` A program that takes input of a list and prints the result. [Test suite](http://pyth.herokuapp.com/?code=tPc.SsQ.u%2BNlYQ0&test_suite=1&test_suite_input=%5B%5B1%2C2%2C3%5D%2C%5B4%5D%2C%5B9%2C10%5D%5D%0A%5B%5B1%5D%2C%5B2%5D%2C%5B3%5D%5D%0A%5B%5B1%2C2%2C3%2C4%2C5%2C6%2C8%5D%5D&debug=0) **How it works** ``` tPc.SsQ.u+NlYQ0 Program. Input: Q .u Q0 (1) Reduce Q with starting value 0, returning all results: + Add N the current value lY to the length of the next element of Q sQ Flatten Q .S (2) Randomly shuffle c Chop (1) at every location in (2) tP Discard the first and last elements Implicitly print ``` [Answer] # **PHP**, 105 bytes ``` $m=array_merge(...$i=$_GET[i]);shuffle($m);foreach($i as$v)$o[]=array_splice($m,0,count($v));print_r($o); ``` reduced to 105 bytes thanks to `user59178`. Original answer: # **PHP**, 132 bytes ``` $i=$_GET['i'];$m=call_user_func_array('array_merge',$i);shuffle($m);foreach($i as$v){$o[]=array_splice($m,0,count($v));}print_r($o); ``` [Answer] ## Mathematica, 67 Bytes ``` ReplacePart[#,Thread[RandomSample@Position[#,_Integer]->Union@@#]]& ``` Explanation: This shuffles the list of positions of all integers in the 2D ragged array. `Union@@` is short for `Flatten@` Note: Squiggly brackets `{}` are used instead of brackets `[]`. [Answer] # [Factor](https://factorcode.org/) + `arrays.shaped`, 67 bytes ``` [ [ flatten randomize ] [ array-replace ] bi [ cut swap ] map nip ] ``` [Try it online!](https://tio.run/##TY67DsIwDEV3vuL@ABVQ3ixsiIUFMVUMITUiok2DE4QK4tuDUyHBcnV8riz7rHRoOB72291mCcWsWp/5i3JUwtPtTlaTz0oiB1a2bGpciS1VvxKOKYTWsbEBq17vhReGGCHHW2jc5QLDgcD7WyY16jL/s2lljAmmmGGefCxQ4FypEMh@r5sn4Si2e7TP5CqlkzkZkfoe4B/KyVxLWiMUA5u1dJnIhPED "Factor – Try It Online") ## Explanation Assumes the input is always a 2D array. * `[ flatten randomize ] [ array-replace ] bi` Place the flat, shuffled version of the input and the lengths of its rows on the stack. * `[ cut swap ] map nip` Create a ragged array from a flat sequence and a list of lengths. See <https://codegolf.stackexchange.com/a/233190/97916>. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 18 bytes ``` {(,/x)@<==0N?&#'x} ``` [Try it online!](https://ngn.codeberg.page/k#eJylyFEOgiAAgOF3TsHWVrohCOJDmtUJugBjiyFgy8QEN1vr7tkZevr2/7Z6J4gs6fnQNPnltN3slg8A13EanMglsDBBvKaQwaJGPP27AQFdjGOoCNG+Nc73Foeo9N0sulODM1j7B3nOJsSbHwKhOSv3JQndbG1vMpVNyjnTZmqa1AsAIbhEgiKGilUuJWyO0GCHoRD0dxBHbLWQ8gtlFT2a) * `&#'x` build a list containing n-copies of each top level index, where n is the length of each element of the ragged list (e.g. `0 1 1 1 2`) * `0N?` shuffle that list * `<==` group the indices, group them again (to essentially flip the keys and values of the dictionary), and sort them ascending (this preserves the original order of the lengths) * `(,/x)@` index into the flattened input and (implicitly) return [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` fÞ℅$• ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJmw57ihIUk4oCiIiwiIiwiW1sxLDIsM10sWzRdLFs5LDEwXV0iXQ==) ``` f # Flatten Þ℅ # Shuffle $• # Mold to original shape ``` [Answer] # Octave , 60 bytes ``` @(a)mat2cell([a{:}](randperm(sum(s=cellfun(@numel,a)))),1,s) ``` [Answer] # **MATLAB**, 84 bytes ``` function b=g(c);a=[c{:}];a=a(randperm(numel(a)));b=mat2cell(a,1,cellfun('length',c)) ``` [Answer] # Java, 368 bytes ``` interface Z{int w(int i);default Z m(int n,int s){return i->w(i)+i>=n?s:0;}static int[][]f(int[][]r){int L=0,o=0,x,d,e=0;Z u=i->0,v=i->i;for(int[]a:r){d=a.length;L+=d;u=u.m(L,1);v=v.m(L,-d);}int[]c=new int[L];for(;e<L;)c[e++]=(int)(L*Math.random());for(int[]a:r){for(x=0;x<a.length;){d=c[x+o];e=v.w(d);d=u.w(d);L=a[x];a[x++]=r[d][e];r[d][e]=L;}o+=a.length;}return r;}} ``` the method `static int[][] f( int[][] r ){...}` solves the challenge. decided to roll my own functional interface to avoid an import and to add in a default method for ease of use ``` interface Z{ //define my own functional interface instead of importing int w(int i); //return a new lambda //where w(int i) adds the value s //to the result when i is greater than n default Z m(int n,int s){ return i->w(i)+i>=n?s:0; } static int[][]f(int[][]r){ int L=0,o=0,x,d,e=0; Z u=i->0, //lambda to convert a flattened index to the input's first dimension index v=i->i; //lambda to convert a flattened index to the input's second dimension index for(int[]a:r){ d=a.length; L+=d; //running total of the lengths u=u.m(L,1); //increment the 1st conversion by 1 at every array length v=v.m(L,-d); //decrement the 2nd conversion by the array length after that length } int[]c=new int[L]; //will contain flattened index swapping positions for(;e<L;) //randomize the swap positions c[e++]=(int)(L*Math.random()); for(int[]a:r){ //swap the elements from the input for(x=0;x<a.length;){ d=c[x+o]; //flattened swap index e=v.w(d); //convert swap index to 2nd dimension index d=u.w(d); //convert swap index to 1st dimension index L=a[x]; a[x++]=r[d][e]; r[d][e]=L; } o+=a.length; //increment offset for flattened index array } return r; } } ``` [Answer] # [q](https://code.kx.com/q), 36 bytes ``` {(0,sums -1_count each x)_0N?raze x} ``` # k, 22 bytes ``` {(0,+\-1_#:'x)_0N?,/x} ``` ]
[Question] [ # Introduction Everyone's heard of [sine (sin)](https://en.wikipedia.org/wiki/Sine), [cosine (cos)](https://en.wikipedia.org/wiki/Trigonometric_functions#Sine.2C_cosine_and_tangent), [tangent (tan)](https://en.wikipedia.org/wiki/Trigonometric_functions#Sine.2C_cosine_and_tangent), [cotangent (cot)](https://en.wikipedia.org/wiki/Trigonometric_functions#Right-angled_triangle_definitions), [secant (sec)](https://en.wikipedia.org/wiki/Trigonometric_functions#Secant), and [cosecant (csc)](https://en.wikipedia.org/wiki/Trigonometric_functions#Right-angled_triangle_definitions). Nearly every angle has them. Far less known, or remembered, are the [exsecant (exsec)](https://en.wikipedia.org/wiki/Exsecant), [excosecant (excsc)](https://en.wikipedia.org/wiki/Exsecant), [versine (versin)](https://en.wikipedia.org/wiki/Versine#Definitions), and [coversine (cvs)](https://en.wikipedia.org/wiki/Versine#Definitions). Nearly every angle has those as well. There are some that are *even less* known, but we'll just stick to these. I've created a visualization of these for angle θ, which is 45°. ![](https://i.stack.imgur.com/WGOTW.png) --- # The Challenge Create a program that takes an input of an angle `n`, in degrees, and will output: 1. the sine of angle `n` 2. the cosine of angle `n` 3. the tangent of angle `n` 4. the secant of angle `n` 5. *at least* one of the following. Every additional item from this list will earn a bonus -5%, for a maximum of -25%. * exsecant of angle `n` * cosecant of angle `n` * excosecant of angle `n` * versine of angle `n` * coversine of angle `n` * cotangent of angle `n` If your score is a decimal after applying a bonus, round up to the nearest whole number. --- # Input You may accept your input through STDIN or through a function call. A single argument, `n`, will be passed. `n` will always be a whole integer that is greater than 0, but less than or equal to 90. --- # Output Here is an example of the output for sine of 45°. All output items must be in this format. The order of the items does not matter. ``` sine: 0.70710678118 ``` All items must have exactly 4 numbers after the decimal (precision to the ten-thousandths). Below are a few examples of rounding. ``` 0 -> 0.0000 1 -> 1.0000 0.2588190451 -> 0.2588 5.67128181962 -> 5.6713 10 -> 10.0000 12.4661204396 -> 12.4661 ``` Any nonexistent/undefined results should default to 0. --- # Example ``` myprogram(60) sine: 0.8660 cosine: 0.5000 tangent: 1.7321 secant: 2.0000 exsecant: 1.0000 cosecant: 1.1547 excosecant: 0.1547 versine: 0.5000 coversine: 0.1340 cotangent: 0.5774 ``` --- # Scoreboard For your score to appear on the board, it should be in this format: ``` # Language, Score ``` Or if you earned a bonus: ``` # Language, Score (Bytes - Bonus%) ``` Strikethroughs shouldn't cause a problem. ``` function getURL(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 getAnswers(){$.ajax({url:getURL(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){var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),useData(answers)}})}function getOwnerName(e){return e.owner.display_name}function useData(e){var s=[];e.forEach(function(e){var a=e.body.replace(/<s>.*<\/s>/,"").replace(/<strike>.*<\/strike>/,"");console.log(a),VALID_HEAD.test(a)&&s.push({user:getOwnerName(e),language:a.match(VALID_HEAD)[1],score:+a.match(VALID_HEAD)[2],link:e.share_link})}),s.sort(function(e,s){var a=e.score,r=s.score;return a-r}),s.forEach(function(e,s){var a=$("#score-template").html();a=a.replace("{{RANK}}",s+1+"").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SCORE}}",e.score),a=$(a),$("#scores").append(a)})}var QUESTION_ID=58283,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],answer_ids,answers_hash,answer_page=1;getAnswers();var VALID_HEAD=/<h\d>([^\n,]*)[, ]*(\d+).*<\/h\d>/; ``` ``` body{text-align:left!important}table thead{font-weight:700}table td{padding:10px 0 0 30px}#scores-cont{padding:10px;width:600px}#scores tr td:first-of-type{padding-left:0} ``` ``` <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="scores-cont"><h2>Scores</h2><table class="score-table"><thead> <tr><td></td><td>User</td><td>Language</td><td>Score</td></tr></thead> <tbody id="scores"></tbody></table></div><table style="display: none"> <tbody id="score-template"><tr><td>{{RANK}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SCORE}}</td></tr></tbody></table> ``` [Answer] # CJam, ~~94~~ ~~89~~ ~~85~~ ~~81~~ 80 bytes ``` "sine tangent secant"S/{"co"1$+}%rd90/_i33Yb@[P*2/__ms\mc@mt]_Wf#W%+?.{d": %.4f"e%N} ``` The code is 84 bytes long and qualifies for a 5% bonus (*cotangent* and *cosecant*). Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%22sine%20tangent%20secant%22S%2F%7B%22co%221%24%2B%7D%25rd90%2F_i33Yb%40%5BP*2%2F__ms%5Cmc%40mt%5D_Wf%23W%25%2B%3F.%7Bd%22%3A%20%25.4f%22e%25N%7D&input=60). ### How it works ``` "sine tangent secant" e# Push that string. S/ e# Split it at spaces. {"co"1$+}% e# For each chunk, append a copy to the string "co", pushing e# ["sine" "cosine" "tangent" "cotangent" "secant" "cosecant"]. rd90/ e# Read a Double from STDIN and divide it by 90. _i e# Push a copy and cast it to integer. 33Yb e# Push 33 in base 2, i.e., [1 0 0 0 0 1]. @ e# Rotate the Double on top of the stack. [ e# P*2/ e# Multiply by Pi and divide by 2. __ e# Push two copies of the result. ms e# Compute the sine of the topmost copy. \mc e# Swap and compute the cosine of the next copy. @mt e# Rotate and compute the tangent of the original. ] e# _Wf# e# Copy the array and raise all Doubles to the power -1. e# This computes cosecant, secant and cotangent. W% e# Reverse their order. + e# Append to the original array. ? e# Select 33Yb if the integer part of the input divided by 90 is e# (i.e., if the input is 90), the constructed array otherwise. .{ e# For each function name and result: d e# Cast to Double (needed for 33Yb). ": %.4f" e# Push a format string containing ": " and a 4-decimal float. e% e# Apply the formatting to the Double on the stack. N e# Push a linefeed. } e# ``` [Answer] # Julia, 162 - 10% = 144 bytes ``` n->for z=zip(split("sine cosine tangent secant exsecant cosecant cotangent"),[sind,cosd,tand,secd,i->secd(i)-1,cscd,cotd]) @printf("%s: %.4f\n",z[1],z[2](n))end ``` Ungolfed: ``` function f(n) # Construct a vector of names s = split("sine cosine tangent secant exsecant cosecant cotangent") # Construct a vector of functions o = [sind, cosd, tand, secd, i -> secd(i) - 1, cscd, cotd] # Print each in a loop for z = zip(s, o) @printf("%s: %.4f\n", z[1], z[2](n)) end end ``` [Answer] # Pyth, 66 - 10% = 59.4 bytes ``` j+V+Jc"sine secant tangent")+L"co"Jsmm%": %.4f"^.t.td7k^_1k3,Q-90Q ``` Calculates the sine, secant and tangent. Then, the co- functions are simply calculated via the formula `coF(x) = F(90 - x)`. [Answer] ## Mathematica (Invalid at the moment), ~~134~~ ~~121~~ 104 Just for fun, surely it can be golfed down a lot ``` f[n_]:=(a={Sin,Cos,Tan,Sec,Cot,Csc};TableForm[N[#@n,4]&/@a,TableHeadings->{ToString[#]<>":"&/@a,None}]) ``` And it should have a 5% bonus (Cot and Csc), therefore amounting at 99 characters Example output: [![Example Output](https://i.stack.imgur.com/MJ5Ot.png)](https://i.stack.imgur.com/MJ5Ot.png) [Answer] # JavaScript (ES6), 173 (182 - 5%) **Edit** revised after clarification, now the bonus is 5% **Edit** realized that the angle can not be 0 ``` // TEST - redefine alert alert=x=>O.innerHTML=x r=(a=prompt(i=0))*(M=Math).PI/180,V=_=>[s=M.sin(r),c=M.cos(r),(f=a-90)&&s/c,c/s,f&&1/c,1/s][i++].toFixed(4); alert(`sine tangent secant`.replace(/.+/g,h=>h+`: ${V()} co${h}: ${V()}`)) /* More bonus, but too longer r=(a=prompt(i=0))*(M=Math).PI/180,V=_=>[s=M.sin(r),c=M.cos(r),1-c,1-s,(f=a-90)&&s/c,c/s,f&&1/c,1/s][i++].toFixed(4); alert(`sine versine tangent secant`.replace(/.+/g,h=>h+`: ${V()} co${h}: ${V()}`)) */ ``` ``` <pre id=O></pre> ``` [Answer] # Javascript ES6, ~~154~~ 148 (198 - 25%) ``` (n=0)=>[S='sine',(O='co')+S,T='tangent',C='secant',X=O+C,O+T,V='ver'+S,O+V,'ex'+C,'ex'+X].map((q,i)=>q+': '+[s=Math.sin(n),c=Math.cos(n),t=s/c,e=1/c,o=1/s,1/t,1-c,1-s,e-1,o-1][i].toFixed(4)).join` ` ``` Ungolfed: ``` (n=0)=> // function declaration, accepts number, defaults to 0 [ // create array of trig function names S='sine', // sine (O='co')+S, // cosine T='tangent', // tangent C='secant', // secant X=O+C, // cosecant O+T, // cotangent V='ver'+S, // versine O+V, // coversine 'ex'+C, // exsecant 'ex'+X // excosecant ].map((q,i)=> // map over names // append ": <value rounded to 4 decimals>" to function name: q+': '+[s=Math.sin(n),c=Math.cos(n),t=s/c,e=1/c,o=1/s,1/t,1-c,1-s,e-1,o-1][i].toFixed(4) ).join` // add newline between each function ` ``` [Answer] # R, ~~122~~ ~~136~~ 134 bytes ``` n=scan()*pi/180;write(paste0(c("sine","cosine","tangent","secant","versine"),sprintf(": %.4f",c(sin(n),r<-cos(n),tan(n),1/r,1-r))),"") ``` --- **Example usage** ``` > n=scan()*pi/180;write(paste0(c("sine","cosine","tangent","secant","versine"),sprintf(": %.4f",c(sin(n),r<-cos(n),tan(n),1/r,1-r))),"") 1: 60 2: Read 1 item sine: 0.8660 cosine: 0.5000 tangent: 1.7321 secant: 2.0000 versine: 0.5000 ``` [Answer] # Perl, ~~182~~ 177 (236 - 25%) Run with `-n` (1 byte added to uncorrected score). ``` $b=$_==90;$_/=57.296;$c=cos;$s=sin;sub f{printf"%s: %.4f\n",@_}$T=tangent;f$T,$b?0:$s/$c;f co.$T,$c/$s;$S=sine;f $S,$s;f co.$S,$c;$C=secant;f$C,$b?0:1/$c;f co.$C,1/$s;f ex.$C,$b?0:1-1/$c;f exco.$C,1/$s-1;$V=ver.$S;f$V,1-$c;f co.$V,1-$s ``` Nothing fancy. It takes advantage of `-n` for implicit input, `$_` as a default argument to `sin` and `cos`, and barewords for strings. The “undefined = 0” rule is hardcoded in using the ternary operator `?:` (it applies only for 90°). One thing I learend is that apparently, you cannot have (or cannot *call*) a subroutine named `s` (or `m`, `y`, `tr`): `sub s {print 1}; s` yields `Substitution pattern not terminated at -e line 1`. [Answer] # Python 3, 282 (375 - 25%) Error handling turned out to be somewhat complicated by floating-point errors; namely, `cos(90)` came out to a very small number instead of zero. It's never going to be the top answer, but I like to think it **might** be the [shortest valid all-functions answer in a non-golfy language that doesn't have the trig functions in the default namespace](http://tvtropes.org/pmwiki/pmwiki.php/Main/OverlyNarrowSuperlative). ;-) ``` import math as m def p(q,r):print(q+':','%.4f'%r) def a(n): n=n*m.pi/180 C,S=round(m.cos(n),8),m.sin(n) A=S,1,0,C,1,S,C,0,C,S,1,C,0,1,S,1,C,-1,1,S,C,1,1,S,1 def t(): nonlocal A;u,v,w,x,y,*A=A;z=-1 if w>0 else 1 try:return z*u/v+w,z*x/y+w except:return 0,0 def q(y,x=''):J,K=t();p(x+y,J);p(x+'co'+y,K) q('sine');q('tangent');s='secant';q(s);q(s,'ex');q('versine') ``` Sample output: ``` >>> a(60) sine: 0.8660 cosine: 0.5000 tangent: 1.7321 cotangent: 0.5774 secant: 2.0000 cosecant: 1.1547 exsecant: 1.0000 excosecant: 0.1547 versine: 0.5000 coversine: 0.1340 ``` [Answer] # Perl, 165 (193 - 15%) I am submit this a s a new answer because the idea is quite different from the [other](https://codegolf.stackexchange.com/a/58397/34438) one. Please let me know if it is more appropriate to replace my first attempt. ``` $p=atan2 1,0;$b=$_-90;%h=qw(sine $s tangent $b?$s/$c:0 secant $b?1/$c:0 versine 1-$c);$_/=90/$p;sub e{$c=cos;$s=sin}e;sub f{eval"printf'$x$_: %.4f ',$h{$_}"for keys%h}f;$b=1;$_=$p-$_;e;$x=co;f ``` Run with `-n` (1 byte added). Ungolfed: ``` # π/2 $p=atan2 1,0; # trouble? $b=$_-90; # Construct a hash whose keys are the “base” function names, # and whose values are the corresponding expressions in terms of sin and cos %h=qw(sine $s tangent $b?$s/$c:0 secant $b?1/$c:0 versine 1-$c); # Thanks to ‘-n’, input is in $_; convert to radians $_/=90/$p; # Compute sin and cos in a reusable way sub e{$c=cos;$s=sin} e; sub f { eval "printf '$x$_: %.4f ', $h{$_}" for keys %h } f; # Now the “co” functions # No trouble here $b=1; # x ← π/2 - x $_=$p-$_; e; $x=co; f ``` Since it does the four “co”-functions, I think it qualifies for a 3\*5% = 15% bonus. [Answer] # Perl, ~~100~~ ~~95~~ 94 bytes Whoa, lotta perl answers. ``` $_=<>;printf"sine: %.4f\ncosine: %.4f\ntangent: %.4f\nsecant: %.4f\n",sin,cos,(sin)/cos,1/cos ``` [Answer] # Haskell, 159 = 186 - 15% bytes ``` s x=zipWith(\a b->a++": "++show b)(concatMap(\n->[n,"co"++n])$words"sine tangent versine secant")$map($(x*pi/180))[sin,cos,t,(1/).t,(1-).cos,(1-).sin,e.t,e.(1/).t] e=sqrt.(+1).(^2) t=tan ``` No ex-thingies to keep my clever naming scheme and since I didn't know how to shorten `(\x->x-1)`. `(-1)` is just a number. Please complain if you want me to prettify (`mapM_ putStrLn`) the lines. ]
[Question] [ I came across an interesting tiling of the plane using squashed hexagons in a popular math book. All the six edges of the squashed hexagon are the same length. Two opposite corners are right angles and the rest four corners are 135 degrees each. This shape allows four squashed hexagons be arranged so that they meet at a point. Then “concentric rings” of squashed hexagons can outline the resulting cross indefinitely. [![Initial cross](https://i.stack.imgur.com/vve8c.jpg)](https://i.stack.imgur.com/vve8c.jpg) [![3 rings](https://i.stack.imgur.com/RmR84.jpg)](https://i.stack.imgur.com/RmR84.jpg) Write a full program or a function that accepts an integer 0 < `n` < 10 and renders `n` rings of this tessellation. You can rotate the image by 45 dergrees if it's more convenient for your algorithm. You can render directly to the screen, or save the result to a file. In either case, please provide an image demonstrating the the result of your code. You can crop the resulting image so that it contains only the hexagons. ## Examples: n = 1 [![n=1](https://i.stack.imgur.com/vve8c.jpg)](https://i.stack.imgur.com/vve8c.jpg) n = 2 [![n=2](https://i.stack.imgur.com/vXHrt.jpg)](https://i.stack.imgur.com/vXHrt.jpg) n = 3 [![n=3](https://i.stack.imgur.com/RmR84.jpg)](https://i.stack.imgur.com/RmR84.jpg) n = 4 [![4 rings](https://i.stack.imgur.com/gu6I8.jpg)](https://i.stack.imgur.com/gu6I8.jpg) The shortest code in bytes in each language wins. [Answer] ## JavaScript (ES6), ~~319~~ 313 bytes ``` f= n=>{s=`<svg viewBox=${n*=-12},${n},${n*=-2},${n}><use href=#d transform=rotate(180) /><g id=d><use href=#s transform=rotate(90) /><path id=s fill=none stroke=#000 d=` for(n/=24;n--;)for(j=0;j<=n;j++)s+=`M${n*5+j*7},${n*12-j*7}h7l5,5v7h-7l-5,-5z`+(j<n?`M${n*12},${n*5-j*10}h7l5,-5l-5,-5h-7l-5,5z`:``) return s+`>`} ``` ``` <input type=number min=1 oninput=o.innerHTML=f(this.value)><div id=o> ``` Output is an HTML5 SVG, which the snippet inserts into a DOM node so that you can see it. Output is rotated by 45° as allowed by the question. Edit: Saved 3 bytes thanks to @KevinCruijssen. [Answer] # [GFA Basic 3.51](https://en.wikipedia.org/wiki/GFA_BASIC) (Atari ST), ~~187 181 174~~ 171 bytes A manually edited listing in .LST format. All lines end with `CR`, including the last one. ``` PRO f(n) DR "MA166,94" t$="FD8LT45PD" h$=t$+"FD8LT90"+t$+t$+"FD8LT90FD8BK8LT90FD8RT45" a$="" F i=1TO n DR STRING$(4,a$+h$+"LT45BK8"+a$+t$)+"PUFD8RT45"+t$ a$=a$+h$ N i RET ``` ### Expanded and commented ``` **PROCEDURE f(n)** ' move the pen at (166,94) **DRAW "MA166,94"** ' t$ = move forward by 8, left turn of 45 degrees, pen down **t$="FD8LT45PD"** ' h$ holds the directives to draw a single hexagon ' and get ready to draw a contiguous hexagon **h$=t$+"FD8LT90"+t$+t$+"FD8LT90FD8BK8LT90FD8RT45"** ' a$ is used to store a concatenation of hexagons **a$=""** ' draw n rings **FOR i=1 TO n** ' draw a full ring and move to the next ring **DRAW STRING$(4,a$+h$+"LT45BK8"+a$+t$)+"PUFD8RT45"+t$** ' append a new hexagon to a$ **a$=a$+h$** **NEXT i** **RETURN** ``` ### Example output [![enter image description here](https://i.stack.imgur.com/Rzi70.png)](https://i.stack.imgur.com/Rzi70.png) [Answer] ## Logo, ~~276~~ 245 bytes ``` to i:n repeat 2[repeat:n[repeat 2[fd 7 rt 45]fd 7 bk 7 lt 90]rt 90 fd 7 rt 90]end to j:n make"m:n repeat:n[i:m make"m:m-1 rt 90 repeat 2[fd 7 lt 45]]repeat:n[repeat 2[rt 45 bk 7]lt 90]end to k:n repeat 4[j:n rt 90 fd 7 lt 45 j:n-1 rt 45 bk 7]end ``` Use `k <n>` to invoke. Output is rotated by 45° as allowed by the question. Example for `n=10`: [Try it online!](http://logo.twentygototen.org/x6AIFvYp) [Answer] # [Python 3](https://docs.python.org/3/), ~~361~~ 342 bytes ``` from turtle import* def t(a):r(a);fd(9) def k(i):Q.add((o+i,pos(),heading(),m)) u=45;n=int(input());Q=set((1,(0,0),a*90,a>3)for a in range(8));ht() while Q: o,p,a,m=Q.pop() if round(o)>n:continue r=(rt,lt)[m];g=not o%1;up();goto(*p);seth(a);pd();t(-u) if g:k(1.1) t(u) if g:k(1) t(u);t(-u);k(2+g/3);undo();undo();t(90);t(u);t(u) done() ``` [![program output for n=10](https://i.stack.imgur.com/rTPV9.png)](https://i.stack.imgur.com/rTPV9.png) [Answer] ## Shadertoy (GLSL), ~~777 710 679 644 630~~ 609 bytes ``` #define V vec2 #define F float #define R return const int n=10;const F Z=2.2/F(n),W=.01*Z,L=.07*Z,K=L/2.,M=K*1.414;F h(V u,V c){u=abs(u-c); if(u.x>.0&&u.x<K)R abs(u.y-M)<W/1.4?.0:1.;else if(u.x<K+M+W)R abs(u.y-M+u.x-K)<W?.0:1.;R 1.;} F m(V u,V c){u=abs(u);R h(u,c)*h(u.yx,c);}void mainImage(out vec4 f,in V c){V S=iResolution.xy;V v=c/S-V(.5); v.y/=S.x/S.y;F b=-atan(1.);mat2 o=mat2(cos(b),-sin(b),sin(b),cos(b));V w=o*v;F s=1.,a=K+M,k=.0,l;int i,j,J; for(i=0;i<n;i++,k++){J=i/2+1;l=.0;for(j=0;j<J;j++,l++){F z=l*2.*M;if(i%2==1)z+=M; s*=m(v,V(a+k*(L+M),z));if(i<n-1)s*=m(w,V(a+k*(L+M)+L,z));}}f.xyz=vec3(s);} ``` [Shadertoy link](https://www.shadertoy.com/view/tsBfRW) Happy to finally see this working, the tile layout can be a bit puzzling at first. It automatically "zooms in" for lower n values, but can also be manually adjusted by changing the `Z` variable because it's not optimal. Something is a bit wrong with the line drawing where diagonal and straight lines meet (which gets more apparent for lower `n` values), perhaps I'll find a way to get that fixed. There also is an [ungolfed version](https://www.shadertoy.com/view/3sSBRW) with some comments on how it does things. Output for `n` = 10: [![enter image description here](https://i.stack.imgur.com/95ipY.png)](https://i.stack.imgur.com/95ipY.png) [Answer] # JavaScript + HTML + CSS, 82 + 39 + 204 = 325 bytes ### JavaScript Function that takes a number `n`. An internal function `P` recursively generates an ASCII pyramid of `⬡` characters, formatted as a CSS string with `\a` line breaks. On the HTML element with `id="X"`, sets the custom CSS custom properties `--` and `---` to `P(n)` and `P(n-1)`, respectively. ``` n=>X.style=`--:"${(P=n=>(n?P(n-1)+`\\a`:'')+'⬡'.repeat(n))(n-1)}";---:"${P(n)}"` ``` ### HTML 8 nested HTML elements whose `:after` pseudo-elements will contain hexagon pyramids; wrapped in a `<pre>` to show line breaks. `<center>` ensures pyramids are centered horizontally. ``` <pre><center id=X><i><b><i><b><i><b><i> ``` ### CSS Applies `transform: rotate(45deg)` to all elements; the rotation effect compounds for the 8 nested elements. Applies `content` such that `i:after` gets the bigger pyramid `---`, and `center:after` and `b:after` get the smaller pyramid `--`. Squishes the ASCII hexagon pyramids into a (decently accurate) tile pattern via `font-size`, `line-height`, `letter-spacing`, and `transform` – results may vary depending on your browser. ``` *{display:flex;place-content:center;transform:rotate(45deg)}:after{font:150%/.62 auto;letter-spacing:-5px;position:absolute;transform:matrix(.69,0,0,1,-1.75,-5);content:var(--)}i:after{top:-8px;--:var(--- ``` --- Output for `n` = 10 (Chromium 81, macOS): [![Tile the plane with squashed hexagons - JavaScript + HTML + CSS, 82 + 39 + 204 = 325 bytes](https://i.stack.imgur.com/we5wA.png)](https://i.stack.imgur.com/we5wA.png) --- ## Try it! ``` f= n=>X.style=`--:"${(P=n=>(n?P(n-1)+`\\a`:'')+'⬡'.repeat(n))(n-1)}";---:"${P(n)}"` f(+prompt()) ``` ``` head,script{display:none !important} body{margin:50vmin} *{display:flex;place-content:center;transform:rotate(45deg)}:after{font:150%/.62 auto;letter-spacing:-.23em;position:absolute;transform:matrix(.71,0,0,1,-1.75,-5);content:var(--)}i:after{top:-.34em;--:var(--- ``` ``` <pre><center id=X><i><b><i><b><i><b><i> ``` ]
[Question] [ Write a function or program which takes as input a set of distinct, non-negative integers \$\{x\_1, \ldots, x\_n\}\$ and outputs the smallest gap between any two values in the set, i.e. \$\min\_{i\neq j}|x\_i-x\_j|\$. ### Scoring **This is not code golf.** Your score is the smallest gap of the set of code points of characters in your code (**highest score wins**). In other words: convert your code to integer code points (using ASCII or whatever code page is standard for your language); remove duplicates; use that as input to your program; the output is your score. For instance, if your code is `min(alldifferences(input))`, to get your score convert `m->109`, `i->105`, `n->110`, `(->40`, ... and your score will be 1, since the codepoints for `m` and `n` are only 1 apart. You may assume that the input contains at least 2 distinct values; behaviour is undefined otherwise. Your code must include at least two distinct characters. If your encoding is ASCII, you can use [this online R code](https://tio.run/##FcqxEYAwCADAVbhUZAMbB7B3gwQ0hXASKJwe9eu3TIYVOKT5UMFZ4RqCfTDjVHMMGXcQhvOy6yb@jV8ylkfDoGknOJQmnGRUar4 "R – Try It Online") to verify your score. ### Test cases ``` Input | Output 0 1 2 3 4 | 1 2 4 8 16 32 | 2 1 | undefined 3 14 159 2653 | 11 4 6 8 9 12 14 | 1 3 14 2 | 1 ``` [Default rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output apply. In particular, since the input is a set, you may assume any structure for the input. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: ~~22~~ ~~49~~ 69 (~~5~~ 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) ``` ê¥êн ``` Uses the [05AB1E encoding](https://github.com/Adriandmen/05AB1E/wiki/Codepage), where the bytes have the codepoints [`[234,165,234,14]`](https://tio.run/##ARkA5v9vc2FiaWX//8W@xIZJU2v//8OqwqXDqtC9) (`ê¥` are 69 apart). +27 score by porting [*@Arnauld*'s approach](https://codegolf.stackexchange.com/a/196794/52210) of sorting. +20 score (and even -1 byte at the same time) thanks to *@Grimmy*. [Try it online](https://tio.run/##yy9OTMpM/f//8KpDSw@vurD3//9oIzNTYx1jHUMTHUNTy1gA) or [verify all test cases](https://tio.run/##NYy9DcIwFIRXiVJfwfuxsasMYrkAiYKKAgkpCzAAO9BkBxqyADOwiDkjpXg63d2773I9HM@ndpuncfjeH8M4zW1d3s91@bwaWik7CBQGrygKR4JEmNIJzyAOCRkag/UPCraQ3hG5yBBl1vugpKka0h6JXd4gnajGXQz4q9f6Aw). **Explanation:** ``` ê # Sort and uniquify the (implicit) input-list (in ascending order) ¥ # Get the deltas of this sorted list ê # Sort and uniquify this again н # Pop this list and push its first item # (which is output implicitly as result) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), Score = 12 ``` ⊇ᶠl₂ˢ-ˢȧˢ⌋ ``` [Try it online!](https://tio.run/##ATUAyv9icmFjaHlsb2cy///iiofhtqBs4oKCy6Ity6LIp8ui4oyL//9bMywxNCwxNTksMjY1M13/Wg "Brachylog – Try It Online") The minimum gap is 12, between `⊇` and `⌋`, and also between `ᶠ` and `ˢ` ([see the code page](https://github.com/JCumin/Brachylog/wiki/Code-page)). ### Explanation ``` ⊇ᶠ Find all subsets of the input l₂ˢ Only keep those that have a length of 2 -ˢ Compute the difference of each subset ȧˢ Compute the absolute value of each difference ⌋ Output is the smallest one ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes, score 3 ``` I⌊Eθ⌊ΦEθ↔⁻ιλλ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczLzO3NFfDN7FAo1BHAcZ1y8wpSS2CiTomFefnlJakglSXFmtk6ijkaGpqQkggsP7/PzraoMLZUkfBoMIQTDqbgkg3QxBpaQYiHV1ApCtY1tU5Nva/blkOAA "Charcoal – Try It Online") Link is to verbose version of code and takes the code's own code points as input. Explanation: ``` θ Input array E Map over elements θ Input array E Map over elements ι Outer element λ Inner element ↔⁻ Take the difference Φ λ Filter out zero values ⌊ ⌊ Take the minimum of the minima I Cast to string for implicit print ``` Charcoal's loop variables are implicit but fortunately `Map` consumes two variables and even more fortunately there is no variable `j` so there is actually a minimum difference of 3. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes, score = 24 This is most probably sub-optimal. Uses [Jelly code page](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page). ``` ṢIṢ1ị ``` [Try it online!](https://tio.run/##y0rNyan8///hzkWeQGz4cHf3////ow0qnMx1FAwqTCxBpLEhiHSxiAUA "Jelly – Try It Online") (with the code points of the source code) ### Commented ``` ṢIṢ1ị - a monadic link taking a list, e.g. [183, 73, 49, 216] Ṣ - sort in ascending order -> [49, 73, 183, 216] I - get increments -> [24, 110, 33] Ṣ - sort in ascending order -> [24, 33, 110] 1ị - extract the first element -> 24 ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), 3 bytes, score = 36 ``` ȯọ⌋ ``` [Try it online!](https://tio.run/##S0/MTPz//8T6h7t7H/V0/0991Dbxf7SxgqGJglEsAA "Gaia – Try It Online") Uses the [Gaia codepage](https://github.com/splcurran/Gaia/blob/master/codepage.md). `ȯọ` are [36 apart](https://tio.run/##S0/MTPz//8T6h7t7H/V0wxmPGuaqPGraWuR0aNmjton/AQ). [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), score = 35 ``` ê│╓ ``` [Try it online!](https://tio.run/##y00syUjPz0n7///wqkdTmh5Nnfz/v6GxpYKhuaWCkaEJAA "MathGolf – Try It Online") Uses [MathGolf's codepage](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) along with [this simple Python script](https://tio.run/##PZLXclJRGIXveYojtsRoLLFGY@@9VzRG0rAAxlhiG0Q8HkYuKPvfnBNjQgkQiiUxZSQ4mdn/jJeHd1gvgjiT8W5dfbOaf2R40OftaDTcvt6@bn/PQJ/WpTk5CbMKcxFWDlYeVhZWCoEMkiaSn5C0YAVhBWCVYJVh1iCrSIagEwI1Na8KkBXoU9Bj0BPQ49CjMCagC8gZyJq2wuVcuWr1mrUtreva1m9o37hp85aOrdu279i5q3O3U3M52jTnnq69@/YfOHjo8JGjx46fOHnq9Jmz585fuHjp8pWr167fuHnL5bp9p/tuzz13b1//wKDn/oOHj7w@/@OhJ8NPnz1/MfLy1es3bxEJ8sdlHte4yBme5BTnuMAlLvMUf@dvXOEQf@Aw51nnWZ7nGV7kX7zEksdURmVVDsHCnzin@Sv/5CpPc0yVVFUtIRJVFfVb1VRaldUiZAwyDpmACEJMgtKgDEiCCJQFxUBJ0BfQGOgzRBRCQMxCVCDGIAIQNdD4slfQBGgUJEBFUB6UAkVBFVABNAVq0nMgC2SC4qAEqAwqQZgQEUgDMgTZFFHIgD3NE3aiHrCz9fdqrh6y87ZpF@1ZGON13Z6DUUQ4raYRziE8iUgKkTQvIGyoHzAstQBjFO@WVHO0FI87HY5@35Dm1jzeZp@lf0Ep4ex0aP4hj3e45f9/2vs93t4Wd2tro/EX). ``` ê Take user input as array of integers │ Take differences ╓ Find minimum ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1), score: 43 ``` n¹än¹n ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=brnkbrlu&input=WzExMCwxODUsMjI4XQ) (includes codepoints test case) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), score 53 ``` ’ÞIṂ ``` **[Try it online!](https://tio.run/##y0rNyan8//9Rw8zD8zwf7mz6//9/tLGOgqGJjoJRLAA "Jelly – Try It Online")** The code page is [here](https://github.com/DennisMitchell/jelly/wiki/Code-page). The code points are `253 20 73 179` which has minimal difference of `73-20=53` as may be seen in this [self-evaluation](https://tio.run/##y0rNyan8///wDK/MRxvXPWrc8ahh5sOdLWUO////BzIPz/N8uLMJAA "Jelly – Try It Online"). ### How? ``` ’ÞIṂ - Link: list of numbers, L e.g. [253, 20, 73, 179] 20: Þ - sort L by: 253: ’ - decrement [20, 73, 179, 253] 73: I - incremental differences [53, 106, 74] 179: Ṃ - minimum 53 ``` [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), Score 1 (79 bytes) ``` D?)0]li[0y̤<<<<<<<< Ro"/{~D-{:ii"6Xkq";$~\"akq"/~{R{0[il]0)?/:}S-:}}:{)?"E͍$; ``` [Try it online!](https://tio.run/##LcYxCoMwAEDRvaf4BBcHMQVbShRc9AJ2EdRB2iUoFQsdJCQ38BYeR8@Uduib3vvz0g/vizyU3agbuexb9neqJhEbV0RGaS2u9TCLNHCt6H@JnamMbPTYyTCPlb1HylplwlyUxxqk3j/JCZE0jGg6FvaNjLOkYkIQY3AURCguCTUDMykBbUtPcsNScqx8AQ "Runic Enchantments – Try It Online") (Note that due to the way input is coerced to the most appropriate type and we want `decimal value 49` not `decimal value 1` for such bytes; this applies to the newline, `0`, `6` (etc), as well as the injection of all the spaces). There's a few reasons I can't score higher. In decreasing order of troublesomeness. 1. `@` and `?` are adjacent (`?` is required for conditionals, `@` is one of two terminators) 2. `:` and `;` are adjacent (`:` is required to duplicate the top of the stack for non-destructive comparisons, `;` is the other terminator) 3. `<` and `;` are adjacent 4. `>` and `?` are adjacent (using other entry points possible, but we're already score-limited, `v` is best option as `^` and `]` are adjacent) 5. `D` and `E` are adjacent (replacing `D` with `/` or `\` or not using `E`val possible) 6. `l` and `k` are adjacent (`l` is required to read all input, `k` is required to inject a newline and entry point into the evaluated code; `E`val not strictly needed) 7. `}` and `~` are adjacent (pop-discarding an arbitrary value without corrupting the stack is difficult otherwise, `[]` does work, but limits score to 2, assuming we could overcome the other points, `0*+` also works, but `+` and `*` are adjacent) 8. `o` and `q` limit score to 2 9. `[` and `]` limit score to 2 (but not strictly necessary, just simplifies the input reading process, but `lril1-` is still score limited to 3 on its own plus `r` and `q` are adjacent as well as `0` and `1`) 10. `l` and `o` limit score to 3 11. pre-processing the code and injecting troublesome bytes with reflection necessitates a minimum of 2 of `1234567890`, all of which are going to cause low score limits. [Answer] # [MATL](https://github.com/lmendo/MATL), Score 16 ``` SdS9z) ``` [Try it online!](https://tio.run/##y00syfn/Pzgl2LJK8/9/9eAUIK0OAA "MATL – Try It Online") For anything up to `SdS)` I could get a score of 17, but generating a `1` for indexing (because `X<` is too close to `S`) bumped the score down to 16. Let's see if any ASCII-based language beats this... [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes, score = 35 ``` ạ€`«/Ƈ€«/€«/ ``` [Try it online!](https://tio.run/##y0rNyan8///hroWPmtYkHFqtf6wdyADSEPL/4RlemYcnADmH23GrAgA "Jelly – Try It Online") A monadic link taking a list of (optionally distinct) integers as its argument and returning the smallest gap. Generates an outer table of absolute differences between the inputs, filters out zero differences, finds the smallest in each row and then the smallest of those values. [TIO link](https://tio.run/##y0rNyan8///hroWPmtYkHFqtf6wdyADSEPL/4RlemYcnADmH23GrAgA "Jelly – Try It Online") has a footer to translate the code into numeric codepoints within Jelly codepage (technically each is +1, but there is no effect on differences between pairs). [Pairwise differences shown here](https://tio.run/##y0rNyan8///hroWPmtYkHFqtf6wdyADSEPL/4RlemYcnADmH27msHzXMUdC1U3jUMNcayA08Oin5MEh1JG79AA) [Answer] # [R](https://www.r-project.org/), 47 bytes, score = 2 ``` `-`=`mi\x6E`;`~`=diff;`?`=`s\x63\x61\x6E`;-~?"" ``` [Try it online!](https://tio.run/##K/r/P0E3wTYhNzOmwsw1wTqhLsE2JTMtzTrBHihaDBQ0BmJDiKRunb2S0n8TBTMFQwMFQ1MFQ3MFQ4v/AA "R – Try It Online") --- The input is assumed to be unique and sorted ascending. ## [Verify the score here](https://tio.run/##K/r/P03BViGtNC@5JDM/T6NYUyE3M08jJTMtTaM4v6hEozQvs7A0VaO0JM0iJN8zrwSoAgT@p2koJegm2CbkZsbEVJi5Jlgn1CXYgrRZJ9gDhYtBosYgwhAqr1tnH6MUo6Sk@R8A "R – Try It Online") [Answer] # **C++, score : 1, bytes : 132** ``` #include <cmath> int f(int* a,int c){int m=abs(a[0]-a[1]),i,j,d;for(i=-1;++i<c;)for(j=i;++j<c;)m=(d=abs(a[i]-a[j]))<m?d:m;return m;} ``` ~~The very need of the `abs` function kills my score, and any other C++ answer's.~~ It's actually `return`. [Try it online!](https://tio.run/##fU/BToQwFLzzFZP1sNSFZFH3sgWMdxM/ADnUUtgSW0gpMWaz344tsGo8eOnrTOfNTHnfxw3n043U/H2sBFLZDdYIpvJgHKRuoJkSQ8@4wGArGgQ/Sq6YPeWT1BZ16M5bsMgDTs5@qIy9DSEr9mXMiqQkkYzaqKJ1Z0KZxQnd7WTKKfG4zaSDrYcqC6t1UfrFtiQkVY/VUVEj7Gg0FL3MmYpJHRKcA2AJNyYC70ZtXUuAS408vxLwz8igxYdXFzNden7u4@xktqeu0Cx31cjVwO25JotlN1qkKTav@lnoxp5wxMYT3yG/FE/GsE8voP9ErPIlw9@22P7xeRlt78CaVIf@m7MFocElmA5IcId7PODwBQ "C++ (gcc) – Try It Online") ]
[Question] [ Some numbers, such as \$14241\$, are palindromes in base 10: if you write the digits in reverse order, you get the same number. Some numbers are the sum of 2 palindromes; for example, \$110=88+22\$, or \$2380=939+1441\$. For other numbers, 2 palindromes are not enough; for example, 21 cannot be written as the sum of 2 palindromes, and the best you can do is 3: \$21=11+9+1\$. Write a function or program which takes integer input `n` and outputs the `n`th number which cannot be decomposed as the sum of 2 palindromes. This corresponds to [OEIS A035137](https://oeis.org/A035137). Single digits (including 0) are palindromes. Standard rules for sequences apply: * input/output is flexible * you may use 0- or 1- indexing * you may output the `n`th term, or the first `n` terms, or an infinite sequence *(As a sidenote: all integers [can be decomposed](https://arxiv.org/abs/1602.06208) as the sum of at most 3 palindromes.)* Test cases (1-indexed): ``` 1 -> 21 2 -> 32 10 -> 1031 16 -> 1061 40 -> 1103 ``` This is code-golf, so the shortest answer wins. [Answer] # JavaScript (ES6), ~~93 83 80~~ 79 bytes *Saved 1 byte thanks to @tsh* Returns the \$n\$th term, 1-indexed. ``` i=>eval("for(n=k=1;k=(a=[...k+[n-k]+k])+''!=a.reverse()?k-1||--i&&++n:++n;);n") ``` [Try it online!](https://tio.run/##XcuxDoMgFEDRvV9hHRRCQJ82DjWv/RDjQCw2FgMNNEz@OzUxLgx3OrkfGaSf3PL9cWNfKs4YF3yoIFeSz9YRgxqh10gkDkIIzQbD9cj0SFlZXlEKp4JyXhH61By2jfOlKBgz972e9iancbLG21WJ1b7JTDKgNKuqrIFLAs0BbZMA1AdA3aYPdCd1Kd3Oa9/iHw "JavaScript (Node.js) – Try It Online") ### How? Given \$n\$, we test whether there exists any \$1\le k\le n\$ such that both \$k\$ and \$n-k\$ are palindromes. If we do find such a \$k\$, then \$n\$ is the sum of two palindromes. The trick here is to process \$k\$ and \$n-k\$ at the same time by testing a single string made of the concatenation of \$k\$, \$n-k\$ and \$k\$. *Example:* For \$n=2380\$: * we eventually reach \$k=1441\$ and \$n-k=939\$ * we test the string "\$1441\color{red}{939}1441\$" and find out that it is a palindrome ### Commented *NB: This is a version without `eval()` for readability.* ``` i => { // i = index of requested term (1-based) for( // for loop: n = k = 1; // start with n = k = 1 k = // update k: ( a = // split and save in a[] ... [...k + [n - k] + k] // ... the concatenation of k, n-k and k ) + '' // coerce it back to a string != a.reverse() ? // if it's different from a[] reversed: k - 1 // decrement k; if the result is zero: || --i // decrement i; if the result is not zero: && ++n // increment n (and update k to n) // (otherwise, exit the for loop) : // else: ++n; // increment n (and update k to n) ); // end of for return n // n is the requested term; return it } // ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16 10~~ 9 bytes -1 byte thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer). Outputs the first \$n\$ terms. ``` 2_ŒḂƇ⁺ṆƲ# ``` [Try it online!](https://tio.run/##y0rNyan8/98o/uikhzuajrU/atz1cGfbsU3K/4GCAA "Jelly – Try It Online") I tried to come up with different idea compared to my original approach. Let's review the thinking process: * Initially, the test worked as follows: It generated the integer partitions of that number, then filtered out those that also contained non-palindromes, then counted how many length-2 eligible lists there were. This was obviously not too efficient in terms of code length. * Generating the integer partitions of \$N\$ and then filtering had 2 main disadvantages: length and time efficiency. To solve that issue, I thought I shall first come up with a method to generate *only* the pairs of integers \$(x, y)\$ that sum to \$N\$ (not all arbitrary-length lists) with the condition that both numbers must be palindrome. * But still, I wasn't satisfied with the "classic way" of going about this. I switched approaches: instead of generating *pairs*, let's have the program focus on *idividual palindromes*. This way, one can simply compute all the palindromes \$x\$ below \$N\$, and if \$N-x\$ is also palindrome, then we're done. ### Code Explanation ``` 2_ŒḂƇ⁺ṆƲ# – Monadic link or Full program. Argument: n. 2 # – Starting at 2\*, find the first n integers that satisfy... _ŒḂƇ⁺ṆƲ – ... the helper link. Breakdown (call the current integer N): Ƈ – Filter. Creates the range [1 ... N] and only keeps those that... ŒḂ – ... are palindromes. Example: 21 -> [1,2,3,4,5,6,7,8,9,11] _ – Subtract each of those palindromes from N. Example: 21 -> [20,19,...,12,10] ⁺ – Duplicate the previous link (think of it as if there were an additional ŒḂƇ instead of ⁺). This only keeps the palindromes in this list. If the list is non-empty, then that means we've found a pair (x, N-x) that contains two palindromes (and obviously x+N-x=N so they sum to N). Ṇ – Logical NOT (we're looking for the integers for which this list is empty). Ʋ – Group the last 4 links (basically make _ŒḂƇ⁺Ṇ act as a single monad). ``` \* Any other non-zero digit works, for that matter. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ⁵ŻŒḂ€aṚ$EƲ# ``` [Try it online!](https://tio.run/##ASIA3f9qZWxsef//4oG1xbvFkuG4guKCrGHhuZokRcayI////zQw "Jelly – Try It Online") The full program roughly works like this: 1. Set **z** to the input. 2. Set **x** to **10**. 3. Set **R** to **[]**. 4. For every integer **k** from **0** up to and including **x**, check whether both **k** and **x - k** are palindromic. 5. If all elements of **L** are equal (that is, if either all possible pairs that sum to **x** have both their elements palindromic, or all such pairs have at most one of their elements be palindromic), set **z** to **z - 1** and append **x** to **R**. 6. If **z = 0**, return **R** and end. 7. Set **x** to **x + 1**. 8. Go to step 4. You may suspect that step 5 doesn't actually do the job it should. We should really not decrement **z** if all pairs that sum to **x** are palindromic. However, we can prove that this will never happen: Let's first pick an integer \$k\$ so that \$10\le k\le x\$. We can always do so, because, at step 2, we initialize **x** to be **10**. If \$k\$ isn't a palindrome, then we have the pair \$(k,x-k)\$, where \$k+(x-k)=x\$, therefore not all pairs have two palindromes. If, on the other hand, \$k\$ is a palindrome, then we can prove that \$k-1\$ isn't a palindrome. Let the first and last digits of \$k\$ be \$D\_F\$ and \$D\_L\$ respectively. Since \$k\$ is a palindrome, \$D\_F=D\_L>0\$. Let the first and last digits of \$k-1\$ be \$D'\_F\$ and \$D'\_L\$ respectively. Since \$D\_L>0\$, \$D'\_L=D'\_F-1\ne D'\_F\$. Therefore, \$k-1\$ isn't a palindrome, and we have the pair \$(k-1,x-(k-1))\$, where \$(k-1)+(x-(k-1))=k-1+x-k+1=x\$. We conclude that, if we start with setting **x** to a value greater than or equal to **10**, we can never have all pairs of non-negative integers that sum to **x** be pairs of palindromes. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~135~~ 102 bytes ``` K`0 "$+"{0L$`\d+ *__ L$` <$.'>$.`> /<((.)*.?(?<-2>\2)*(?(2)$)>){2}/{0L$`\d+ *__ ))L$` <$.'>$.`> 0L`\d+ ``` [Try it online!](https://tio.run/##K0otycxLNPz/3zvBgEtJRVup2sBHJSEmRZtLKz6eC8jkslHRU7dT0Uuw49K30dDQ09TSs9ewt9E1sosx0tTSsNcw0lTRtNOsNqrVR9GqqYmq2cAHJPX/vyUA "Retina – Try It Online") Too slow for `n` of 10 or more. Explanation: ``` K`0 ``` Start off by trying 0. ``` "$+"{ ``` Repeat `n` times. ``` 0L$`\d+ *__ ``` Convert the current trial value to unary and increment it. ``` L$` <$.'>$.`> ``` Create all pairs of non-negative integers that sum to the new trial value. ``` /<((.)*.?(?<-2>\2)*(?(2)$)>){2}/{ ``` Repeat while there exists at least one pair containing two palindromic integers. ``` 0L$`\d+ *__ ))L$` <$.'>$.`> ``` Increment and expand the trial value again. ``` 0L`\d+ ``` Extract the final value. [Answer] ## Haskell, ~~68~~ ~~67~~ 63 bytes ``` [n|n<-[1..],and[p a||p(n-a)|a<-[0..n]]] p=((/=)=<<reverse).show ``` Returns an infinite sequence. Collect all `n` where either `a` or `n-a` is not a palindrome for all `a <- [0..n]`. [Try it online!](https://tio.run/##DcmxDsIgEADQ3a@4wQESOdsdvgQZLhVsUzwv0OjCt3v61rdS33OtWsJNIw/2Ls6I6UJ8jwI0hhh2ZAf9Y0LklNJJgjHXYIP3Lb9z69liX18ffdLGEEDaxgec4aA9wzxB0e9SKj26ukXkBw "Haskell – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=any -p`, ~~59~~ 55 bytes *-3 bytes thanks to @NahuelFouilleul* ``` ++$\while(any{$\-reverse($\-$_)==reverse}0..$\)||--$_}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/19bWyWmPCMzJ1UjMa@yWiVGtyi1LLWoOFUDyFSJ17S1hfJrDfT0VGI0a2p0gcK11f//mxj8yy8oyczPK/6v62uqZ2BoAKR9MotLrKxCSzJzbIHG/dctAAA "Perl 5 – Try It Online") Note: `any` could be replaced by `grep` and avoid the `-M` command line switch, but under the current scoring rules, that would cost one more byte. [Answer] # [R](https://www.r-project.org/), ~~115~~ 111 bytes *-4 thanks to Giuseppe* ``` function(n,r=0:(n*1e3))r[!r%in%outer(p<-r[Map(Reduce,c(x<-paste0),Map(rev,strsplit(a<-x(r),"")))==a],p,'+')][n] ``` [Try it online!](https://tio.run/##FcixCsMgEADQvX/RQMhde4K2nYp@Qpeu4iBWQShGLqbk7y0ub3jck@lpL6HltUAhNvIJ5aLiHZHtmedc5nVvkaFqwfblK7zjZw@RAhxaVL@1KJHGc/zR1nir39zAa3EAI00TIhrjHVVargs6W1xPoPCU4DZQcviQ2P8 "R – Try It Online") Most of the work is packed into the function arguments to remove the `{}` for a multi-statement function call, and to reduce the brackets needed in defining the object `r` Basic strategy is to find all palindromes up to a given bound (including 0), find all pairwise sums, and then take the n-th number not in that output. The bound of `n*1000` was chosen purely from an educated guess, so I encourage anyone proving/disproving it as a valid choice. `r=0:(n*1e3)`can probably be improved with a more efficient bound. `Map(paste,Map(rev,strsplit(a,"")),collapse="")`is ripped from Mark's answer [here](https://codegolf.stackexchange.com/questions/146084/yo-boy-must-it-sum/146256#146256), and is just incredibly clever to me. `r[!r%in%outer(p,p,'+')][n]`reads a little inefficient to me. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 124 bytes ``` n=>{int a=0;for(string m;n>0;)if(Enumerable.Range(0,++a).All(x=>!(m=x+""+(a-x)+x).Reverse().SequenceEqual(m)))n--;return a;} ``` [Try it online!](https://tio.run/##Fc2xCoNADIDhvU9hnRJO5ZzTEzrYqZMdOl8lSkBTPL0ilD671eGHf/vaOW9n2W5R24voku1VndvUVd99E@8sde8A8xJE@2QkrSyhdFBrHDn418BF47VnsJkxHovrMMDqqjOMbjVpasDnK5oVi4Y/HGYGLB48RdaW6yn6AUZE1DynwEsMmnj6bXQ6yIMXV5JcXGktiTH4DLLwXZShA0Gk7Q8 "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [J](http://jsoftware.com/), 57/60 bytes ``` 0(](>:^:(1&e.p e.]-p=:(#~(-:|.)&":&>)&i.&>:)^:_)&>:)^:[~] ``` [Try it online!](https://tio.run/##JcUxCoAwDADArwSFkAwNrYhDwH5EWgcpqIvtLv16HLzlbrO2qqdEUbNSwCIViiRXV6Wxk9NXGAfFyHgJRuWsO/9vPVk5zgcjNAgwQfAQFpi9fQ "J – Try It Online") The linked version adds 3 bytes for a total of 60 in order to save as a function that the footer can call. In the REPL, this is avoided by calling directly: ``` 0(](>:^:(1 e.q e.]-q=:(#~(-:|.)&":&>)&i.&>:)^:_)&>:)^:[~] 1 2 10 16 40 21 32 1031 1061 1103 ``` ## Explanation The general structure is that of this technique from an [answer](https://codegolf.stackexchange.com/a/91176/87770) by [Miles](https://codegolf.stackexchange.com/users/6710/miles): ``` (s(]f)^:[~]) n ] Gets n s The first value in the sequence ~ Commute the argument order, n is LHS and s is RHS [ Gets n ^: Nest n times with an initial argument s (]f) Compute f s Returns (f^n) s ``` This saved a few bytes over my original looping technique, but since the core function is my first attempt at writing J, there is likely still a lot that can be improved. ``` 0(](>:^:(1&e.p e.]-p=:(#~(-:|.)&":&>)&i.&>:)^:_)&>:)^:[~] 0(] ^:[~] NB. Zero as the first term switches to one-indexing and saves a byte. (>:^:(1&e.p e.]-p=:(#~(-:|.)&":&>)&i.&>:)^:_)&>:) NB. Monolithic step function. >: NB. Increment to skip current value. (>:^: <predicate> ^:_) NB. Increment current value as long as predicate holds. p=:(#~(-:|.)&":&>)&i.&>: NB. Reused: get palindromes in range [0,current value]. #~(-:|.)&":&> NB. Coerce to strings keeping those that match their reverse. ]-p NB. Subtract all palindromes in range [0,current value] from current value. >:^:(1&e.p e.]-p NB. Increment if at least one of these differences is itself a palindrome. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` °ÝDʒÂQ}ãOKIè ``` -3 bytes thanks to *@Grimy*. 0-indexed. Very slow, so times out for most test cases. [Try it online](https://tio.run/##AR0A4v9vc2FiaWX//8Kww51EypLDglF9w6NPS0nDqP//Mw) or [verify the first few cases by removing the `Iè`](https://tio.run/##yy9OTMpM/f//0IbDc11OTTrcFFh7eLG/9///xgA). **Much faster previous 15 byter version:** ``` µNÐLʒÂQ}-ʒÂQ}g_ ``` 1-indexed. [Try it online](https://tio.run/##yy9OTMpM/f//0Fa/wxN8Tk063BRYqwuh0uP//zcGAA) or [output the first \$n\$ values](https://tio.run/##yy9OTMpM/f//0Fa/wxN8Tk063BRYqwuh0uMzdQ7t@f/fEgA). **Explanation:** ``` °Ý # Create a list in the range [0, 10**input] D # Duplicate this list ʒÂQ} # Filter it to only keep palindromes ã # Take the cartesian product with itself to create all possible pairs O # Sum each pair K # Remove all of these sums from the list we duplicated Iè # Index the input-integer into it # (after which the result is output implicitly) µ # Loop until the counter variable is equal to the (implicit) input-integer NÐ # Push the loop-index three times L # Create a list in the range [1, N] with the last copy ʒÂQ} # Filter it to only keep palindromes - # Subtract each from N ʒÂQ} # Filter it again by palindromes g_ # Check if the list is empty # (and if it's truthy: increase the counter variable by 1 implicitly) # (after the loop: output the loop-index we triplicated implicitly as result) ``` [Answer] # [Red](http://www.red-lang.org), 142 bytes ``` func[n][i: 1 until[i: i + 1 r: on repeat k i[if all[(to""k)= reverse to""k(s: to""i - k)= reverse copy s][r: off break]]if r[n: n - 1]n < 1]i] ``` [Try it online!](https://tio.run/##TU27CsMwENvzFcJTSik0QxfT/kTX44Y0seFwuISLE@jXu06H0kUPJCQLY3mGkbiJvsRNB1Im8eiwaZbpkIJzteYxKywsoc9IEJKIfpqozbNz6fSo0R5sDc3Xt6vHIQQX/IUY5uWNlelYixEvC31irlNG6qG13bHiXlG4/M5uVxAWE82VE5x3iJUZXD4 "Red – Try It Online") Returns n-th term, 1-indexed [Answer] # [Python 3](https://docs.python.org/3/), 107 bytes ``` p=lambda n:str(n)!=str(n)[::-1] def f(n): m=1 while n:m+=1;n-=all(p(k)+p(m-k)for k in range(m)) return m ``` [Try it online!](https://tio.run/##PU7LboMwELz7K6a5xBZQxVDl4MpfkubggkkQ2FjGUVtZfDu1i9LTzs7OY91PuM@22TYnJ2U@OwUrluCpZS9ynxchKn4lne7Rp1UQGMkJvu7DpJPYFJK/20qqaaKOjqxw1FQj62ePEYOFV/amqWGMwOvw8BZma9WiF0hEAi5qXhLUoqnT4CfBT00m@Dmhc0ZviUtkQishOTa7S@hvp9ugu9zxl/c6BG0Wmh@EasNDTamhp/mWuuH8YAPtD/FYFcfL0y3lLr2uiFm5CnyE/@j4RGuJ2xwQd/F6YNsv "Python 3 – Try It Online") Inverting the palindrome checking saved 2 bytes :) For reference the straight forward positive check (109 bytes): ``` p=lambda n:str(n)==str(n)[::-1] def f(n): m=1 while n:m+=1;n-=1-any(p(k)*p(m-k)for k in range(m)) return m ``` [Answer] # APL(NARS), 486 bytes ``` r←f w;p;i;c;P;m;j p←{k≡⌽k←⍕⍵}⋄i←c←0⋄P←r←⍬ :while c<w i+←1 :if p i⋄P←P,i⋄:continue⋄:endif m←≢P⋄j←1 :while j≤m :if 1=p i-j⊃P⋄:leave⋄:endif j+←1 :endwhile :if j=m+1⋄c+←1⋄r←i⋄:endif :endwhile ``` What is the word for break the loop? It seems it is ":leave", right? `{k≡⌽k←⍕⍵}` in p is the test for palindrome. This above function in the loop store all the palindrome found in the set P, if for some element w of P is such that i-w is in P too this means that the i is not right and we have increment i. Results: ``` f 1 21 f 2 32 f 10 1031 f 16 1061 f 40 1103 f 1000 4966 f 1500 7536 ``` ]
[Question] [ In this challenge we try to solve two important problems at once. They are: 1. Given integers \$a\$ and \$b\$, tell if \$a^b-1\$ is a prime number. 2. Given integers \$a\$ and \$b\$, return [\$a\choose b\$](https://en.wikipedia.org/wiki/Binomial_coefficient). Specifically, you must write two programs, one that does the first task and one that does the other. As we want to solve both problems at once, it is encouraged to use a same piece of code in both programs. ## Scoring The score of an answer is the Levenshtein distance between the two programs. Lower score is better. In case of a tie, the answer with the shortest combined code of the two programs wins. You can use [this script](https://tio.run/nexus/mathics#@@@aklnikllckpiXnKrg4KAQkpidGq3inJ@bm5iX4pOZl6qjoGsUq6CvrxBQlJlX8v///4Ki/PSixFwFQzjLCAA) to calculate the score of your solution. ## Rules 1. You must write two programs in the same language that solve the tasks described above. You can use any I/O methods you want. For task 1, you can return a truthy/falsy value or choose two values to mean true and false and return them accordingly. Eg. you can choose that `"prime"` means true and `"not prime"` means false. 2. The algorithms you use must work for all possible inputs, but it is OK if the code fails for large numbers due to limitations of the used number type. You can assume that the input is valid. 3. No subset of the program must solve the problem, ie. the code must not work if any character(s) are removed. For example, the following code is not valid, because it is possible to remove the unused else-block without breaking the program: ``` if (1) { /* change to 0 to get the second program*/ ... } else { ... } ``` 4. Standard loopholes are not allowed. ## Test cases ### \$a^b-1\$ is prime? ``` a b 1 1 false 2 3 true 5 2 false 2 5 true 4 3 false 2 7 true ``` ### \$a\choose b\$ ``` a b nCr(a,b) 1 1 1 5 2 10 4 3 4 10 7 120 12 5 792 ``` [Answer] # Ruby, Distance 1, Combined Length 194 **Prime check:** ``` ->a,b{s='[(a**b-1).prime?,(1..b).inject(1){|m,i|(a+1-i)/i*m}][0]';require'math'<<s.size*2;eval s} ``` [Try it online!](https://repl.it/H7ch/3) **nCr:** ``` ->a,b{s='[(a**b-1).prime?,(1..b).inject(1){|m,i|(a+1-i)/i*m}][1]';require'math'<<s.size*2;eval s} ``` [Try it online!](https://repl.it/H7ch/2) As predicted in the comments, some jerk always has to go against the spirit of the problem. It was fun finding a way to work around it, though! Here's how it works: We have two separate solutions to the problems. We run both, put them into an array, and then either choose the 0th element or the 1st, for an edit distance of 1. This would ordinarily be illegal, since you could just delete everything but the calculation you wanted and it would still work. However, each code snippet is written to rely on the loading of the same standard library, `'mathn'`: * The first uses its builtin `prime?` * The second relies on `mathn` changing how division works--before loading it, `3/4` evaluates to `0`, while afterwards it evaluates to the fraction `(3/4)`. Since the intermediate result of `(a+1-i)/i` is not always a whole number, the overall result is wrong without the library. Now we just need to make loading the library contingent on the rest of the code being unmodified. We do this by generating the name mathn using the character length of the rest of the main code: the combined calculation has length 55, which doubled to 110 is the ASCII value of 'n'. So concatenating this onto the string 'math' gives the desired library. As a bonus, introducing the library dependencies also makes the code run in a reasonable amount of time. In particular, the naive approach to nCr wouldn't generate fractional intermediate results. [Answer] # MATLAB, distance 10 **Primality:** ``` function x=f(a,b);x=isprime(a^b-1); ``` **nCr:** ``` function x=f(a,b);x=nchoosek(a,b); ``` [Answer] # PHP, distance 29 `a^b-1` prints 0 for true and any integer value > 0 for false ``` [,$a,$b]=$argv;for($c=-$i=1;$i<=$d=$a**$b-1;$d%++$i?:$c++);echo$c; ``` `nCr(a,b)` ``` [,$a,$b]=$argv;for($c=$i=1;$i<=$a;$c*=$i**(1-($i<=$a-$b)-($i<=$b)),$i++);echo$c; ``` ## PHP, distance 36 `a^b-1` prints 1 for true nothing for false ``` [,$a,$b]=$argv;for($c=-1,$i=1;$i<=$d=-1+$a**$b;)$d%++$i?:$c++;echo$c<1; ``` `nCr(a,b)` ``` [,$a,$b]=$argv;for($c=$d=$i=1;$i<=$a;$c*=$i++)$d*=$i**(($i<=$a-$b)+($i<=$b));echo$c/$d; ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), distance 3 **nCr** ``` sc ``` [Try it online!](https://tio.run/nexus/05ab1e#@1@c/P@/KZcRAA) **isPrime(a^b-1)** ``` m<p ``` [Try it online!](https://tio.run/nexus/05ab1e#@59rU/D/vymXEQA) [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), distance 13 ``` [([@.!]$/{%y!x y-!*})fork!] [^#-:([]1/$%{!n 1-!})fork!=] ``` [Try it online!](https://tio.run/nexus/stacked#@2@qYKSgoBCtEe2gpxirol@tWqlYoVCpq6hVq5mWX5StGAuUVVBMySwu4DJSMAcpjVPWtdKIjjXUV1GtVsxTMNRVhCq1jYUp/f8fAA "Stacked – TIO Nexus") The first calculates nCr, the second primality, using Wilson's theorem. `(f g h) fork!` pops `N` args from the stack (call them `a0 ... aN`) and applies `a0 ... aN f a0 ... aN h g`. For the first program: ``` [([@.!]$/{%y!x y-!*})fork!] [( )fork!] apply the fork of: [@.!] equiv. { x y : x ! } => `x!` $/ divided by {% } two-arg function y! y! x y- (x - y)! * * ``` And for the second: ``` [^#-:([]1/$%{!n 1-!})fork!=] [^ ] exponentiate (a^b) #- decrement (a^b-1) : duplicate (a^b-1 a^b-1) ( )fork! apply the fork to: []1/ 1-arg identity function $% modulus by {! } 1-arg with `n`: n 1- (n-1) ! ! = check for equality ``` [Answer] # [Python 2](https://docs.python.org/2/), [distance 15](https://tio.run/nexus/mathics#jYwxC8IwEIV3f8UNCrmQENuxWCgYN4cMbuJwsR3CmSvUDv77WEQHwcHp8d73@MqhT7NP95nkOkDXwYl4OK/3Y84k/THJYMDWF3AOwpRkLqX49kY59gTcZHootpWpcBU@qxhut43sGMYJgpIFM2pxvHofyMQmKNI62hq1rjf@VfAfcfUt9orxl9tEdEvYiE8 "Mathics – TIO Nexus"), length 172 ### Task 1 ``` D=lambda k:max(k-1,1) P=lambda n,k=0:n<k or P(n-1,k)*n/k lambda a,b:P(a**b-2)**2%D(a**b) ``` ### Task 2 ``` D=lambda k:max(k-1,1) P=lambda n,k=1:n<k or P(n-1,D(k))*n/k lambda a,b:P(a,b)/P(a-b) ``` [Try it online!](https://tio.run/nexus/python2#jY5BCsIwEEXX5hSzKWbCFG20CMXueoBeIbEWJTYtVdDb1yRtRQXBRfiZP/PfzFDkF9XoSoHJGvXgJk4oQVbOriWTrzO7N9D2UHLr2gaFXRnWzSOKdFZyJYSOJQohoyIUyNgf7OSTXXCDI/7whSeNKyexxqE61nA9tXdvUo0ZW3T92d5gGckKwttUS4hg7IeoO6Z2S8Ifzha4v4SAS9p4SUmOVeplO5qSdp792tQ5SFj0gzVBpnSydnGvHvqOOeDwBA "Python 2 – TIO Nexus") [Answer] # Mathematica, distance 10 Task 1: `PrimeQ[#2^#-1]&` Task 2: `Binomial[#2,#]&` Both functions take the inputs in the order `b,a`. [Answer] # Javascript ES7, distance 14 Thanks @Conor O'Brien for reducing the distance by 7 **Primality:** ``` f=x=>y=>{t=x**y-1;s=1;for(i=2;i<t;i++){if(!t%i)s=i-i}return s} ``` Returns 1 if prime returns 0 if not prime. Incredibly inefficient prime check, checks the number modulo every number smaller than it and greater than 1... **nCr:** ``` f=x=>y=>{t=x+1;s=1;for(i=1;i<t;i++){if(y<i)s*=i/(i-y)}return s} ``` Multiplies 1 by each number from y+1 to x and divides by each number from 1 to x-y (x!/y!)/(x-y)! [Answer] # Octave, distance ~~17~~ ~~16~~ 15 ### nCr ``` a=input("");b=input("");f=@(x)factorial(x);printf("%d",f(a)/f(b)/f(a-b)) ``` [Try it online!](https://tio.run/nexus/octave#@59om5lXUFqioaSkaZ2ExE6zddCo0ExLTC7JL8pMzAGyrQuKMvNK0jSUVFOUdNI0EjX10zSSQESibpKm5v//plzGAA "Octave – TIO Nexus") ### `isprime(a^b-1)` ``` a=input("");b=input("");f=@(x)isprime(x);printf("%d",f(a^b-f(8-6))) ``` [Try it online!](https://tio.run/nexus/octave#@59om5lXUFqioaSkaZ2ExE6zddCo0MwsLijKzE0FsqyBjLySNA0l1RQlnTSNxLgk3TQNC10zTU3N//9NuYwB "Octave – TIO Nexus") I am not very fluent in Octave, so I don't know if there is a builtin to calculate nCr. [Answer] # [MATL](https://github.com/lmendo/MATL), distance 4, length 6 ### Tell if `a^b-1` is prime: ``` ^qZq ``` [Try it online!](https://tio.run/nexus/matl#@x9XGFXw/78plzEA) ### Compute `nCr(a,b)`: ``` Xn ``` [Try it online!](https://tio.run/nexus/matl#@x@R9/@/KZcxAA) ## How it works ### Tell if `a^b-1` is prime: ``` ^ % Power with implicit inputs q % Subtract 1 Zq % Is prime? Implicit display ``` ### Compute `nCr(a,b)`: ``` Xn % nchoosek with implicit inputs. Implicit display ``` [Answer] # Pyth, distance 4, total length 8 ## Primality of `a^b-1` ``` P_t^F ``` [Try it online!](http://pyth.herokuapp.com/?code=P_t%5EF&debug=0) ## nCr(a, b) ``` .cF ``` [Try it online!](http://pyth.herokuapp.com/?code=.cF&debug=0) Both take input as tuples/lists of integers (e.g. `(1,2)`). [Answer] # PHP, distance 14 Writing a program with two functions and only calling one of them would lead to a distance of 1, but it´d be too lame. Prime Test, 100 bytes: ``` [,$a,$b]=$argv;function f($n){for($i=$n;--$i>0&&$n%$i;);return$i==1;}echo f($a**$b*-1)*(1|f($a-$b)); ``` nCr, 98 bytes: ``` [,$a,$b]=$argv;function f($n){for($i=$n;--$i>0&&$n*=$i;);return$n*=1;}echo f($a)/(f($b)*f($a-$b)); ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), distance 4, length 5 ### Task 1 ``` *’ÆP ``` ### Task 2 ``` c ``` [Try it online!](https://tio.run/nexus/jelly#@6/1qGHm4bYAruT/hkcbFHQUjIBkpMLDHdsfNcxRcE7MyVFIyi/JUMjJzMsu1lEoTi1ILEosSVVIqlRIBAmmpqWmpuj9/29o8N8YAA "Jelly – TIO Nexus") ## How it works ### Task 1 ``` *’ÆP Main link. Argument: a, b * Yield a**b. ’ Decrement; yield a**b-1. ÆP Test the result for primality. ``` ### Task 2 ``` c nCr atom ``` [Answer] # JavaScript, Score:1, Length:~~144~~ ~~142~~ ~~126~~ 117 ``` function(a,b){s="a=Math.pow(a,b)-t;for(b=2;a%b++;);b>a1for(;b;)t=t*a--/b--";t=s.length-56;return eval(s.split(1)[0])} ``` ~~function(a,b){s="a=Math.pow(a,b)-s.length+79;for(b=2;a%b++;);b>a1for(t=s.length-79;b;)t=t\*a--/b--";return eval(s.split(1)[1])}~~ ``` function A(a,b){a=Math.pow(a,b)-(B+0).length+63;for(b=2;a%b++;);return b>a;} function B(a,b){for(t=(A+0).length-76;b;)t=t*a--/b--;return t;} F=A ``` Both subroutines use the other one's length to calculate its own constant, so no char can be removed ]
[Question] [ ## Background [Link-a-Pix](https://www.conceptispuzzles.com/index.aspx?uri=puzzle/link-a-pix) is a puzzle on a rectangular grid, where the objective is to reveal the hidden pixel art by the following rules: * Connect two cells with number N with a line spanning N cells, so that the two cells are at the two ends of the line. * The number 1 is considered connected to itself (which makes it an exception to the rule of "connect *two* cells"). * Two different lines are not allowed to overlap. * The puzzle is solved when all the given numbers on the grid are connected by the above rules. There may be some unused cells after the puzzle is solved. The following is an example puzzle and its unique solution. ![](https://i.stack.imgur.com/Akxry.jpg) (Source: [The NP completeness of some lesser known logic puzzles, 2019](https://dspace.library.uu.nl/bitstream/handle/1874/383821/Scriptie_Mieke_Maarse_5750032.pdf?sequence=2&isAllowed=y)) A Link-a-Pix puzzle often involves colors and reveals a colorful picture when solved, but we will ignore them for simplicity, and focus on "monochrome" puzzles. ## Task In this challenge, the puzzle is limited to one dimension, or equivalently, a grid of height 1. Given a 1D Link-a-Pix puzzle instance, check if it has a solution or not. A puzzle instance is given as a sequence of non-negative integers, where each cell with a given number contains that number and the others contain 0. For output, you can choose to 1. output truthy/falsy using your language's convention (swapping is allowed), or 2. use two distinct, fixed values to represent true (affirmative) or false (negative) respectively. ## Test cases ``` Truthy [0, 1, 0, 4, 0, 0, 4, 2, 2, 0, 1] [0, 0, 0, 0] (the puzzle is solved vacuously) [12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12] (multi-digit numbers must be supported) [2, 2, 0, 2, 2, 2, 2, 1, 2, 2] (suggested by tsh) Falsy [0, 4, 0, 3, 4, 3, 0] (two lines cannot overlap) [3, 0, 3, 0, 3, 1, 3, 0, 3, 0, 3] [1, 0, 2, 2, 2, 2, 2, 0, 1] (one of 2s have nowhere to connect) [3, 3, 3, 3] (suggested by tsh) [3, 3, 3] [0, 0, 4, 4] (the 4s must begin and end the 4-cell line) [12, 2] (multi-digit numbers must not be treated as multiple single-digit numbers) ``` [Answer] # JavaScript (ES6), 41 bytes Returns *false* for valid or *true* for invalid. ``` a=>a.some(p=(x,i)=>--p>0?x:a[i+x-1]^=p=x) ``` [Try it online!](https://tio.run/##dU9LDsIgFNx7iu4KsTSluDKhrr2AG6wJ6cdgEIg1DbdHC35qpMnLZMLMvDdc@MiH5ibMHSnddq6njtOK54O@dsBQYDMBaYWQqYqd3XIm1hbh@kQNtdA1Wg1adrnUZ5CyA5eirVO4mj/3gBVZgrPkiRuPgZR@JqmGscRrIuInWc4GBzLZf/zpUbG9GpebhU7EExI/SN6WgHjGJ4wk8F@/5b8Sv4jEF30V9wA "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input a.some(p = // start with p NaN'ish (x, i) => // for each value x at position i in a[]: --p > 0 ? // decrement p; if it's positive: x // make sure that we have x = 0 // (because we're currently over a connection 'line') : // else: a[ // XOR the entry at ... i + x - 1 // ... i + x - 1 ... ] // ^= p = x // ... with x; and set p = x // this must give 0 if the puzzle is valid ) // end of some() ``` The trickiest case is when a \$0\$ is reached at position \$i\$ and we're currently outside a connection (i.e. \$p\le0\$), which causes the entry at \$i-1\$ to be XOR'ed with \$0\$. If the puzzle is valid, this will always result in \$0\$ as expected because: * if \$i=0\$, we do `undefined ^ 0` * if \$i>0\$, the entry at \$i-1\$ either was already set to \$0\$ or was cleared by the previous XOR [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` Ṁ1;Ṭ×Ʋ€ṚœṣF¥ƒ⁸Ẹ ``` [Try it online!](https://tio.run/##y0rNyan8///hzgZD64c71xyefmzTo6Y1D3fOOjr54c7FboeWHpv0qHHHw107/h@d9HDnDOtHDXMUdO0UHjXMtT7cDhZS0Yz8/z@aK9pAR8FQRwFImoBJCMMIjEBSsTpgJVAE4sHljJCQIYQBVQ0xyhjMMIZqM4aJQUhDJDaIBCkxxDAWyRHGYKXGUKWoTAOYnEEsV@x/gl4CAA "Jelly – Try It Online") A monadic link taking a list of integers and returning `0` for those that have a solution and `1` for those that don’t. ## Explanation ``` Ṁ | Max Ʋ€ | For each integer z from 1 to this: 1; | - Prepend 1 Ṭ | - Untruthy (so [1, 4] becomes [1, 0, 0, 1] × | - Multiply by z Ṛ | Reverse (so that the largest lists come first) ¥ƒ⁸ | Reduce using the original list as the starting point and the following two links as a dyad: œṣ | - Split at matching substrings F | - Flatten Ẹ | Finally check if any non-zero values remain ``` --- # Second approach # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` Ị¬Ts2r/€ịµF^Ø.¦L)FẸ ``` [Try it online!](https://tio.run/##y0rNyan8///h7q5Da0KKjYr0HzWtebi7@9BWt7jDM/QOLfPRdHu4a8f/o5Me7pxh/ahhjoKuncKjhrnWh9vBQiqakf//R3NFG@goGOooAEkTMAlhGIERSCpWB6wEikA8uJwREjKEMKCqIUYZgxnGUG3GMDEIaYjEBpEgJYYYxiI5whis1BiqFJVpAJMziOWK/U/QSwA "Jelly – Try It Online") ## Explanation ``` Ị | Insignificant (<= 1) ¬ | Not T | Truthy indices s2 | Split into pairs r/€ | For each, make a range between the two values (returns asingle value if there isn’t a pair, which will knly be seen if no solution ị | Index into original input µ | Start a new monadic chain ) | For each: F | - Flatten (handles situation with single value) ^Ø.¦ | - Xor the first and last values with: L | The length of that set F | Flatten Ẹ | Any ``` --- # Original approach # [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes ``` ṣḊLḂȯm2;Ẉ+2nʋ¥ɗʋɗⱮỊÐḟFẸ ``` [Try it online!](https://tio.run/##y0rNyan8///hzsUPd3T5PNzRdGJ9rpH1w10d2kZ5p7oPLT05/VT3yemPNq57uLvr8ISHO@a7Pdy14//RSQ93zrB@1DBHQddO4VHDXOvD7ZqR//9Hc0Ub6CgY6igASRMwCWEYgRFIKlYHrASKQDy4nBESMoQwoKohRhmDGcZQbcYwMQhpiMQGkSAlhhjGIjnCGKzUGKoUlWkAkzOI5Yr9T9BLAA "Jelly – Try It Online") In brief, tries splitting the list at every occurrence of each integer >=2 and then tests the following for each of those splits: * The length is odd (I.e. there was an even number of that value originally) * There are no non-zero integers in between the pairs of that integer * The lengths of each run of zeros is equal to the integer minus 2 If any test fails for any split then the puzzle is not-solvable. ## Explanation ``` ɗⱮỊÐḟ | Use each of the input except 0s and 1s as the right argument y of the following (with the original argument x as the left argument): ṣ | - Split x at y (-> z) ʋ | - Following as a dyad using arguments z and y: Ḋ | - Remove first element L | - Length Ḃ | - Odd ȯ ɗ | - Or the following as a dyad with arguments z and y: m2 | - Take every other sublist starting at the first (-> w) ¥ | - Following as a dyad using arguments (w, y) ; ʋ | - Concatenate to the following using arguments (w, y) Ẉ | - Lengths of w +2 | - Add 2 (vectorises) n | - Not equal to y F | Finally, flatten all lists Ẹ | Check whether any are non-zero ``` [Answer] # [J](http://jsoftware.com/), 33 bytes ``` 0(-.~-:2#_2-~/\I.@:<)1&(1+=j.<)#] ``` [Try it online!](https://tio.run/##hY5Na8MwDIbv@RViAefLdiy7Jy@F0UGhMHYYu6VljNISwqDQj0Nh5K@nThyHJCsrSEJ6/VivyvqJB3uYawiAggBtknF4/Xhb1iJkvGJa@l@SVel6xV90FiEJMZmXPIv8TQ3wvuDg3QU3foUJEoMiybyOzLVBiRiz8UMWmaH/g8ELcx2n8jfXSWqgZ460IhjF/RJMJpZx8zvydtviAMHn8XIuroGd9iAoIG3qrK22kW00TwOsC6f0jBwE2qazWn7/nEZO1kO1jRrsUk63FelYcRj@8ZtcqaiLidIfDeius8NgFGYQMDMpQJlH2Sj1DQ "J – Try It Online") A large part is reused from [Jonah's solution](https://codegolf.stackexchange.com/a/226196/78410), but this solution adds an idea and a J-specific black magic of combining `j.` with `#`. ### A high-level view of the algorithm ``` Example input: 0 1 0 4 0 0 4 2 2 0 1 Insert a 1 after ones, and a 0 after other nonzeros (call it X): 0 1 1 0 4 0 0 0 4 0 2 0 2 0 0 1 1 1) Nonzero indices of X: 1 2 4 8 10 12 15 16 Non-overlapping pairwise difference: (2-1),(8-4),(12-10),(16-15) = 1 4 2 1 Duplicate each number (call it Y): 1 1 4 4 2 2 1 1 2) Remove zeros from X (call it Z): 1 1 4 4 2 2 1 1 Do Y and Z agree? Yes. ``` ### Why this works First, note that Z, which is simply X without zeros, should agree with something duplicated. This means the paired non-zero numbers in X should have the same value (and X cannot have any unpaired value at the end). This holds iff the nonzeros in the original input can be paired in the Link-a-Pix way, ignoring the distances. Then look at Y, which is generated from the paired distances between nonzero numbers. Y = Z means that the numbers forming a pair must be equal to the distance between them. The process of computing X precisely makes the distance between two `n`'s equal to `n` (by duplicating the ones and adding a distance of 1 for the others). ### How the code works When given a complex number `a+bi` as the left arg of `#`, the corresponding item is replicated `a` times and then `b` fill elements are inserted. It is like APL's `/` and `\` combined, and as far as I'm aware, it is at least not very straightforward to do the same in other languages (APL-like or not). ``` 0(-.~-:2#_2-~/\I.@:<)1&(1+=j.<)#] NB. Input: vector of integers 1&(1+=j.<)#] NB. Construct X: 1&( = ) NB. For each item, 1 if equal to 1, 0 otherwise 1&( <) NB. For each item, 1 if greater than 1, 0 otherwise 1+ j. NB. Compute complex numbers (a, b) -> (a+1) + bi #] NB. As left arg of #, duplicate 1s and insert a 0 after >1s 0(-.~-:2#_2-~/\I.@:<) NB. Test if Y = Z: 0( 2#_2-~/\I.@:<) NB. Construct Y: 0( I.@:<) NB. Indices of nonzero items of X _2-~/\ NB. Non-overlapping pairwise differences 2# NB. Duplicate each number 0(-.~ ) NB. Construct Z: Remove zeros from X -: NB. Do Y and Z agree? ``` [Answer] # [J](http://jsoftware.com/), 53 bytes ``` ([:*/2|[:+/@:*;.1,~&1)*[:(-.&0-:1+2#_2-~/\I.@:*)]*1&< ``` [Try it online!](https://tio.run/##dY5dS8MwFIbv/RUHC23SpGlOuqujA1EYCOKF7C4rQ8bGEEHw40KU/vWaj2W03YSTw8mb5815X/pLVexgTlCABA3kTqXg7ulh0TNLZW1@LYn6hsorhbLLkZeWWKVyXREKk61N1dWre@UA3paYX/f84vFWAfvXZTIUJ67gcQhbmx@18iBntqJWYEeWj/CsQzHPMTk8G1Eg0hT4SawzjjMxmPBcyz253ezfoFi@f33uv4t424GWgNL3WehxMKH80wA7VFKOjBkUxuGwavH8@jHaFHc0YWgGfzVJjx3lWEkYnuybpGxkqolyDA2Y0rlA7qJh5o6Gxj0Zr/R/ "J – Try It Online") This is the idea for the approach [Bubbler's answer](https://codegolf.stackexchange.com/a/226199/15469) improves and refines. I consider that answer the "final draft" J answer. Aside from making use of some nice J tricks, it also eliminates the need for doing a separate check for "ones in the middle". Previous versions of this answer had similar ideas, but each of them failed on some test cases, whereas Bubbler's solution irons out all the problems. Consider `0 1 0 4 0 0 4 2 2 0 1`: * `]*1&<` Convert ones to zeros: ``` 0 0 0 0 4 0 0 4 2 2 0 0 0 ``` * `I.@:*` Signum and find indexes (ie, indexes of everything non-zero): ``` 3 6 7 8 ``` * `_2-~/\` Deltas of consecutive (non-overlapping) pairs: ``` 3 1 ``` * `1+2#` Duplicate in place and add 1: ``` 4 4 2 2 ``` * `-.&0` - Does that equal the original input without zeroes or ones? (yes, in this case) ``` 4 4 2 2 ``` * `([:*/2|[:+/@:*;.1,~&1)*` Are there also no `1`s between any of the pairs? ``` _1 1 _1 3 _1 _1 3 1 1 _1 1 ``` [Answer] # [Haskell](https://www.haskell.org/), ~~64~~ 61 bytes ``` f[]=1>0 f(h:t)|r<-drop(h-1)t=[a`div`h*h|a<-[2..h]]++r==t&&f r ``` [Try it online!](https://tio.run/##ZU7LDoIwELz7FXswBOQRSj0Z6hfoyWPTSBMkJfJKqY8D/16BgmBMZiezuzObFby934pC64wygo7hJrPFQTmdjP1U1o0tfOQoQnmS5s9E7ETHY59GQSAYc11JiLKsDKQueV4BgZI35ys0D3VR8lQBbUX9gi1k8Iaur9gHugEAGnqAPOh5P7IR0YhhxbzZNWEafB3RCsiIJWNu4lHgJYznsWG00gNPLvR3//cnPAbwEpg7xvQH "Haskell – Try It Online") ``` f[]=1>0 - if we reach end is solvable: output True f(h:t)= - head : tail [a`div`h*h|a<-[2..h]] - we build the tail of h-block we expect ==take(h-1)t - and compare with the actual one &&(f$drop(h-1)t) - then continue ``` * abusing the fact that `drop` and `take` can take negative amount (behaving like 0) on tail to handle both 0 and 1 * edit : concatenaing expected with rest of list and compared to rest of list [Answer] # [JavaScript (V8)](https://v8.dev/), 45 bytes ``` a=>a.some(v=>c?a*!--c-v:(c=a=v)&&0*--c,c=0)|c ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/0dYuUa84PzdVo8zWLtk@UUtRVzdZt8xKI9k20bZMU03NQAsooJNsa6BZk/w/OT@vOD8nVS8nP10jTSPaQEfBUEcBSJqASQjDCIxAUrGamtZcmFqgCJssXK8REjKEMHCYBrHaGMwwxmGsMUwNhDREYoNIbFoMMZyBx1PGYKOMcRiFJPUfAA "JavaScript (V8) – Try It Online") Output falsy if solutions exist. ``` a=> // `a` is the given input array a.some( // try to find out some value violate spec v=> // `v` is current value c? // `c` is count down since last non-zero a*!--c-v: // if c=1, we need to close the segment // with value equals to previous `a` // if c>1, we need the value to be 0 // if `v` is not what we want, `some` returns true // also count down `c` (c=a=v)&& // if c=0 and v=0, ignore current value // if c=0 and v>0, assign `v` to `a` and `c` 0*--c, // count down c // also return something falsy c=0) // count down is initialized to 0 |c // test if there is an unmatched number left ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~19~~ 18 bytes ``` ~c{+<2|h.~l?↔?b+}ᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy65WtvGqCZDry7H/lHbFPsk7dqHWyf8/x9toKNgqKMAJE3AJIRhBEYgqVgA "Brachylog – Try It Online") (Times out for falsey test cases longer than seven elements.) ### Explanation Checks every possible partition of the list until it finds a valid solution. ``` ~c Construct a list of lists whose concatenation is the input list { }ᵐ The following predicate must succeed for each sublist: Either: + The sum of the sublist <2 is less than 2 (in which case it's a bunch of 0's and at most one 1) | Or: h The first element of the sublist . (which will be the output of this predicate) ~l? is the length of the sublist ↔ and the sublist reversed ? is the same as itself b and the sublist with first element removed + summed equals the output of this predicate (previously declared to be the first element of the sublist) ``` The second branch succeeds iff the sublist is a valid would-be line of the form \$[N, 0, \cdots, 0, N]\$: * The head of the sublist is \$N\$. * Its length is also \$N\$, so it can be filled in to form a line of \$N\$ numbers. * It is a palindrome, which means its tail is also \$N\$. * The sum of everything but the head is \$N\$. Since the tail is \$N\$ and all the numbers are nonnegative, all the numbers in the middle must be \$0\$. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes ``` ¹Wθ«≔⊟θι¿›ι¹¿∨Φ⁻ι²∧θ⊟θ¬∧θ⁼ι⊟θ⎚ ``` [Try it online!](https://tio.run/##NY07DsIwDEDn9hQeHSlIbcXGVCHKBHSvOkQlUEtRSpMUBsTZg8PHlj28588wKjdMysTYOrIBS7HJHyMZDTgLeOZZ7T1dLbbTjYEEYp/RBXDvtAraIUkohYCETg4bMgkeyC4@qYpXanvGWcL3gmBwnAL@4G5elPlM/jUHbI1WDvnTK8auK2QpC7nmSr3iZNL3cXU3bw "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean i.e. `-` for affirmative, nothing for negative. Explanation: ``` ¹ ``` Assume a solution exists. ``` Wθ«≔⊟θι ``` Loop over the cells (in reverse order, not that it matters here). ``` ¿›ι¹ ``` If the last cell `n` was greater than `1`, then... ``` ¿∨Φ⁻ι²∧θ⊟θ¬∧θ⁼ι⊟θ ``` ... if any of the next `n-2` cells is nonzero, or the following cell is not `n` or does not exist, then... ``` ⎚ ``` ... clear the canvas, because there is no solution. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 37 bytes ``` ’ȯ€Ø1F‘µTịĖs2ạ;2ị$$}¥/€‘1¦€2ị$ÐḟUƑƇ$Ƒ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw8wT6x81rTk8w9DtUcOMQ1tDHu7uPjKt2OjhroXWRkC2ikrtoaX6QBVAWcNDy4AMsOjhCQ93zA89NvFYu8qxif8PtwPF//@PjjbQUTDUUQCSJmASwjACI5BUrI5CtAFMxgDEg8sZISFDCAOqGmKUMZhhDNVmDBODkIZIbBAJUmKIYSySI4zBSo2hSmHMWAA "Jelly – Try It Online") Uses Jonah's trick to replace 1 with 2, 2; credit for that to him [here](https://codegolf.stackexchange.com/a/226196/68942). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~52~~ 45 bytes ``` $ , \d+ $* 1?,|(1(1)+)(?<-2>,)+\1,(?(2)^) ^$ ``` [Try it online!](https://tio.run/##TUzBCkIxDLvnOya0LsK6eRR39CceDwU9ePEgHv332W0iEpImJe3z9ro/Lm0jp3MLIJZrRNjCKt9iYhpV6mGXj9S4GKVK1lWBNbSWaEzcO7tmh2@QRk6YOX9hXTHbxbV4owzfafx52N/V/Fg4MOcH "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 7 bytes thanks to @tsh. Explanation: ``` $ , ``` Add a trailing comma so that all numbers are followed by commas. ``` \d+ $* ``` Convert the numbers to unary. ``` 1?,|(1(1)+)(?<-2>,)+\1,(?(2)^) ``` Match all cases of either 0 or 1 followed by a comma, or a number `n+1` repeated twice with `n` commas between (which represents `n-1` empty cells) and one following. A .NET balancing group is used to ensure the relationship between the numbers and the number of commas. ``` ^$ ``` Check to see whether everything was matched. [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~38~~ 37 bytes ``` !qR` [01]\b|( \d+)( 0)*\1`{(sNa)-b|x} ``` Regex solution. Takes input from stdin as a space-separated list of integers with a single leading space. [Try it here!](https://replit.com/@dloscutoff/pip) Alternately, here's a 39-byte version in Pip Classic: [Try it online!](https://tio.run/##K8gs@P9fsTAoQSHawDA2JqlGQyEmRVtTQ8FAUyvGMKFao9gvUVO3piappqL2/38FAwVDIDYBYhBpBIRAEQA "Pip – Try It Online") If the numbers were single-digit only, this could be **25 bytes**: ``` !qR`0|1|(\d)0*\1`{#a-b|x} ``` [Try it online!](https://tio.run/##K8gs@P9fsTAowaDGsEYjJkXTQCvGMKFaOVE3qaai9v9/A0MDEwMDEyMjA0MA) ### Explanation ``` !qR` [01]\b|( \d+)( 0)*\1`{(sNa)-b|x} q Read a line of stdin R` ` Find all non-overlapping matches of this regex: [01]\b A single 0 or 1 | or ( \d+) Any other number ( 0)* followed by zero or more 0's \1 followed by the same number again { } Replace each match with this function: sNa The number of spaces in the match ( -b) minus the value of the first capture group (Either the first branch was taken, in which case the capture group is unused and the expression is nil [falsey], or the second branch was taken and the length is correct, in which case the expression is 0 [falsey], or the length is incorrect, in which case the expression is nonzero [truthy]) | OR x empty string (The effect is to remove correctly formatted lines from the input; incorrectly formatted lines are either left unchanged or replaced with 1's) ! Return 1 if the resulting string is empty, else 0 ``` --- Here's a non-regex solution in **40 bytes** that takes the list as command-line arguments and outputs via stderr (error message = falsey, no error = truthy): ``` W#Y@g2>y?POg#g>=y=g@Dy=$+g@\,y?g@>:@g;Vk ``` [Try it online!](https://tio.run/##K8gs@P8/XDnSId3IrtI@wD9dOd3OttI23UFXt9JWRTvdIUan0j7dwc7KId06LPv///8G/02A2BhIGv83AAA) [Answer] # SWI-Prolog, 131 bytes ``` t([]). t(L):-append(Q,W,L),g(Q),t(W). g([0]). g([1]). g(W):-append([H|L],Q,W),append(L,[H],Q),sum_list(L,0),length(L,X),X is H/2-1. ``` Prolog is hard to golf but it is ideal for this kind of problem. Explanation: ``` % recursion stop condition t([]). % a testcase succeeds if the first part Q of the list is good % and the second part W recursively also succeeds t(L):-append(Q,W,L),g(Q),t(W). % base cases: 0 and 1 are both good g([0]). g([1]). % a longer list is good if it consists of the pattern HLLH g(W):-append([H|L],Q,W), append(L,[H],Q), % and L consists of zeros sum_list(L,0), % and the length of L is half the border value minus 1 length(L,X), X is H/2-1. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .œεεćsOyθyg)Ëy2‹P~]Pà ``` Can probably be shorted, but this will do for now. [Try it online](https://tio.run/##yy9OTMpM/f9f7@jkc1vPbT3SXuxfeW5HZbrm4e5Ko0cNOwPqYgMOL/j/P9pAx1DHQMcEiEGkERACRWIB) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXSf72jk89tPbf1SHuxf@W5HZXpmoe7K40eNewMqIsNOLzgv5JemM7/6GgDHUMdAx0TIAaRRkAIFInVUYg2AAsZgJiGRjoGWKChEUgSosUICg1BJEQ7yExjIGkMMcQYzAVhQx04G2w6kna47cY6YAhnwlxkomMCdRHYFlOgkCnYmbEA). **Explanation:** ``` .œ # Get all partitions of the (implicit) input-list: ε # Map over each partition: ε # Map over each inner part-list: ć # Check if the first item of the list, sO # the sum of the list minus its first item, yθ # the last item of the list, yg # and the length of the list, )Ë # are all four equal to each other ~ # Or y P # Check if all items in the list 2‹ # are either 0 and/or 1 ] # Close both maps P # Check if all parts in a partition were truthy (product) à # Check if any partition is truthy (max) # (after which the result is output implicitly) ``` [Answer] # [sed](https://www.gnu.org/software/sed/) `-E`, 50 bytes My sed is rusty and I’m not totally happy with this, but *c’est la vie*. Takes input on stdin with a trailing space, prints `T` or `F`. ``` s/\b1 /&&/g s/([0-9]+ )(0 )*\1//g /[^0 ]/{cF n} cT ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlWbSSrqtS7IKlpSVpuhY3jYr1Y5IMFfTV1PTTuYr1NaINdC1jtRU0NQwUNLViDPWBovrRcQYKsfrVyW5cebVcySEQnVADFtz0NVAwVDBQMAFiEGkEhCARLgjDCAoNwSQXRJ0xkDQG0lyGSCog2iCmAgA) ]
[Question] [ I've been playing around with a robot on the coordinate plane. This robot is able to tell me if it goes left, right, up, or down by reporting back a string consisting of the letters `L`, `R`, `U`, and `D`, such as `DLURRDLURDLLLRRLRLDURRU`. Each character represents a movement of one unit. However, it seems that the robot is going in loops on the plane, returning to coordinates that it has already visited. I don't want the robot to do that. I'd like the robot to tell me about the path it takes without any loops included - these loops should be removed from left to right in the string. Every step in the string it reports should represent movement to a cell that it has not yet visited before. If the robot ends where it starts, then it should report back an empty string. ``` Test cases ULRURU -> UURU URDLDRU -> DRU LLLLRRRL -> LL LLLULRRRL -> LLLUR UURDDRULDL -> {empty string} DLURRDLURDLLLRRLRLDURRU -> R URULLLDLUULDDLDRDDLLLLLDLLUUULLURU -> URULLLDLUULDDLDRDDLLLLLDLLUUULLURU ``` This is a standard code golf challenge, where the shortest answer wins. Standard rules apply. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` O2ȷ:ı*S ẆÇÐḟḢ⁸œṣFµÐL ``` **[Try it online!](https://tio.run/##y0rNyan8/9/f6MR2qyMbtYK5Hu5qO9x@eMLDHfMf7lj0qHHH0ckPdy52O7T18ASf////u/iEBgWBCBcfH5@gIJ8gHxegQCgA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/f6MR2qyMbtYK5Hu5qO9x@eMLDHfMf7lj0qHHH0ckPdy52O7T18ASf/4fbHzWtifz/P1o91CcoNChUnUtHPTTIxccFwvQBgqCgIB8oOxTOCQUqAqrxcQHzXHxCg4JAhAtYvU@QjwtQAGpYKFAMKAdUCzLWBaQEJAAUAcqArYwFAA "Jelly – Try It Online"). ### How? ``` O2ȷ:ı*S - Link 1, distance travelled: list of UDLR characters O - ordinals -> U:85 D:68 L:76 R:82 2ȷ - 2000 : - integer division -> U:23 D:29 L:26 R:24 (Note mod 4 these are 3 1 2 0) ı - square root of -1 - i.e. (0+1j) * - exponentiate -> U:(0-1j) D:(0+1j) L:(-1+0j) R:(1+0j) S - sum - 0 iff the path is a loop ẆÇÐḟḢ⁸œṣFµÐL - Main Link: list of UDLR characters µÐL - loop until no change occurs: Ẇ - all sublists Ðḟ - filter discard those which are truthy (non-zero) under: Ç - call last Link (1) as a monad Ḣ - head - X = first, shortest loop (if none this yields 0) ⁸ - chain's left argument œṣ - split at sublists equal to X F - flatten ``` [Answer] # [J](http://jsoftware.com/), 51 39 bytes ``` ([,~i.~{.])/@|.&.([:+/\0,0j1^'ULDR'&i.) ``` [Try it online!](https://tio.run/##hY6xCsJADIZ3nyI49Fq8pnU9KAgGp0yBm6ouYrFdfAClr34mom2dPLgj93/5/2RIa3QdNAEceKgh6C0R9sKHlLd@7HF84Kmodk/MMG/DpjrWvh62ZxeZxGU9FqlYXS@3O7gYJTooA3Ras9jvQ2gBhJhmwvwFrEdEeCYcZQHjD53iNE/jmCainsYIqV3soXcwC5MK02DdTnXl6rWNyNpMUCXa6MXGfzvTCw "J – Try It Online") *-12 bytes thanks to Bubbler! For the idea of combining "Under"s into a single train, and skipping an unnecessary increment of the indexes* ## The idea 1. Convert the letters to their indexes within the `ULDR` 2. Convert those indexes to complex vectors: Think `U = i`, `L = -1`, `D = -i` `R = 1` In fact, because of rotational symmetry, we don't actually care which direction is "up" as long the relative order of the directions is preserved. 3. Scan sum those vectors to get the path positions (still as complex numbers) 4. Reduce the path into a loop free version: Any time we arrive at a point we've seen, remove all history up to and including that old point. 5. Invert steps 1 to 3, in reverse order. The fun thing is that step 5 is accomplished with J's [Under](https://code.jsoftware.com/wiki/Vocabulary/ampdot) conjunction, which allows you to perform a transformation, do stuff, and then have the inverse transformation automatically applied. Here, J is smart enough to know how to invert the entire train comprising steps 1 through 3 in reverse order: ``` Elementwise reduce to Scan sum index within remove loops of... 'ULDR' | | | vvvvvvvvvvvvv vvvvv vvvvvvvv ([,~i.~{.])/@|.&.([:+/\0,0j1^'ULDR'&i.) ^^ ^^^^^^ | | Under 0 prepended to i raised to... ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~101 ... 91~~ 90 bytes ``` f=s=>s&&[s[Buffer(s).every(c=>p+=[w=s.length,~!++i,1,-w][c%5],i=p=0)-1]]+f(s.slice(p?1:i)) ``` [Try it online!](https://tio.run/##hZA/T8MwEMV3PkWIRGUrf0oGFiS3EvJ4kyVPUYbK2MEoTaw4tKoQfPVwJjDQ0OYGD0/3e/f8XneHnVe9dUPWds96HA3zbONXq9KXT2/G6J54muuD7k9EsY1LWHlkPm90Ww8v6edtkti0SLNjVaq7hyq1zLF7mhVVlRjic99YpYnbFo@W0lF1re8anTddTQyJJQgpZBxdGUqj9TqSuHZzDgsO/Do9wXzOAo4QAuIlFuAfVC6wvyhIMQuNqTEP8Mv4RL/rvRtOkR9629Yf5zYcrUV4@PdHQABH4U8Xk808AB4HPC8xQ@iPB4cgoCJDYhn/VL64OH4B "JavaScript (Node.js) – Try It Online") ## How? ### Method For each index \$n\$ in the input string, we initialize our position to \$(0,0)\$ and run a simulation of the walk starting from the \$n\$-th character. If there's some move at \$n+i-1,i>0\$ that brings us back to \$(0,0)\$, it means that we have identified a loop: we skip the entire segment and restart at \$n+i\$. ``` n n+i-1 v v ...LLURRD... ^ n+i ``` Otherwise, we append the current move to the output (***L*** in the above example) and advance to \$n+1\$. ### Implementation * Instead of relying on an explicit counter \$n\$, we use recursive calls to our main function where the leading characters of the input string are gradually removed. * Instead of using a pair \$(x,y)\$ to keep track of our position, we actually use a scalar value \$p=x+y\cdot w\$, where \$w\$ is the remaining number of characters in the string. This is safe because we can't have more than \$w\$ moves in the same direction from this point. * To convert a character move into a direction, we take its ASCII code modulo \$5\$. The ASCII codes of \$(D,L,R,U)\$ are \$(68,76,82,85)\$, which are conveniently turned into \$(3,1,2,0)\$. ## Commented ``` f = s => // f is a recursive function taking a string s s && // if s is empty, stop recursion [ // wrapper to turn undefined into an empty string: s[ // get either s[0] (next char.) or s[-1] (undefined): Buffer(s).every(c => // for each ASCII code c in s: p += [ // add to p: w = s.length, // +s.length for up ('U' -> 85 -> 85 % 5 = 0) ~!++i, // -1 for left ('L' -> 76 -> 76 % 5 = 1) // (increment i) 1, // +1 for right ('R' -> 82 -> 82 % 5 = 2) -w // -s.length for down ('D' -> 68 -> 68 % 5 = 3) ][c % 5], // using c modulo 5 // stop if p = 0, meaning that we're back to our // starting point i = p = 0 // start with i = p = 0 ) - 1 // end of every(), subtract 1 ] // end of s[] lookup ] + // end of wrapper f( // recursive call with either: s.slice(p ? 1 : i) // s.slice(1) (no loop) ) // or s.slice(i) (skipping the loop) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 26 bytes ``` t"0J&y15\^hYs&=XR&fq&:[]w( ``` [Try it online!](https://tio.run/##y00syfn/v0TJwEut0tA0Ji4jsljNNiJILa1QzSo6tlzj/3/10KBQHx8fF5/QUB8XFx@XICDhAxYAigBlgNLqAA) Or [verify all test cases](https://tio.run/##y00syfmf8L9EycBLrdLQNCYuI7JYzTYiSC2tUM0qOrZc43@suq6ueoRLyH/1UJ@g0KBQdS710CAXHxcwywcIgoKCfCDMUBg7FKgCqMDHBcRx8QkNCgIRLmDFPkE@LkABiDmhQCGgFFAlyEQXkAqQAFAEKAOyDAA). ### Explanation ``` t % Implicit input. Duplicate " % For each 0 % Push 0 J % Push j (imaginary unit) &y % Duplicate third-topmost element from the stack: current string 15\ % ASCII code of each character, modulo 15. This gives 10, 7, 8, 1 % for 'U', 'R', 'L', 'D' respectively ^ % Element-wise power. This gives j^10=-1, j^7=-j, j^8=1, j^1=j for % 'U', 'R', 'L', 'D'. These are the steps followed by the robot in % the complex plane (rotated and reflected, but no matter) h % Concatenate. This prepends the 0, as starting point of the path Ys % Cumulative sum. This computes the path traced by the robot &= % Matrix of pair-wise equality comparisons for robot positions XR % Upper triangular part, without diagonal &f % Row and column indices of nonzeros. This will be non-empty if % there is a loop in the path q % Subtract 1 &: % Two-input range. This uses the first element from each input, % that is, the first loop found []w( % Push [], swap, assignment index: this removes the characters that % caused the loop % string % End (implicit). The loop is run as many times as the input length, % which is an upper bound to the number of loops % Display (implicit) ``` [Answer] # T-SQL, 236 bytes First time I ever use `PI()` in sql I am [using table as input](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341) ``` WHILE @@rowcount>0WITH C as(SELECT*,sum(ascii(a)/12-6+3/(ascii(a)-79)*pi())over(order by b)x FROM @)DELETE C FROM C,(SELECT top 1max(b)i,min(b)j FROM C GROUP BY x HAVING SUM(1)>1or x=0ORDER BY 2)z WHERE(i=j or j<b)and i>=b SELECT*FROM @ ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1243748/remove-loops-from-a-walk)** [Answer] # [Java (JDK)](http://jdk.java.net/), 229 bytes ``` s->{var l=new java.util.Stack();int x=0,y=0,i;for(var c:(s+"").getBytes()){l.add(x+","+y);i="DLUR".indexOf(c);x+=~i%2*~-i;y+=i%2*(i-2);i=l.indexOf(x+","+y);if(i>=0){var z=l.subList(i,l.size());s.delete(i,i+z.size());z.clear();}}} ``` [Try it online!](https://tio.run/##bZBNa@MwEIbv@RXCEJBrR5Qe43UOXR@1LCj4VHpQZblMKtvBGmfjBPevu6O0TbfsCqQZPe87@pidPujVrnqZodl3PbId7cWA4MRN9g@qh9YgdO3/NI@91Q0pxmnv2S8NLTvvhycHhnnUSOHQQcUaEvgWe2ifHx51fP7ZtX5obP/jnd0P4Crbb@p89qvN@aB75vLW/vnrpi1q88LjDFpkx/w2HWlCVnc9D26z5j6Jolg8W7wf0Xoex2cndFXxYxKlUTJSZR4VslSRgLayx981N3F2TPJXWN7dvK4gG5M8pBxWd8Hsrr6vE2oOm/w2vjzwRA4/PEnwyCGlHE6Wbs28qKyzaAlCcrrikzDO6p5@ME3TnC0Yjc/X45paciGMfWsI8yxnoQ/fKMc4@3DXQhtj98j9FW1Hj7YR3YBiT0VY82jp12zpl22UYvppnBZhTot5LqUqVTmXqpAFRUlDKSVDUr5nJWkkyULOoYMqLMXFJpUsCITqkgAJ5ArnFEEPgAgpJL8B "Java (JDK) – Try It Online") ## Credits * 5 bytes saved thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) * 22 bytes saved thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~119 ... 111~~ 110 bytes Outputs by modifying the input string. ``` p;f(char*s){for(char*r,*q=s;*q;p?*s++=*q++:(q=r))for(r=q,p=0;*r?p+=(*r%17?strlen(q):1)*~-(*r++%5&2):0;);*s=0;} ``` [Try it online!](https://tio.run/##hZFPa8IwGIfvfopQcOSPYlutA0PwkmNOgZy2HUpnXUFrm8jGEPfR170xKiqF9RDK73nyy5u2GK@LousaXuLiI7fUkUO5s@HdjmgrHKctb5bUMSZoy9gCt8IS4iUr2lEjYk7tsmECUztMnpdubzerGrdkkRD6M4aUsWH2lJJFzAmnDvxj97mr3tE2r2pM0GGAkD8OufjlDQkUGaWNNhG/5sk511LJO5AGoODRWqsbMr0S84hm5zaogzYlb1kWmFRGa7/IU7PSSkJwe/L8MpIBA0zo8cNJv8EHkAAJ14BNJXYx4aixVb0vcTR0r3U0QqdsMkEwiglS0iMlQZIXJ@1x0uAoFZRpjzK9KDBVsGY91ixYh9W22X8j@JdVvT4GPevRs6CfC@d3BnCETpm/4r8fanDsfotyk69dN/76Aw "C (gcc) – Try It Online") ### How? The algorithm is the same used [in my JS answer](https://codegolf.stackexchange.com/a/205221/58563) with a few differences: * We use a `for` loop instead of a recursive approach. * We overwrite the input string with the output. This is safe because what is written is at most as long as what is read, and the meaningful information is always ahead of both the read and the write pointers (`q` and `s` respectively). * Given the ASCII code `c` of the move character, we use `c % 17` to find out if it's a vertical or horizontal move, and `c % 5 & 2` to distinguish between *down* and *up* or between *left* and *right*. ``` | 'D' (68) | 'L' (76) | 'R' (82) | 'U' (85) ---------+----------+----------+----------+---------- % 17 | 0 | 8 | 14 | 0 % 5 & 2 | 2 | 0 | 2 | 0 ``` [Answer] # perl -nF/(?{s-.\*(??{!($&=~y&R&&c==$&=~y&L&&c&&$&=~y&U&&c==$&=~y&D&&c)})--g;print})(\*COMMIT)/, 62 12 5 0 bytes [Try it online!](https://tio.run/##TYxBCsIwEEX3vYUgISnErlxJ6MJBEKYIg3MCESlIG9pupNSjW3/Mxlkkj/cmiffhuV8xyqKihQox4WaMiHACzaRoSExcEKtIOui3xsIEkV4rBAK20j@UehIwKMifPk5t342r706VrefR70pb1/PGbk14v4wYcwshM4ONyax/nsBucd4/DnFou2lxtjxemuZ8ddUX "Perl 5 – Try It Online") Finds substrings with the same amount of Ls and Rs, and the same amount of Us and Ds, and removes them. Prints the result. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 253 252 243 bytes ``` static String r(String s){String e=s;int l=s.length();for(int i=0;i<l;i++)for(int j=i+1;j<l;j++){int u=0;for(int k=i;k<=j;k++)u+=(9*(e.charAt(k)%6/3)+1)*2*(5.5-(e.charAt(k)-12)/11);if(u==0)return r(e.replace(e.substring(i,j+1),""));}return e;} ``` [Try it online!](https://tio.run/##hZDBa8IwFMbP@lcUYZC0Wq3DwYg5DHrMLpGexg6xRk1a05KkwpD@7d2r1LHL1hzC4/d9eS/f0@IqFlUtjT4UXV4K54J3oUxwm04754VXebDzVplTYNFQOHwbKkkdUcYHJXVxKc3JnxEmx8qiHiq6ImpbEhVF@ME0VVFCNFAN9NajBmwPuaCKFFuqSQFqE1H0GiIZ52dh3zwq8NPL8hlHCQ7XIdrEm8VvbZGs8TJJMFFH1FC6wlb6xhr4tYytrEuRS6hcs3f3ryM119BpPpthTNrBK0nbTepmX0LoIfu1UofgAgsZwn98BsKeHIb9TCa7L@flJa4aH9cg@tIgi2YZ4xnP@r5/W3jK0hEPg8M5Z2OmbNyVwTwYx9L/bSnLOO@v9D6acZYCGEuSgRkeQfc@U9q/7QEQUH4W0U7b7hs "Java (OpenJDK 8) – Try It Online") This uses a recursion method, so I'm not entirely sure if it's being scored correctly. It has a limit of going off 9 tiles in a given loop, but that can be increased to any amount as needed. Ungolfed: ``` public static String remove(String str) { String removed = str; int l = str.length(); for (int i = 0; i < l - 1; i++) //-1 optional for (int j = i + 1; j < l; j++) { int upDownLeftRight = 0; for (int k = i; k <= j; k++) upDownLeftRight +=(9*(e.charAt(k)%6/3)+1)*2*(5.5-(e.charAt(k)-12)/11); if (upDownLeftRight == 0) return remove(removed.replace(removed.substring(i, j + 1), "")); } return removed; } ``` A few seconds before I was going to submit this the post closed, a few days ago. Just realized it was opened back up. [Answer] # [Python 2](https://docs.python.org/2/), ~~94~~ 93 bytes *-1 byte thanks to @dingledooper!* ``` r="" x,=l=[0] for c in input():x+=1j**(ord(c)%15);r+=c;l[len(r):]=x,;r=r[:l.index(x)] print r ``` [Try it online!](https://tio.run/##hU/BasQgEL3PV0igrO5mQ7fQS4J78uhJ8BT2sE0stRgjaiH79emYtNBbRRze8715M@GRP2b/sg7zaAgnVVWtkVcVLDV3vH@@wfscyUCsxxu@MmXtcuKXz@ORznGkA3u6vLIunvjQud4ZTyNrb3ypu8hj37rG@tEsdGE3CNH6TOKKCQB2CnPMJD3S1t9Zb0oE4ibl0foWSKqJWYIZshlxrukeaMoRf6MN9WZoUnA208P5emAM9vFQ6e7T23hvE6DdDKTsBWQP/@33g3FVLZVWmpyvRGMFrYQUO8YCEo9SShYsZYH6D5ZaAboEKqXYOBDIqfKIzSmVFEhs/VCLOolKjfISI4qoEMjo0m2f41/VNw "Python 2 – Try It Online") A minor improvement over [@xnor's solution](https://codegolf.stackexchange.com/a/205285/92237) using slice assignment. Be sure to check out and upvote his answer! The current position `x` is stored as a complex number. For each movement, the program checks the list of visited positions `l`, and truncates the redundant moves appropriately. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes ``` ⊞υ⟦ⅈⅉ⟧FS«M✳ι⊞υι⊞υ⟦ⅈⅉ⟧≔…υ⊕⌕υ§υ±¹υ»⎚↑Φυ﹪κ² ``` [Try it online!](https://tio.run/##VY5Bi8IwEIXP7a/IcQLxsHtcT9IiFNJFIgUX8VDSsQ2bTUqaiCL@9mxyEHQOw5vHex8jp95J2@sYd2GZIDByPABl5Afoia7Ls3UEGjMHv/dOmREoJfeyaO0FoVYOpVfWgKIpWjwB6vV4oxWbZVGjgeomNVaTnXOiMdLhHxqPA2yVGbK38Y0Z8JrlN469R/igeRgJCfMoK429gyR36SkPX93MyFZpjy5XWjsEbeGXkc/UWcdY806IvGrOuRBc8DoZXVxd9D8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υ⟦ⅈⅉ⟧ ``` Save the current coordinates to the predefined empty list. ``` FS« ``` Loop through each character of the input string. ``` M✳ι ``` Move the cursor in that direction. ``` ⊞υι⊞υ⟦ⅈⅉ⟧ ``` Save the direction and the new position. ``` ≔…υ⊕⌕υ§υ±¹υ ``` Truncate the list to the original appearance of the position. ``` »⎚ ``` Reset the cursor (possibly due to a bug in Charcoal). ``` ↑Φυ﹪κ² ``` Output the directions which didn't get truncated. [Answer] # [Python 3](https://docs.python.org/3/), 178 bytes ``` x=y=0;c=[[0,0]];a='';t='UDLR';u=['y-=1','y+=1','x-=1','x+=1'] for i in input(): exec(u[t.index(i)]) if[x,y]in c:f=c.index([x,y]);a=a[:f];c=c[:f] else:a+=i c+=[[x,y]] print(a) ``` [Try it online!](https://tio.run/##LU6xCsMgFNz9CjeVpCWlm@Ftjk5CJnEQq1QoaUgN6NdbTQuPd9y9495tJT3f673WDAWm2YHW0zgZM1sgZE5AFiEVmQ/QpFzgRkZShhPyj@XODArvHUcc1zbbkSjjCPvsHT10usb14TONzDCEY9B5LKYZHQ/g/rdTY@2l1TyYVsJ1bBGvj@d2gIiwG1qzbjNo2@OaqGW1Crko1ZeQUiollRRNWL4 "Python 3 – Try It Online") Keeps track of visited coordinates and removes letters between duplicate coords. [Answer] # [R](https://www.r-project.org/), ~~208~~ 205 bytes ``` u=function(a){s=function(x)unlist(strsplit(x,'')) m=match d=s(a) l=length(d) for(i in 1:l)for(j in i:l)if(l&!sum(m(d[k<-i:j],s("L R"),2)-2)&!sum(m(d[k],s("D U"),2)-2))return(u(d[-k])) paste(d,collapse='')} ``` [Try it online!](https://tio.run/##XY87a8QwEIR7/QrHRW4FdpErj6hTqWpBVbjC@JHTnSwZPeAg5Lc7K5PHOSoE882OdhTW7Kz3i1izmLLrk/EOOv4R/9Sd04iJCWIKcbEmwb05HDhns5i71F/YICJFmBV2dO/pAgNnkw9gKuOql5PlRVyLMCTMBPb5KeYZZhjebq@tOV3PTYRaVVjz5sjbI3/wN0tW@sfiYUw5OMhktrcztVi6mEYYmt5b2y1xFNTt8/tXUGuFGinNfgFKJXdE0UFEtUf6P9OUpKCSj1AqjVguuT2iUEkC@32aLBqhZNksy2QBRMjZyq1f "R – Try It Online") Recursive function: starting at each position in the string, check whether there are equal numbers of L+R and of U+D in the range up to each subsequent position. If so, then this is the first left-to-right loop, so delete this and call the function using the result. Otherwise, there are no loops, so output whatever is left. Frustratingly, R is not particularly golfy at string-handling (at least with my ability), and one-third of the code is ~~wasted~~ used splitting strings into characters... so: # [R](https://www.r-project.org/)+stringr, 155 bytes (or [R](https://www.r-project.org/) 172 bytes) ``` u=function(d,l=nchar(d),s=substring){ for(i in 1:l)for(j in i:l)if(l&all(!diff(str_count(e<-s(d,i,j),s("UDLR",1:4,1:4)))[-2]))return(u(str_remove(d,e))) d} ``` [Try it online!](https://tio.run/##XY5Ba8MwDIXv@RVdDkOG9NCxU2luPvok8KmMkSZ2p@LaRYkLY@y3Z3LKYJlBhvdJ70k8Bzpxx58wTkzxzKrKMaR0a@fc@hz7iVKEoQlt7D86hkE1Yzvm02NafVU@MdCG4ma3D6qISxEkgjyE5y4EeBrI@5L/3qccJ3CH7SiR1FwkDGqrDdbNbv9aSil13L68KcVuyhwhLz5213R34nHSr4bv@XGjeA1atPXv0QJQG70iRh4imjWy/5kVpxiN/gu1sYjl00uIQaMFrPdZacmIOMtmXSYLECKd5bj5Bw "R – Try It Online") Exactly the same approach, but using `stringr` library to work directly on the string instead of splitting into characters. [Answer] # [Python 2](https://docs.python.org/2/), 98 bytes ``` r="" x,=l=0, for c in input():x+=1j**(ord(c)%15);l+=x,;r+=c;n=l.index(x);l=l[:n+1];r=r[:n] print r ``` [Try it online!](https://tio.run/##NY3BCsMgDIbvfQoRBm0tYw52qeTm0VPA0@jJOtohtkjH3NN3sWNBwu@Xj2T9bNMSr/t7moNnsvfZO875noDzKncQ4NJVjyUxx@ZIb31tddNnAfLZtvWSxto1J3lrVBCQO5UEOBUhnOc4@lxn4hDufRRyUAkSpaFa0xw3lvZyhluDFi2vuEVt9JEMFSKaX7T/bMkgwejy0cYilqYP2aDRBH57LCEakVk26mIUQIQmx7Ev "Python 2 – Try It Online") Instead of branching on whether the current position `x` has appeared before, we just look for where it first appeared and truncate to right after that. If it never appeared before, we find the current appearance, so nothing gets cut off. The `ord(c)%15` is from a suggestion by Jonathan Allan. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~168~~ ~~164~~ ~~163~~ ~~126~~ 125 bytes ``` l=[p:=0] n="" for s in input(): if(p:=p+1j**(ord(s)%15))in l:x=l.index(p);l=l[:x+1];n=n[:x];p=l[x] else:l+=[p];n+=s exit(n) ``` [Try it online!](https://tio.run/##NY5Ba8QgEIXv/goRCroppaEsFIM3j54GPAUPW@JSizUSXXB/fTom1IM83/uceflZv9f08Zm3vfpSC1WUzswasGDZK7OgjT6UwQMA5pT2X1skEDC6P7SxAP3SB2zAaDTOORYtjJDsE3UnuoEOJn2ZI71AWLDBlYSUHxVVvP1@LTdJj27zCbg9qjlL9e5IUoyR@7rRQkOixycuJKHhzhHIw/hzufB1W3gRL@NVCISibCq@hbT4xrOYooqzbMPopqQSKjdldJoj1MfiZRxwFWaDKsS3UHkS@/4H "Python 3.8 (pre-release) – Try It Online") Assigns a complex number to go up, down, left right on the complex plane. Then iterates over the given path S and either adds the new point to the path in the list of points `l` and the result string `n` or if it detected a loop from a previous index up until the current character, it slices the characters and points that created the loops out of the lists. -35 thanks to @JonathanAllan! [Answer] # [Wolfram Language](https://www.wolfram.com/language/), ~~101~~ 100 bytes ``` StringJoin[Characters@#/.(r={"L"->-"R","U"->-"D"})//.{a___,x__,b___}/;Tr@{x}==0->{a,b}/.Reverse/@r]& ``` [Try it online!](https://tio.run/##PY1BC8IwDIXv/owKotCt3mWjYE@Sg0R7EhmddG6HTahFBqW/faZzGEj48vJ46Y1vbW989zBTU0wX77rheXp1w@3YGmce3rq3XIt864rAgGVlxpBxpmdSLO6EyIOpqoqP1DVBFIerk2GMRbHPymB4HUWO9kNBVkh330xn@uGFbIQMK6YBNWrGiVCB@iFQISIsrP@LJhN5QM2bAo2Yhpr9gKBIWMI0aXQjb4pVyZIEUuiSXsbpCw "Wolfram Language (Mathematica) – Try It Online") With some fancier formatting and comments: ``` StringJoin[ (*reconvert to input format*) Characters@# (*split into characters*) /. (r = {"L" -> -"R", "U" -> -"D"}) (*map L to -R and U to -D*) //. {a___, x__, b___} /; Tr@{x} == 0 -> {a, b} (*delete runs that sum to 0*) /. Reverse /@ r (*convert -R and -D back to L and U*) ]& ``` This takes a similar method to some of the others, deleting runs that sum to zero, but this one does it by replacing L and U with negative R and negative D respectively. Another **100 byte** solution that uses a similar but distinct technique, using [SequenceReplace](http://reference.wolfram.com/language/ref/SequenceReplace.html): ``` StringJoin@SequenceReplace[Characters@#/.(r={"L"->-"R","U"->-"D"}),{__}?(Tr@#==0&)->{}]/.Reverse/@r& ``` [Try it online!](https://tio.run/##PY3BCsIwDIbvPkYHMmFbfYHNgj1JDhrtSWSUkenATa3Vy9izz3SKOYT///Mlaa2/UGt9U9mxzse9d0133tyaTu3p8aKuIqT71VZ0XF@ss5Un91SRzGKX9wJEWqQCRSLMpLQYFklflsMqPjgV5flyvkiLfjjJDOnNmySVm49b/uGlqqXqZ8IAGjQiYYUa9FcCFyLCT5u/MQwxA3pyGgxiaHriAUFz8DtmOOMZs@GsDkgIOOFJeDlIuXs15McP "Wolfram Language (Mathematica) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 44 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` gU0ˆÇ5%v1X‚Â(ìyè¯θ+ˆ¯¤kÐV¯gα<‚Xª£ιнJ¯Y>£´vyˆ ``` Ugh.. This can definitely be golfed substantially, but it works.. Inspired by both [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/205221/52210) and [*@OlivierGrégoire*'s Java answer](https://codegolf.stackexchange.com/a/205240/52210), so make sure to upvote them! [Try it online](https://tio.run/##AVUAqv9vc2FiaWX//2dVMMuGw4c1JXYxWOKAmsOCKMOsecOowq/OuCvLhsKvwqRrw5BWwq9nzrE84oCaWMKqwqPOudC9SsKvWT7Co8K0dnnLhv//VUxSVVJV) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeXhCf/TQw1Otx1uN1UtM4x41DDrcJPG4TWVh1ccWn9uh/bptkPrDy3JPjwh7ND69HMbbYDyEYdWHVp8bueFvV6H1kfaHVp8aEtZ5em2/7W1Ooe2/I9WCvUJCg0KVdJRCg1y8XEBs3yAICgoyAfCDIWxQ4EqgAp8XEAcF5/QoCAQ4QJW7BPk4wIUgJgTChQCSgFVgkx0AakACQBFgDIgy2IB). **Explanation:** ``` g # Get the length of the (implicit) input-string U # Pop and store it in variable `X` 0ˆ # Add 0 to the global array Ç # Convert the (implicit) input-string to an integer-list of codepoints 5% # Take modulo-5 on each v # Loop over each integer `y`: 1X‚ # Pair 1 with the length `X`: [1,length]  # Bifurcate it (short for Duplicate & Reverse copy) ( # Negate the values: [-length,-1] ì # Prepend the lists together: [-length,-1,1,length] yè # Index `y` into this quadruplet ¯θ+ # Add the last item of the global array to it ˆ # And pop and add it to the global array ¯ # Push the global array ¤ # Push its last item (without popping) k # Get the first index of this last item in the global array Ð # Triplicate this index V # Pop and store one copy in variable `Y` ¯g # Push the length of the global array α # Take the absolute difference with the index < # Decrease it by 1 ‚ # Pair it with the index Xª # And append length `X` £ # Split the string into parts of that size # (which uses the implicit input-string in the very first iteration) ι # Uninterleave it н # Only leave the first part of two strings, removing the middle part J # Join this pair together ¯ # Push the global array again Y> # Push `Y` + 1 £ # Only leave the first `Y`+1 values of the global array ´ # Empty the global array v # Loop over the `Y`+1 values of the global array: yˆ # And add each of them back the global array ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~126~~ 120 bytes ``` $x=$y=0 switch -r(,'-'+$args){U{$y++}D{$y--}R{$x++}L{$x--}.{$g="$g$_$x-$y"-replace"(?<=($x-$y)).*\1$"}} $g-replace'\d|-' ``` [Try it online!](https://tio.run/##hZFRT8IwEMff@yma5bSbrESfdRFjE1@aaEr6BIbgqEMzBNcRIKWffV43przZh13u97/fddk2652p7NKUZQPvNKOugX0Gh@ya2N1HnS8pr@KUcTaAeVXYxGkHh8HACyyce@Vgj53Egt3QQZFFUMAMWzhEvDKbcp6bKL6/y@KWJcnwanoDkfcEij5n08WRs8YTMooJSWOmpdJKs5QyHWrSMiWk6KDomcSjlJIBSvnL9BmUWp18XICiFG3QMYGpCg/RLpJKCgTtHb2FhkRHoxjuF2EyACQ6LO/e8v@phJCEHukFdYTigXy9Ws2/FjalYPYbk9dmgV8fZl1aGbstawSX@FNG/WybTV7Gj1tbr1fPb5@ovY4cHW/z3Fgb/JPIzfff3lsqHp7OQk988wM "PowerShell – Try It Online") The script: 1. injects `$x-$y` to input string like `-0-0U0-1U0-2R1-2U1-3` 2. removes substrings between same coordinates 3. removes digits and minus chars Less golfed: ``` $x=$y=0 switch -regex (,'-'+$args){ U {$y++} D {$y--} R {$x++} L {$x--} . {$g="$g$_$x-$y"-replace"(?<=($x-$y)).*\1$"} } $g-replace'\d|-' ``` ]
[Question] [ In the burial place of King Silo of Asturias there is an inscription that reads **SILO PRINCEPS FECIT** (*King Silo made this*). ![SILO PRINCEPS FECIT](https://upload.wikimedia.org/wikipedia/commons/3/32/Silo_princeps_fecit.JPG) The first letter is found in the very middle, and from there one reads by going in any non-diagonal direction radiating outward. The final letter is found on all four corners. In this challenge, you'll generalize the process to make them. ## Input A string ([or equivalent](https://codegolf.meta.stackexchange.com/questions/2214/whats-a-string/2216)), and an integer. You may make the following assumptions about the input: * The string will have an odd length. * The integer will be an odd number between 1 and one less than twice the length of the string. ## Output An *inscriptio labyrinthica* for the string, using the integer for the height *or* width (see models for height examples). Output should be each letter with no spaces, line break as default to your system/language. ## Test cases Note that an input of 1 or (length \* 2 - 1) will result in a horizontal or vertical palindrome. ``` Input: FOO, 3 Input: BAR, 1 Input: BAR, 3 Input: BAR, 5 Output: OOO Output: RABAR Output: RAR Output: R OFO ABA A OOO RAR B A R Input: ABCDE, 5 Input: ABCDE, 3 Input: *<>v^, 5 Output: EDCDE Output: EDCBCDE ^v>v^ DCBCD DCBABCD v><>v CBABC EDCBCDE ><*<> DCBCD v><>v EDCDE ^v>v^ ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) forbidden. [Answer] # [J](http://jsoftware.com/), 27 bytes ``` ([{~]+/&(|@i:)#@[-1+])-:@<: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NaKr62K19dU0ahwyrTSVHaJ1DbVjNXWtHGys/mtycaUmZ@QrqLv5@6srpCkYQ7nqUNrJMQgkbIhd2BRN2NHJ2cUVr4TxfwA "J – Try It Online") An example will clarify the high-level approach. Consider `'ABCDE' f 3` We notice that what we seek is simply the "cross addition" table of `1 0 1` and `3 2 1 0 1 2 3`, which looks like this: ``` 4 3 2 1 2 3 4 3 2 1 0 1 2 3 4 3 2 1 2 3 4 ``` We then pull those indexes from the original string: `[{~`. All the rest of the code is just boring arithmetic and the use of `i:` to construct the arguments `1 0 1` and `3 2 1 0 1 2 3`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` Uṡṛ‘HɗŒBŒḄZY ``` [Try it online!](https://tio.run/##y0rNyan8/z/04c6FD3fOftQww@Pk9KOTnI5OerijJSryv/Wjhrk61o8adwLxdmufRw0zPY51PWrcVnFyOlBqTtmhbUAF1oeXA6X3Hdp2aBvX4eWPNq7T5zrc/qhpzf//0dFKbv7@SjrRxrGxOtFKTo5BQLahjrGOKZjv6OTs4goUMdWByGvZ2JXFwVUHe/r4BwR5@jm7BgS7uTp7hoD0AjXG/gcA "Jelly – Try It Online") A dyadic link taking the string as its left and height as its right argument. Returns a string with line breaks. If a list of strings were acceptable for output, I can remove the final `Y` saving a byte. Interestingly the original “SILO PRINCEPS FECIT” looks to me like ASCII art of a 3D diamond when I look at it on TIO. ## Explanation ``` U | Reverse input ṡ ɗ | All overlapping substrings of the length given by: ṛ | - The right argument ‘ | - Incremented by 1 H | - Halved ŒB | Concatenate to the reverse, keeping a single copy of the last character (so creating a palindrome) ŒḄ | Do the same, but this time using the lists of characters generated by the last atom Z | Transpose Y | Join with newlines ``` [Answer] # [R](https://www.r-project.org/), ~~93~~ ~~91~~ 87 bytes -2 bytes thanks to Giuseppe. -4 bytes by inputting the width rather than the height, as allowed by OP. ``` function(s,W,w=W%/%2,h=length(s)-w-1)write(s[1+outer(abs(-w:w),abs(-h:h),`+`)],1,W,,"") ``` [Try it online!](https://tio.run/##bY7RCoJAEEXf@4pYEHZyJCwikgzKDIKoqMCHKCzRFEJBrf18G7f1QfDhwO6Zu3cnryK7ij5pUCZZygv0UNieNtRGGNvvMH2VMS/AEIYJIk/KkBdXU88@ZZjzx7PghrAEoDzFVgzo6z7c0KQWZAyqiAecbRiygwSwP4ZeT9oVmSVxqu2k03ZnzcbWpp44xJpwW02d02kzHZCZEwviS9xbb89ktsRObX6Uf//dXnW6ytfZjbo7KnORe86g@gE "R – Try It Online") Takes input as a vector of characters. The key part is `s[1+outer(abs(-w:w),abs(-h:h),'+')]`. First compute \$w\$ and \$h\$ such that the output is of size \$(2w+1)\times(2h+1)\$. In the output, we want the character in position \$(i,j)\$ to be the character at index \$1+|i-h|+|j-w|\$ in the input. This corresponds to the outer sum of `abs(-w:w)` and `abs(-h:h)` (`abs(-h:h)` is a short way of writing the vector \$[h, h-1, h-2, \ldots, 2, 1, 0, 1, 2, \ldots, h-1, h]\$). For instance, `outer(abs(-2:2), abs(-1:1), '+')` gives ``` 32123 21012 32123 ``` (we then need to add 1 because R is 1-indexed.) The 0 in the centre is where the first letter of the input should go. The rest is formatting. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~25~~ 19 bytes ``` E⊘⊕η✂θι⁺ι⁻Lθ⊘⊖η‖O←↑ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDDIzGnLDVFwzMvuSg1NzWvBMjO0NTUUQjOyUxO1SjUUcjUUQjIKS3WANK@mXlAhk9qXnpJhkYhUBFUs0sqimYQsOYKSk3LSU0u8S9LLcoB2mPlk5pWoqNgFVqgaf3/v6OTs4srl/F/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` E⊘⊕η✂θι⁺ι⁻Lθ⊘⊖η ``` Draw a quarter of the inscription. ``` ‖O←↑ ``` Reflect to complete the inscription. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~19~~ 16 bytes ``` z ò@VÔtXUaVÊ)êÃê ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=egryQFbUdFhVYVbKKerD6g&input=MTUKIlNJTE9QUklOQ0VQU0ZFQ0lUIg) ``` z\nò@VÔtXUaVÊ)êÃê :Implicit input of integer U & string V z :Floor divide U by 2 \n :Reassign result to U ò :Range [0,U] @ :Map each X VÔ : Reverse V tX : Substring from index X to index ... Ua : Absolute difference between U and ... VÊ : Length of V ) : End substring ê : Palindromise à :End map ê :Palindromise :Implicit output, joined by newlines ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~57~~ 54 bytes ``` (g=Reverse@Rest@#~Join~#&)@BlockMap[g,#,⌈#2/2⌉,1]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XyPdNii1LLWoONUhKLW4xEG5zis/M69OWU3TwSknPznbN7EgOl1HWedRT4eykb7Ro55OHcNYtf8arskZ@Q7KytYBRZl5JfoOadHOGYlFicklQJMclHWUjWI11RwcHKq5qpXc/P2VdIxrdYBMJ8cgJR1TBBNJ1BDMdHRydnGFKYFyzMEcLRu7sjiQDFftfwA "Wolfram Language (Mathematica) – Try It Online") Takes the width as input. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 10 bytes ``` Ôã°Vz)mê ê ``` Takes width instead of height. [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=1OOwVnopbeog6g&input=IlNJTE9QUklOQ0VQU0ZFQ0lUIgoxOQ) Pseudocode (U is string, V is integer): ``` U.Reverse().AllSubstringsOfLength(++V / 2).Map(Palindromize).Palindromize ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~68~~ 67 bytes ``` {say |$^a.comb[{$_...0...$_}($a.comb-$^b+>1-1)X+.abs]for ^$b-$b+>1} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/ujixUqFGJS5RLzk/Nym6WiVeT0/PAIhV4ms1VCCiuipxSdp2hrqGmhHaeolJxbFp@UUKcSpAcZBw7X8gl0tD3c3fQF1HwVhTB8h2cgwCsg2R2MjipmC2o5OziysGD6JOy8auLA4uF@zp4x8Q5Onn7BoQ7Obq7BkCMttUk6uaizNNo0YlXtOai7OgKDOvREEpJk/Jmqv2PwA "Perl 6 – Try It Online") [Answer] # Python 3, 104 bytes I haven't golfed in so long... I'm sure this could be shorter. ## Details This code defines a function that takes two arguments (the string and the height) and gives the result on standard output. The index into the string is the Manhattan distance from the centre of the grid. For a grid of width `w` and height `h`, the distance for the cell at `(x, y)` is `abs(x - (w - 1) / 2) + abs(v - (h - 1) / 2)`. The width of the grid must be such that the Manhattan distance of the corners (say, `(0, 0)`) is one less than the length of the string. Substituting `(0, 0)` into the above and simplifying, we find that the width is simply `2 * len(s) - h`. ## Code ``` def b(s,h): w=2*len(s)-h for y in range(h):print(''.join(s[abs(x-w//2)+abs(y-h//2)]for x in range(w))) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFJo1gnQ9OKS6Hc1kgrJzVPo1hTN4NLIS2/SKFSITNPoSgxLz1VA6iioCgzr0RDXV0vKz8TqCo6MalYo0K3XF/fSFMbxK7UzQCxY0E6KxA6yzU1Nf8naSi5@fsr6SgYa3JBzNHkAoo5OQYBxQyxiGFTZ4oi5ujk7OKKUxRVv5aNXVkchtpgTx//gCBPP2fXgGA3V2fPEJBbTDX/AwA "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` RŒI>;ù€ûû» ``` [Try it online!](https://tio.run/##ASIA3f9vc2FiaWX//1LFkkk@O8O54oKsw7vDu8K7//9BQkNERQoz "05AB1E – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 19 bytes ``` L+_btbjyyM.:Q-lQ/E2 ``` [Try it online!](https://tio.run/##K6gsyfj/30c7PqkkKauy0lfPKlA3J1Df1ej/f6VgTx//gCBPP2fXgGA3V2fPECUuQ1MA "Pyth – Try It Online") ``` L+_btbjyyM.:Q-lQ/E2 Implicit: Q=string, E=height L Define a function, y(b): _b Reverse b + tb Append all be first element of b y is now a palindromisation function lQ Length of Q - /E2 Subtract floored division of E by 2 .:Q All substrings of Q with the above length yM Palindromise each substring y Palindromise the set j Join on newlines, implicit print ``` [Answer] # [Python 2](https://docs.python.org/2/), 95 bytes ``` def f(s,n): y=len(s);n//=2 for i in range(n+1)+range(n)[::-1]:print s[y+~i:n-i:-1]+s[n-i:y-i] ``` [Try it online!](https://tio.run/##tYpNDoIwEEb3c4pZthZCgLCpYuLvlgMQNCRSncQMpEVNN169SnThBdy9971v8OOl5yyEU2fQCBex1IC@vHYsnJxzkpQZoOktEhKjbfncCVapVF@UtdZx2ujBEo/oaq@epDmmaVSunsjH1AQjbPs4Eg@3Ucjo/f11KeHPPazWm@0OCthXFeTwsRxmi@X9EEHxAg "Python 2 – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~11~~ 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` é─C[┬«#t▒ ``` [Run and debug it](https://staxlang.xyz/#p=82c4435bc2ae2374b1&i=3,+%22FOO%22%0A5,+%22BAR%22%0A1,+%22BAR%22%0A3,+%22ABCDE%22%0A5,+%22ABCDE%22&a=1&m=2) It takes the width, and the original string, in that order. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 146 bytes ``` s=>n=>{int w=s.Length*2-n,i=0,j;var r=new char[n,w];for(;i<n;i++)for(j=0;j<w;)r[i,j]=s[System.Math.Abs(n/2-i)+System.Math.Abs(w/2-j++)];return r;} ``` [Try it online!](https://tio.run/##dVDRasIwFH3vV1z2lM7aVd9GmsIQHYJuMgd7KH3IaqwpegtJtIj47V1q3Ww3dh8Scu65J/ecVPfTQokq3XKtYaGKTPGdc3LAljbcyBSU4KsCt0dYHrURO3@yxzTURknMvA4m0XiQbriKvSSKYA2s0ixCFp1sB0qm/ZnAzGzuh330JAu8nB64AsVQlM0cemVC14UiVIZIZa/n1o@cBTQPS@qqWHp5wnR8/XXOzcZ/@tQEH4Z96fZ@w6WFcyuSUCXMXiEoeq6o0zZ3KOQK5lwiaRzFCXCVaffCaWKoq94TgcHgkXYwbbG75XT2Cou36ctovFjCZDyavt91aUrUxDXRLkH31rLmgNTZSNsNqL3Cmuo/C9MkRQLXotbBz8htpY5A3gjkfwQGViBvC3zXNatRgbrYCv9DSSOInb1E3NrxP@5MoiAt3tlpznP1BQ "C# (.NET Core) – Try It Online") Longest answer so long. :-) It uses the Manhattan distance to the center of the square. There must be a shorter way, though. [Answer] # [Tcl](http://tcl.tk/), ~~188~~ ~~170~~ 162 bytes ``` {{w s} {join [lmap C [lrepeat $w string] {join [$C reverse [set y [$C range $s [set x [expr abs($w/2+1-[incr i])]] end-[expr $w/2-$x]]]][$C range $y 1 end]}] \n}} bytes ``` [Try it online!](https://tio.run/##bYzBisIwGITvPsVYcnDVIt1lD4IIWhf2DTykWcjqr1RiGpJoW0qevbYUYVmcy8B8H@MPqnXkcULWNk0JF9BcilyDq6s0SLu2ZEh6sA56m@uzeBoshaU7WUfg/Uc9TFKfCcwNWwVOlbGQv27CysX7LIl5rg8WuXgTAqSP8SD0MGaV6PLnpUbSOyIIZDqE1ty8Q8SlMaoGO@ED0TcpVcyxL6w6jiMRjf47n5iu1vefFyTBZpvuvl6Q5ZO0Dw "Tcl – Try It Online") There seem to be a million bad ways to golf this problem in TCL. This is not the worst of them. Saved 18 bytes minimum by converting to lambda (can save up to 13 more if return value of a list of lines is acceptable) Saved an additional 8 since lmap iterator served as an extra constant [Answer] # [Canvas](https://github.com/dzaima/Canvas), 18 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ±X↕┌L╵┌-Y{x;1y1@]┼ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JUIxJXVGRjM4JXUyMTk1JXUyNTBDJXVGRjJDJXUyNTc1JXUyNTBDJXVGRjBEJXVGRjM5JXVGRjVCJXVGRjU4JXVGRjFCJXVGRjExJXVGRjU5JXVGRjExJXVGRjIwJXVGRjNEJXUyNTND,i=U0lMT1BSSU5DRVBTRkVDSVQlMEExNQ__,v=8) Canvas doesn't do substrings, so I need to treat it like an art object and get a subsection that way. I feel like this costs me 2 bytes, but hey, what can you do. Looks like this actually doesn't work like I thought: Canvas's palindromize functions mirror certain characters (e.g. V mirrored vertically becomes ^), and I can't exactly disable that... oh well, i guess [Answer] # [Ruby](https://www.ruby-lang.org/), 65 bytes ``` ->s,h{(-(h/=2)..h).map{|y|(z=s[(w=y.abs)..w+~h]).reverse.chop+z}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf165YJ6NaQ1cjQ9/WSFNPL0NTLzexoLqmskajyrY4WqPctlIvMakYKFOuXZcRq6lXlFqWWlScqpeckV@gXVVb@7@gtKRYIS1aydHJ2cXVzd3D08tbSUfB0DT2PwA "Ruby – Try It Online") ]
[Question] [ The famous constructed language [Esperanto](http://en.wikipedia.org/wiki/Esperanto) uses the Latin alphabet (mostly, see the linked wikipedia page for details). However, there are some characters with accents: **ĉ, ĝ, ĥ, ĵ, ŝ, and ŭ**. (C-circumflex, g-circumflex, h-circumflex, j-circumflex, s-circumflex, and u-**breve**.) Naturally, these characters are very hard to type. Even for this question, I had to search in the Unicode selector for the characters. Due to this, a convention using the letter "x" has been developed for electronic use. For example, "cxu" is used for "ĉu". (Note: the letter "x" is not used normally in the Esperanto alphabet." However, I am a language purist! This \*air quote\* x nonsense is killing me! I need a program to fix this, preferably as short as possible so I can type it into my terminal as fast as possible! ## Challenge Your mission is to take a string of Esperanto using x-convention and convert it to real Esperanto. In effect, you have to map: ``` cx: ĉ gx: ĝ hx: ĥ jx: ĵ sx: ŝ ux: ŭ Cx: Ĉ Gx: Ĝ Hx: Ĥ Jx: Ĵ Sx: Ŝ Ux: Ŭ ``` All other printable ASCII characters should be accepted and not changed. Unicode would be nice, but not necessary. Input and output can be in any format reasonable to your language. Good luck! ## Testcases ``` "input" : "output" _____________ "gxi estas varma" : "ĝi estas varma" "Cxu sxi sxatas katojn aux hundojn?" : "Ĉu ŝi ŝatas katojn aŭ hundojn?" "Uxcxsxabcd(hxSx)efg{};" : "Ŭĉŝabcd(ĥŜ)efg{};" "qwertyuiop" : "qwertyuiop" " " : " " "" : "" "x" : "x" "xc" : "xc" "xcx" : "xĉ" "cxx" : "ĉx" ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Answers are scored by smallest bytecount in the language's default encoding. Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=149292,OVERRIDE_USER=47670;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> ``` Good luck, have fun, and feel free to suggest improvements! ## Clarifications: * You only need to worry about *printable* ASCII characters. * You only need to output a character that *looks like* the correct output. Yes, this means you can tack the accent onto the standard character. [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 65 bytes ``` .x 3::⍵M⋄'ĉĝĥĵŝŭĈĜĤĴŜŬ'['cghjsuCGHJSU'⍳⊃⍵M] ``` [Try it online!](https://tio.run/##KyxNTCn6/1@vgsvYyupR71bfR90t6kc6j8w9svTI1qNzj6490nFkzpElR7YcnXN0jXq0enJ6RlZxqbO7h1dwqPqj3s2PuppBumL//0@vyFRILS5JLFYoSyzKTeRyrihVKAaKFVckggSzE0vys/IUEksrFDJK81Lys@y5QiuSK4CySckpGhkVwRWaqWnp1bXWXEqF5alFJZWlmfkFSlxKCkAMRBUgnAwmQMzkigolAA "QuadR – Try It Online") `.x` replace any char followed by "x" with `3::⍵M` upon indexing error, return the match unmodified `⋄` now try:  `'ĉĝĥĵŝŭĈĜĤĴŜŬ'[`…`]` index into this string with   `⍵M` the match's   `⊃` first letter's   `⍳` index   `'cghjsuCGHJSU'` in this string This is equivalent to the Dyalog APL tacit function: ``` '.x'⎕R{3::⍵.Match⋄'ĉĝĥĵŝŭĈĜĤĴŜŬ'['cghjsuCGHJSU'⍳⊃⍵.Match]} ``` [Answer] # [Retina](https://github.com/m-ender/retina), 27 bytes ``` iT`x`̂`[cghjs]x iT`x`̆`ux ``` [Try it online!](https://tio.run/##JclNDkExFIbh@VnFGbIGAwNLwEgkPXqrP6Lltr0@ERMDq7Onqkje0fOOpvgorfmNgvq81E5bF/Ie9Ie3qmjNwrPJRTJPMp6FVqicu2XID09SUogsFexqHFJY0hYa/R70MHNYY26O9vFc0PVmxnKvPl2IiUDQPZAGvg "Retina – Try It Online") This program is composed by two transliterations. Due to having combining characters in the code this doesn't render too well, the first line should actually look similar to `iT`x`^`[cghjs]x`, where `^` stands for the circumflex accent combining character. What this is saying is that it should `T`ransliterate (`i`gnoring case) all the `x`s in the input into a `^`, whenever they are following any letter in `[cghjs]`. --- Note: TIO incorrectly measures this code as 25 bytes. Actually, this Retina program uses UTF-8 encoding (other programs can use UTF-32 or ISO 8859-1) and the two combining characters present cost 2 bytes each. [Answer] # C, ~~173~~ 154 bytes *Thanks to @Colera Su for saving 17 bytes!* ``` p,c,i;f(char*s){for(char*l="cghjsuCGHJSU";p=*s;~c&&putchar(p))for(c=*++s,i=0;c=='x'&&l[i];++i)l[i]-p||write(1,"ĉĝĥĵŝŭĈĜĤĴŜŬ"+i*2,2,c=-1,++s);} ``` [Try it online!](https://tio.run/##bY69TsMwFEb3PoXlIbUTR6JdLYuhA4i16oQYzG1@HNokxAk1SssM79BusMFG38B5rpCA2HynT@ee7@pCmAD0fcmAKR4TSGXla9rGRfWXNwJDkma6WVxd3yxXmJfC1/wFPK9s6tEgJaW/tvCDQDMlLjgIMTVTz9vcqjseBIqOISz3@12l6ojMGLZv9mQ/7Lk7dV/21R7tu/3ujt0nDpQ/Z3MGIpyx4Rzlh17lNdpKlRM6aSdomJjgxCgU6Vpq9CSrrcSUD99ogofwryxMg/SgaSNH70HWRZYj2RiUNvm6yC5dpZUBMxTuYU1SszQ0ipP2wF3m4y6q6udGFaVri1zQxYwTgps6ZTAjnhz6Hw) **Explanation:** ``` p,c,i; f(char*s) { // The outer loop and an array of characters that are modified by a trailing 'x'. // The array/string is used for getting the index for the accented character later. for (char*l="cghjsuCGHJSU"; // Store the current character of the input string in 'p'. // If it is '\0', the loop terminates. p=*s; // The last statement in the loop. // If 'c==-1', it outputs the char stored in 'p'. ~c&&putchar(p)) // Store the character following 'p' in 'c' and increment the string pointer. for(c=*++s, i=0; // If 'c' is not the letter 'x', the inner loop terminates // immediately. Otherwise it loops through the characters of // string 'l'. c=='x'&&l[i]; ++i) // If the character stored in 'p' is found inside the string 'l'... l[i]-p || // ...then print the accented character corresponding to 'p'. // 'i' is the index of 'p' in 'l', and, because the characters // with accents are two bytes each, the index is multiplied by 2. write(1,"ĉĝĥĵŝŭĈĜĤĴŜŬ"+i*2,2, // Finally set 'c' to -1 so that the non-accented character doesn't // get printed too, and increment the string pointer so that the // letter 'x' doesn't get printed either. c=-1, ++s); } ``` [Answer] # [Python 3](https://docs.python.org/3/), 81 bytes ``` lambda s,T="cĉgĝhĥjĵsŝuŭ":eval("s"+".replace('%sx',%r)"*12%(*T+T.upper(),)) ``` [Try it online!](https://tio.run/##XcpNDsFAGMbxvVNMJmnMVCPBjlg5gtrZvKbTL9WO@eAVcQCHsLS0dIM6V7GRjOXvef7qZPOmnnTpfN1VsNskQEwUz6lor1l7y9t72T7N6@ZeDzqVB6gYNXRAh1qqCoRk/cBgPwo0p@FoHLAwHsRDp5TUjEecd0oXtWUpoxkWRBoLhhxA74By3vt9C3TEfH6D8A22YJuyJuCQ5K5OmtKLVyjwE25EwnJcIpdpdr7MvGR/lNqeXNEobyaePKAv8Uf/Fvh19wY "Python 3 – Try It Online") Generates and evaluates the string: ``` s.replace('cx','ĉ').replace('gx','ĝ').replace('hx','ĥ').replace('jx','ĵ').replace('sx','ŝ').replace('ux','ŭ').replace('Cx','Ĉ').replace('Gx','Ĝ').replace('Hx','Ĥ').replace('Jx','Ĵ').replace('Sx','Ŝ').replace('Ux','Ŭ') ``` *Erik the Outgolfer saved a byte.* [Answer] # [///](https://esolangs.org/wiki////), 75 bytes ``` /,/\/\///>/x\,/c>ĉ,g>ĝ,h>ĥ,j>ĵ,s>ŝ,u>ŭ,C>Ĉ,G>Ĝ,H>Ĥ,J>Ĵ,S>Ŝ,U>Ŭ/ ``` Note: Because the OP request all printable characters must be processed, my "special characters" chosen must not be printable. So I chosen tab and newline instead of , which does not change my bytecount or code functionality. The code would look like: ``` / /\/\/// /x\ /c ĉ g ĝ h ĥ j ĵ s ŝ u ŭ C Ĉ G Ĝ H Ĥ J Ĵ S Ŝ U Ŭ/ ``` However that requires the input must not contains tab or newlines. [Try it online!](https://tio.run/##VYyxTsMwEIb3PIXlCaSTvIN0DB1ArFW3Ssi4IUmhSaljOITYm3dINrq1G7zB@bmC4wBqz8N9/3//b/ukbZ7avleg5uEphYrmoAxyAxlyBznyDpbI32DRd@DQH2CCvIVr5BZukD/hFvkLpuhbmKHfq14W5drVUlwIWbl6wOTueBKZUSFSW2srXvRmpWOUu1MvkRNywoakJT3Yj7qulqXQjkTuykW1vBp7Wyd86PruJOUP/6lEzshQ@OXeLM5ymtJ5@pC9f1zGut9zE6rDiXe@/Tsl8vk13dRvrqjWMXckEymiJQJFCJsi0EBmRBP51@cmKEOj4oZk/wM "/// – Try It Online") Because `///` can't take input, you should put the input after the code. Pretty straightforward. I guess it can't be shorter because `///` need special handling of each character. Explanation: ``` /,/\/\// Replace all `,` in the code by `//` (two slashes are represented as two backslash-ed slashes) />/x\, (in original code) becomes />/x\// (because `,` is replaced by `//`) - replace all occurence of `>` by `x/`. /cx/ĉ//gx/ĝ//hx/ĥ//jx/ĵ//sx/ŝ//ux/ŭ//Cx/Ĉ//Gx/Ĝ//Hx/Ĥ//Jx/Ĵ//Sx/Ŝ//Ux/Ŭ/ ^ The remaining part of the code should look like this. Straightforward replacement. ``` [Answer] # [Python 3](https://docs.python.org/3/), 95 bytes ``` f=lambda x,v="cĉgĝhĥjĵsŝuŭCĈGĜHĤJĴSŜUŬ":v and f(x.replace(v[0]+"x",v[1]),v[2:])or x ``` [Try it online!](https://tio.run/##XYo7TgMxFEV7VvHkyhYR4tMFpUoBoo1SRVO8eP4k9uAfL0L0sIekgw462IFnXZNJg2SaK517TrdztVY3w1DONrhd5wg0CTMm43sVD3X8bOOv7Q@@/57Ht7u4v48fD/Fn0e@X/RebBkCVQ8npwhTdBmXBw@oyO2fEJmF1lYlxr6eZ0AZo6EyjHC85q6iBwjq0ENBskQlx9ufm5MGO3hKegkd0ulWAnqD2KtdtEi9J0hiuZc5rWpAoyurl9TZJnp4L43a@0V1yQ0IJUEryH6Za0omHIw "Python 3 – Try It Online") -10 bytes thanks to WhatToDo -1 byte thanks to Colera Su [Answer] # [Retina](https://github.com/m-ender/retina), 55 bytes ``` iT`CG\HJSUcg\hjsux`ĈĜĤĴŜŬĉĝĥĵŝŭ_`[cghjsux]x ``` [Try it online!](https://tio.run/##HYoxEsFAFED7f4otOYNCkYLRRiqMrM3abIyE7C7fGD13SDo6Om7w91wrzLzqvVdLq0segp6m0Wg@nsSJUPO8MA5TulJDd3r7xj/pRi096ONb/1qmM6H@ywJDUKiZNJYbduD1lkOEjpnOGeQ/ueG2KkrGHbLclVlVDCFBgV1diayXY4x9uVbnywD2R1nbk9PVDhgAAooOBIH4BQ "Retina – Try It Online") Non-combining approach. Bytes could be saved if not for the standalone `x` test cases. [Answer] # [Perl 5](https://www.perl.org/), 101 + 1 (`-p`) = 102 bytes ``` %k=qw/c ĉ g ĝ h ĥ j ĵ s ŝ u ŭ C Ĉ G Ĝ H Ĥ J Ĵ S Ŝ U Ŭ/;$"=join"|",keys%k;s/($")x/$k{$1}/g ``` [Try it online!](https://tio.run/##DcPBCoIwAAbgV/kRhYJsevAk0sFDEXSKHkBK1C02a44W1b3eQW91q1u9wXytVh98db7fRtZ6LNkdyBrmhgKmQwnzAIX5QKLvoNC/kMJcMYVpMYO5Yw7zxhJ9ixX6J4ldJ6Gi4s7ZGbH8KD0WSzJwnaEmLju54YUU1qZaQerqP2syCZY1gnJkSqNUfCPo5CvqphJcWn8RjYMwsH79Aw "Perl 5 – Try It Online") [Answer] # JavaScript (ES6), 92 bytes ``` s=>[..."cghjsuCGHJSU"].reduce((a,v,i)=>a.split(v+"x").join("ĉĝĥĵŝŭĈĜĤĴŜŬ"[i]),s) ``` [Try it online!](https://tio.run/##dY2xTsMwFEX3foXlyVGLs4Nahg4g1qpTqZBx3NShxCG2gxFib/6h2ejWbvAH9nelyQBqE/lNT@@ee15CCiJpzjN1lYqI1atxLceTBcYY0nidSD29u3@YzeES5yzSlCFERsWIB@MJwTLbcIWKITQwwIngKYK2tJXd219XuaPd2p39tj9u5w5wwZfBSAZ1GEKeZlpBcA2g0KpdB2H4dD4DKlIpNgxvRIzgI4RgCFYIxoYDJhWRoCD5K2mvbRgEYdjKbHUZeyxTo4FsTNKQln0hSiQpINqAtU4jkdz2vFsNXON21UXBHf8Lnk9zQ03z5ZlGaG1mJmCr@PPrpqt3B1s26paye7f7ozzOt3eWqw/NRdb1nCWeLuhWgI/sgj7OdEHjJWkPpX6277Wlj6amR9vSwPoE "JavaScript (Node.js) – Try It Online") Used split-join method recommended in [here](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) to reduce byte counts because the `new RegExp(/*blah*/)` constructor took up too many bytes. Comparison: ``` Original: a.replace(new RegExp(v+"x", "g"), "ĉĝĥĵŝŭĈĜĤĴŜŬ"[i]) New : a.split(v+"x").join("ĉĝĥĵŝŭĈĜĤĴŜŬ"[i]) ``` [Shorter, combining accent approach (63 bytes), but with some artifacts visible.](https://tio.run/##dY0/TsMwGEf3nuKTxZCIUouVqjBwBMQECBnH@Ucah9guH0IsTETiCHRkg1vEG3dK44EqTWRPlt/7PedswxSvs0qflDISXbzq1OpcLWpRFYyLgAY3PElzdRciTbI5gb/3o1MSDrjZk09Hlh2lJCsrowmcAZFGu@uM0vvhmXFZKlmIRSGTgNwSAscQByTBDITSTMGG1WvmXh0MQ0pdrN0eYk/lEg2ovqSQOfeRaZmXwAxCaspI5heT7ocB27ft9mBgf/cDz0/XyLH/5YFHQYpXGIo4eX1bjvP2p236tLPab/v1b3maT8@i1i8mk9W4MyCeLYwn4DPHos/DsYhek09U7nen3bbx2Rwndtsg6XY) ``` s=>s.replace(/([cghjs])x/gi," ̂$1").replace(/(u)x/gi," ̌$1"); ``` Footnote: I'm claiming my answer 92 bytes because the 63-byte solution has artifacts that may affect the output. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 57 bytes Anonymous tacit function. Usages: 1. Prefix function to string. This transliterates the string. 2. Prefix function to list of strings. This transliterates the strings. 3. Infix function with input file tie number as right argument and output file tie number as left argument. This populates the output file with the transliterated content of the input file. `('cghjsuCGHJSU',¨'x')⎕R(,¨'ĉĝĥĵŝŭĈĜĤĴŜŬ')` `(`…`)⎕R(`…`)` PCRE **R**eplace `'cghjsuCGHJSU'` these letters `,¨'x'` each followed by an x  … with… `,¨'ĉĝĥĵŝŭĈĜĤĴŜŬ'` each of these letters as strings [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X0M9OT0jq7jU2d3DKzhUXefQCvUKdc1HfVODNEDsI51H5h5ZemTr0blH1x7pODLnyJIjW47OObpGXfP//zQF9fSKTIXU4pLEYoWyxKLcRHUuoJhzRalCMVC8uCIRJJGdWJKflaeQWFqhkFGal5KfZQ9WFVqRXAFUkZScopFREVyhmZqWXl1rDZZSKixPLSqpLM3ML1CCCChAaShVAaOT4QyYUHIFkAUA "APL (Dyalog Unicode) – Try It Online") [Answer] # [J](http://jsoftware.com/), 64 63 bytes ``` rplc((_2]\'ĉĝĥĵŝŭĈĜĤĴŜŬ');~"1'cghjsuCGHJSU',.'x')"0 ``` How it works: With `_2]\` I rearrange the string 'ĉĝĥĵŝŭĈĜĤĴŜŬ' into a 12-row column in order to fit the shape of the other string. `,.` adds 'x' to each character of the 'cghjsuCGHJSU' string and makes a 12 row by 2 columns array `;~"1'` makes a list of boxed pairs of the above, "1 - rank 1 - apply to each row. ``` ┌──┬──┐ │cx│ĉ │ ├──┼──┤ │gx│ĝ │ ├──┼──┤ │hx│ĥ │ ├──┼──┤ │jx│ĵ │ ├──┼──┤ │sx│ŝ │ ├──┼──┤ │ux│ŭ │ ├──┼──┤ │Cx│Ĉ │ ├──┼──┤ │Gx│Ĝ │ ├──┼──┤ │Hx│Ĥ │ ├──┼──┤ │Jx│Ĵ │ ├──┼──┤ │Sx│Ŝ │ ├──┼──┤ │Ux│Ŭ │ └──┴──┘ ``` `rplc` uses these boxed items to replace each occurrence of the left boxed item from a pair with the right one. [Try it online!](https://tio.run/##VYq9joJAFEZ7nuKG5kJiCFpqjAWFxtbYacw4MiD@oAyj1xi3Xt9BO7dbO32D4bkQGzN25/vOSUoh2x740AS/zDZL7jiTxniE@qyv@k8/i2tx17/6om/6UVyKf3RbP3YdeRQnUgXdXn8wxJqHhK7tl65le4Ci7SHU4NQEIS0r5HEKAjCiOYQyZxJ2LFsxhI8JSIGsrCT21guWp8kamCKI1XqWJh2jHRKnqpvymRPTgNxQRMdTywi2@zDLD2qebowTDDaQTOZfw1ScqlW@AA "J – Try It Online") [Answer] # [Befunge](https://esolangs.org/wiki/Befunge), 2x48 +1 = 99 bytes ``` >~:1+!#@_:"x"-v>$ 11p0"cghjsuCGHJSU"1\ >\31p11g-v ^ # #, : ++$\ _^#1"x"0*4!-"u"g11*"ʊ"!\_^#!:\*g13< ``` [Try It Out](http://www.quirkster.com/iano/js/befunge.html) (TIO is super weird about Befunge and I couldn't get any of my solutions to work on it) ### How it works ``` >~:1+!@_ ``` Gets input and checks if it's the end. End program if it is. ``` "x"-v> ^ # #, : ++$\ _^ ``` Checks if the character is an "x". If not, keep a copy of the character and print it. ``` >$ 11p0"cghjsuCGHJSU"1\ ``` Store the last character at (1,1). Puts all the characters to check into the stack. ``` >\31p11g-v _^#!:\*g13< ``` Compare the last character against all the values in the stack. ``` 1"x"0*4!-"u"g11*"ʊ"!\ ``` Multiply the check (0 or 1) by ʊ (unicode value 650). Check whether the character was a u (for the breve) and adds 4 to the stack if so. Finally, add the ascii value of x (100) as well. The total adds up to the correct accent if needed or just an "x" if not. ``` >~:1+!#@_ ^ # #, : ++$\ _^# ``` Add all the values in the stack together, print it and keep a duplicate. Go back up for the next input. [Answer] # [R](https://www.r-project.org/), ~~75~~ 70 bytes ``` function(s)gsub('([cghjs])x','\\1\U302',gsub('(u)x','\\1\U306',s,T),T) ``` [Try it online!](https://tio.run/##TYrLCsIwEEX3fkVwkwSy8AFuRFz4CdqVdZGmTdqKiXYSHRG/PUZSQRjmzpxzh6g3UQerfOcsA24gVIyyozJtDyeOVNCynJfFcragYpThH6@oAHHgaaJmU4MdacBLIHc5XOSUTxLcYSCQBKD8mrP0rrdEBiRtsLXrt7lWoMJUqVTNWtwjb7R5vdfZ3R7N4J@hc9f8kxx54xjqlyNQmI74AQ "R – Try It Online") -5 bytes thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) ### Explanation * `gsub('(u)x','\\1\U306',s,T)`: replace in `s` every occurrence of an uppercase or lowercase "u" (by using `ignore.case=TRUE` via the fourth argument `T`) followed by an "x" the "u" followed by the unicode for a breve * `gsub('([cghjs])x','\\1\U302',gsub('(u)x','\\1\U306',s,T),T)`: take the result of that and replace every occurrence of an uppercase or lowercase (by using `ignore.case=TRUE` via the fourth argument `T`) "c", "g", "h", "j", or "s" followed by an "x" with the letter followed by the unicode for a circumflex [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 25 bytes Combining diacritics edition. ``` ux ([cghjs])x ̆& ̂\1 ``` `i` flag [Try it online!](https://tio.run/##HYk7DsIwEER7n2LlyilTU1BwBERFKBbb@IOIiT@wCNFQcDruZGykmafRm6WgirWKMhATe2msT4c24fuZxsb3NNZqyIFOGRPcMF6QbahAai4RdnnGHPwMWAhsmVXwa7YjSe09SiUsbWnQJ/N8rRhf7jrmR3HhyhmH1hbqlX/0KYl4dT8 "QuadR – Try It Online") *Replace…* ``` (u)x u followed by x and ([cghjs])x any of these letters followed by x … ̆\1 by a breve followed by the first group (the u) and ̂\1 a circumflex followed by the first group (the letter) ``` *case **i**nsensitively* Equivalent to the following Dyalog APL code: ``` '(u)x' '([cghjs])x'⎕R' ̆\1' ' ̂\1' ``` [Answer] # C, ~~145~~ 144 bytes Another C approach. Return by overwriting the input, using the fact that circumflex / breve are 2 bytes. *-1 bytes thanks to [Steadybox](https://codegolf.stackexchange.com/users/61405/steadybox).* ``` i,t;f(char*s){for(t=1;*s;s++)if(*s^'x')for(i=12,t=1;i--;)t="cghjsuCGHJSU"[i]-*s?t:i*2;else t^1&&memcpy(s-1,"ĉĝĥĵŝŭĈĜĤĴŜŬ"+t,2),t=1;} ``` [Try it online!](https://tio.run/##VY49TsNAEIV7n2LlItl1bCl2ySpKkQJEG6WKEmlZ/LMB28Ezho0i93CHpIMOOrjB@lzGNinMVO/N9@ZppBdL2TTKRR5RmYjCAXaM8oLizOcOcJhMmIqoA9uxHrMOqJkfuB1VnscZzmwZJzsoF9c3t8uVvVYbz4E5Xikn4OEjhAS3/miUhqncHyh4vmubN3M2H@anPtdf5tWczLv5rk/1pz1BN2B9ddXIv2cIMHK0SDudJbgOptMNJ4BFV4duy3mPI4oXtS8RelNZlsqQpEJllFmXFmrHWpEQUAB5FkUq7MtZSxa6JNBS0KLDDwLzXUZEqUlSZvf5bj7IrrTUbe5O3tNELzULo/hY8UHg6SUs8FCqfD9YkoEeSD3U8p8ZIql7VzW/ "C (gcc) – Try It Online") [Answer] # Mathematica, 81 bytes or 57 bytes `StringReplace[RemoveDiacritics@#<>"x"->#&/@Characters@"ĉĝĥĵŝŭĈĜĤĴŜŬ"]` It applies a replacement rule where the letter without the hat together with an "x" is replaced by the letter. Here is an alternative using the added accents character: `StringReplace[{"ux"->"ŭ","Ux"->"Ŭ",c_~~"x":>c<>"̂"}]` [Answer] # [Perl 5](https://www.perl.org), 49 + 2 (`-p -C`) = ~~61~~ 51 bytes ``` s/[CGHJScghjs]\Kx/\x{0302}/g;s/[Uu]\Kx/\x{0306}/g ``` [Try it online!](https://tio.run/##TYmxDoIwFEX3fsUbdTAQjS4MDgwaHQmTONRSS1Fppa0@Q/h162MzOTe5OcfK/r6O0SWnfLc/FEI1rTtXR0wqHNJVuhwTlVEsw5/ckIxRoQbpPHfw4v2DA8sxgCPpkE/2xr1pO@ABoQldbdotsBIFUr6IetZggXN5VcOYAXu@Ze8/QRsLDAiGhJhGRyDC11ivTefiwv4A "Perl 5 – Try It Online") *Saved 10 bytes thanks to [Nahuel Fouilleul](https://codegolf.stackexchange.com/users/70745/nahuel-fouilleul)* [Answer] # sed, 40 bytes (38 chars) ``` s/([cghjsCGHJS])x/\1̂/g s/(u|U)x/\1̆/g ``` [Try it online!](https://tio.run/##VYy9bsIwEMd3P8XJEwwoYqUDA0JFXRET7WCc1AlVk4Dj9qqWhQGRdyhjN/oW9tZnqrk4rYDpfv@v00ncU7nxXkeduVTpUo9uJ3fThy5G9/2fbaQYBeZj1updpLznCjNIdCU0vIj1s@AwAG4P1x7jIzSgqalRNPaTqIplDsIgpCaPiYftcG/A0dgdrmru@1xjfIYS6c9Cxp0Up9hNHtX75ibs3dHWtG0i@@U@/yPGV6/JunozWVGG3oVkHIIFRAHoYgBsSLYoA//5tiYlsVW2Rv5blFVW5Nr3xic "sed – Try It Online") I believe this is different enough from [iBug's answer](https://codegolf.stackexchange.com/a/149338/44694). [Answer] # [Lexurgy](https://www.lexurgy.com/sc), ~~60~~ 48 bytes ``` a: x=>̂/{c,g,h,j,s,C,G,H,J,S} _ x=>̆/{U,u} _ ``` Replaces `x` with the correct combining diacritic based on the preceding character. * -12 bytes for removing the `Class`. [Answer] # [CJam](https://sourceforge.net/p/cjam), 51 bytes ``` q"ĉĝĥĵŝŭĈĜĤĴŜŬ""cghjsuCGHJSU".{'x+@\/*} ``` [Try it online!](https://tio.run/##AT4Awf9jamFt//9xIsSJxJ3EpcS1xZ3FrcSIxJzEpMS0xZzFrCIiY2doanN1Q0dISlNVIi57J3grQFwvKn3//2N4eA "CJam – Try It Online") Explanation: ``` q Read input "ĉĝĥĵŝŭĈĜĤĴŜŬ" String literal "cghjsuCGHJSU" Another string literal .{ Iterate over the strings in parallel 'x+ Add an 'x to the normal character @ Rotate to bring the input to the top of stack \ Swap to bring the "cx" to the top / Split the input on instances of "cx" * Join the input on instances of the accented character } ``` [Answer] ## PowerShell, 58 bytes It's 54 characters and saving it in PowerShell ISE makes it [UTF-8 + BOM](https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8) for 58 bytes. It doesn't render as nicely in a browser: ``` $args-replace'(?<=u)x','̆'-replace'(?<=[cghjs])x','̂' ``` regex replaces the x with the combining Unicode characters from @user202729's comment. e.g. ``` PS C:\> .\eo.ps1 "Cxu vi sxatas la cxapelliterojn? Mi ankaux." Ĉu vi ŝatas la ĉapelliterojn? Mi ankaŭ. ``` [Answer] # Clojure, ~~126~~ 115 bytes -11 bytes by changing the replacement map to a partition of a string. ``` #(reduce(fn[a[f r]](clojure.string/replace a(str f\x)(str r)))%(partition 2"cĉgĝhĥjĵsŝuŭCĈGĜHĤJĴSŜUŬ")) ``` A reduction over a map of replacements to look for, and what to replace them with. Still working on a way to compress the replacement map. ``` (defn translate [^String esperanto] (reduce (fn [acc [f r]] (clojure.string/replace acc ; Replace the translation so far by (str f \x) ; adding a x after each character, search for it in the string, (str r))) ; and replace it with a stringified accented char esperanto ; Before the reduction happens, the accumulator is the original string ; A list of [char-to-find what-to-replace-with] pairs (partition 2"cĉgĝhĥjĵsŝuŭCĈGĜHĤJĴSŜUŬ"))))) ``` [Answer] # JavaScript (ES6), 91 bytes ``` (i,s='cĉgĝhĥjĵsŝuŭCĈGĜHĤJĴSŜUŬ')=>i.replace(/.x/g,m=>s[1+s.search(m[0])||s]||m) ``` [Try it online!](https://tio.run/##bZK7bsIwFIb3PMVRlyRqGtq1yHRAVauuiAkxuMa5UHJpnFBXhJ28A9nKBlv7BvZzpUkoIiHdjv19/@/BZ46XmJHIDeMbP5jRwkKF5hoMqURktsgdsZuLHybzRB6GYvMkts/i60V8j@R2LPeqjgauGdFwgQnVeibv2YaHBmxyd81MRnFEHM2b3E71NGXTNPX0ggQ@i4FgRhkgmCgAK3D9MInv4crmLlAWYwZLHHn4yoAgiY9I5G0Ea6MVHfIEWBlnHFfSG46DuQ844eAk/qycH1ptmwRk2Sjzli0PZ/vygTEnvCx/JTPN4SOuU8terfvNUrkXWVlYGWIntyfjsuj9g0bxZ@IGYTPcuL0MQNODDm7SDuRNyruYtDj5R2g3iKyjEN5SRFY9o0z7SvXTwYKai8DW1NqG9M8rBw/HxKFM1ZV6F0wriB5xuS0EDVbNJDHrqKGmqmGdTnp9JOaxDSF0JvpaL34B) [Answer] # [Scala](http://www.scala-lang.org/), 110 bytes Boring regex solution: ``` def?(s:String)="(.)x".r.replaceAllIn(s,m=>m.group(0)(0)+(if(m.group(0)(0).toUpper=='U')"\u0306"else"\u0302")) ``` Old scala solution (116 bytes) ``` def?(s:String)=s.foldLeft("")((r,c)=>if(c=='x')r.init+r.last+(if(r.last.toUpper=='U')"\u0306"else"\u0302")else r+c) ``` Ungolfed ``` def?(s:String)= s.foldLeft("")((r,c)=> // 'Fold' string with empty string as first result if(c=='x') // If current character is x r.init+ // Take the every character from result but the last r.last+ // The last character from result and add (if(r.last.toUpper=='U') "\u0306" // combining breve if 'u' or 'U' else"\u0302") // combining circumflex in any other case else r+c // Otherwise return result + character ) ``` [Answer] # JavaScript, 35 chars, 36 bytes ``` s=>s.replace(/([cghjsu])x/gi,"$1̂") ``` [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), ~~57~~ 50 bytes ``` {S:g:i/(<[cghjsu]>)x/{$0~chr 770+4*("u"eq$0.lc)}/} ``` [Try it online!](https://tio.run/##PcrNCoJAFEDhfU9xGSS1IF1Egvaz6BGkVbS4jeOMplaOE1fEXn0yiHYHvvMQbbWxdT/Pd3ZIYxkXgbc9c6lKbS57n4LBCd9ctRBF4XK98Jhh4umEq4r7YzBajT3kwCQVIHSHGl7Y1siS2Q@OZEBPqAm/esPuXjaAhkCZJpv68H/dE3GavivPPEUp@SKXw5i49gM "Perl 6 – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 71 bytes ``` for 2 3 (`fold -1<<<${a=cĉgĝhĥjĵsŝuŭ}${a:u}`)1=${1//$2x/$3} <<<$1 ``` [Try it online!](https://tio.run/##qyrO@F@cWqKgm6@QW5pTkplUWZL6Py2/SMFIwVhBIyEtPydFQdfQxsZGpTrRNvlIZ/qRuRlHlmYd2Vp8dG7p0bW1QGGr0toETUNblWpDfX0Vowp9FeNaLpAGw////ztXlCoUV2QCcWJJYrFCdmJJflaeQmJphUJGaV4KkG0PAA "Zsh – Try It Online") [Answer] # sed, 108 bytes ``` s/cx/ĉ/g s/gx/ĝ/g s/hx/ĥ/g s/jx/ĵ/g s/sx/ŝ/g s/ux/ŭ/g s/Cx/Ĉ/g s/Gx/Ĝ/g s/Hx/Ĥ/g s/Jx/Ĵ/g s/Sx/Ŝ/g s/Ux/Ŭ/g ``` ]
[Question] [ In the game of sudoku, many players like to "pencil in" possible numbers that can go in each square: [![Sudoku row](https://i.stack.imgur.com/6RQ7U.png)](https://i.stack.imgur.com/6RQ7U.png) The above row can be represented as an array: ``` [[1,2,9], [6], [5], [7], [1,2,9], [1,2,9], [3], [1,2,4], [8]] ``` Now, notice that there is only 1 place where a `4` can go. This effectively lets us simplify the above list to: ``` [[1,2,9], [6], [5], [7], [1,2,9], [1,2,9], [3], [4], [8]] ``` **The goal of this challenge is to take a list of possible numbers in a permutation, and deduce which possibilities can be eliminated**. As another example, lets say you have the following array of possibilities: ``` [[0,1,3], [0,2,3], [1,2], [1,2]] ``` The last two places *must* be filled with 1 and 2. Therefore, we can remove those possibilities from the first two elements in the array: ``` [[0,3], [0,3], [1,2], [1,2]] ``` As another example: ``` [[0,1,2,3], [0,2], [0,2], [0,2]] ``` Its *impossible* to construct a permutation from the above possibilities, as there's only 1 location for both `1` and `3`, and you would want to return an empty array. **You need to input a list of possibilities and output the remaining possibilities after the maximum number of possibilities have been eliminated.** * If a particular array is impossible, you either need to return an empty array, or an array where one of the subarrays is empty. * You may assume that the array will be well-formed, and have at least 1 element. * Given an array of size `N`, you can assume the numbers in the subarray will always be in the range `[0:N)`, and that `N <= 10` * You may not assume that every number from `0` to `N-1` will be present * You may assume that numbers within a single subarray are unique. * If a subarray contains only a single possibility, you can either represent the possibility in an array or by itself. `[[1],[2],[0]]`, `[1,2,0]`, `[[1,2],0,[1,2]]` are all valid. * You may accept the array either in a reasonable string format or in list/array format. * Subarrays can be in any order. * Instead of dealing with ragged arrays, you can pad empty places with `-1`. # Test cases ``` [[0]] -> [[0]] [[1],[0]] -> [[1],[0]] [[1],[1]] -> [] [[1],[0,1]] -> [[1],[0]] [[0,1,2],[1,2],[1,2]] -> [[0],[1,2],[1,2]] [[0,1],[1,2],[0,2]] -> [[0,1],[1,2],[0,2]] [[2,1],[1,2],[1,2]] -> [] [[0,3],[2,1],[3,0],[3,2]] -> [[0,3],[1],[0,3],[2]] [[0,1],[0,1],[2,3],[2,3,0]] -> [[0,1],[0,1],[2,3],[2,3]] [[0,1],[0,3],[3,2],[0]] -> [[1],[3],[2],[0]] [[3,5,2],[0,2,4],[4,0],[0,1,3,5],[2,1],[2,4]] -> [[3,5],[0,2,4],[4,0],[3,5],[1],[2,4]] [[6,9,8,4],[4,5],[5,3,6],[3,8,6,1,4],[3,1,9,6],[3,7,0,2,4,5],[9,5,6,8],[6,5,8,1,3,7],[8],[8,0,6,2,5,6,3]] -> [[6,9,4],[4,5],[5,3,6],[3,6,1,4],[3,1,9,6],[0,2],[9,5,6],[7],[8],[0,2]] [[3,5,0],[5,7],[5,1,2],[1,3,0],[5,3],[5,0],[5,3,7,8,0,6],[7,5,0,1,8],[1,0,8],[0,6]] -> [] [[9,0,2,3,7],[0,7,6,5],[6,9,4,7],[9,1,2,3,0,5],[2,8,5,7,4,6],[6,5,7,1],[5,9,4],[5,9,3,8,1],[5,0,6,4],[0,7,2,1,3,4,8]] -> [[9,0,2,3,7],[0,7,6,5],[6,9,4,7],[9,1,2,3,0,5],[2,8,5,7,4,6],[6,5,7,1],[5,9,4],[5,9,3,8,1],[5,0,6,4],[0,7,2,1,3,4,8]] [[2,6,0],[0,4,3],[0,6,2],[0,7],[0,9,2,3,6,1,4],[1,7,2],[2,7,8],[8,6,7],[6,5,2,8,0],[5,8,1,4]] -> [[2,6,0],[3],[0,6,2],[0,7],[9],[1],[2,7,8],[8,6,7],[5],[4]] [[8],[8,0,6,5,7,2,4,1],[8,6,9,3,5,0,7],[3,9,1,0],[9],[9,2,6],[2,8,3],[3,1,6,8,2],[6],[6,4,5,3,0,7]] -> [[8],[5,7,4],[5,7],[0],[9],[2],[3],[1],[6],[4,5,7]] [[8,1,0],[5,8,7,6,2,0],[6,8,2],[2,4,0,9],[4,1,7,3,6,8],[8,1],[8,0,3],[0,8,2],[0,8,3],[1,8,0]] -> [] ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so make your answers as short as possible! [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 21 bytes ``` :1fz:da|,[] :2a#d :Am ``` [Try it online!](http://brachylog.tryitonline.net/#code=OjFmejpkYXwsW10KOjJhI2QKOkFt&input=W1s4XTpbODowOjY6NTo3OjI6NDoxXTpbODo2Ojk6Mzo1OjA6N106WzM6OToxOjBdOls5XTpbOToyOjZdOlsyOjg6M106WzM6MTo2Ojg6Ml06WzZdOls2OjQ6NTozOjA6N11d&args=Wg&debug=on) [Try it online!](http://brachylog.tryitonline.net/#code=OjFmejpkYXwsW10KOjJhI2QKOkFt&input=W1s4OjE6MF06WzU6ODo3OjY6MjowXTpbNjo4OjJdOlsyOjQ6MDo5XTpbNDoxOjc6Mzo2OjhdOls4OjFdOls4OjA6M106WzA6ODoyXTpbMDo4OjNdOlsxOjg6MF1d&args=Wg&debug=on) ## Predicate 0 (main predicate) ``` :1fz:da|,[] :1f Find all solutions of Predicate 1 using Input as Input. z Transpose :da Deduplicate each. |,[] If there is no solution, return [] instead. ``` ## Predicate 1 (auxiliary predicate 1) ``` :2a#d :2a Each element of Output satisfies Predicate 2 with each element of Input as Input #d Each element is different ``` ## Predicate 2 (auxiliary predicate 2) ``` :Am Output is member of Input ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 10 bytes ``` Œp⁼Q$ÐfZQ€ ``` [Try it online!](http://jelly.tryitonline.net/#code=xZJw4oG8USTDkGZaUeKCrA&input=&args=W1s4XSxbOCwwLDYsNSw3LDIsNCwxXSxbOCw2LDksMyw1LDAsN10sWzMsOSwxLDBdLFs5XSxbOSwyLDZdLFsyLDgsM10sWzMsMSw2LDgsMl0sWzZdLFs2LDQsNSwzLDAsN11d) ``` Œp⁼Q$ÐfZQ€ Main chain, argument: z Œp Cartesian product ⁼Q$Ðf Filter for those that remain unchanged when uniquified Z Transpose Q€ Uniquify each subarray ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 11 bytes ``` {MC{I#.nM*F ``` [Try it online!](http://pyth.herokuapp.com/?code=%7BMC%7BI%23.nM%2aF&input=%5B%5B8%5D%2C%5B8%2C0%2C6%2C5%2C7%2C2%2C4%2C1%5D%2C%5B8%2C6%2C9%2C3%2C5%2C0%2C7%5D%2C%5B3%2C9%2C1%2C0%5D%2C%5B9%5D%2C%5B9%2C2%2C6%5D%2C%5B2%2C8%2C3%5D%2C%5B3%2C1%2C6%2C8%2C2%5D%2C%5B6%5D%2C%5B6%2C4%2C5%2C3%2C0%2C7%5D%5D&debug=0) ``` {MC{I#.nM*F *F reduce by Cartesian product produces nested arrays .nM flatten each {I# filter for invariant under deduplication C transpose {M deduplicate each ``` [Answer] ## Haskell, 100 bytes ``` import Data.List p z=map nub$transpose$filter(and.(flip$zipWith elem)z)$permutations[0..length z-1] ``` [Answer] # [Actually](http://github.com/Mego/Seriously), 27 bytes ``` Rd╗R`╜∙"♂i"£M╗`MX╜`;╔=`░┬♂╔ ``` [Try it online!](http://actually.tryitonline.net/#code=UmTilZdSYOKVnOKImSLimYJpIsKjTeKVl2BNWOKVnGA74pWUPWDilpHilKzimYLilZQ&input=W1szLDUsMl0sWzAsMiw0XSxbNCwwXSxbMCwxLDMsNV0sWzIsMV0sWzIsNF1d) [Answer] # Python 3, ~~101~~ 99 bytes *Thanks to @TLW for -2 bytes* ``` from itertools import* lambda x:list(map(set,zip(*[i for i in product(*x)if len(i)==len(set(i))]))) ``` An anonymous function that takes input via argument of a list of lists and returns a list of sets. **How it works** ``` from itertools import* Import Python's library for iterator generation lambda x Anonymous function with input possibilities x as a list of lists ...for i in product(*x)... For i in the Cartesian product of x, ie all candidate arrangements: [...if len(i)==len(set(i))] Filter into list by non-duplicity (set removes duplicates, so there are no duplicates if the length of i is the same as the length of the set of the elements of i) zip(*...) Unpack and take the transpose, leaving the modified possibilities with duplicates map(set,...) Remove duplicates :list(...) Return the modified possibilities as a list of sets ``` [Try it on Ideone](http://ideone.com/RS6smt) [Answer] # Mathematica, 46 bytes ``` Union/@Thread@Select[Tuples@#,DuplicateFreeQ]& ``` [Answer] # PHP, ~~245~~ 231 bytes ~~131~~ 117 for the cartesian product function, 114 for the other stuff ``` function c($a){if ($a){if($u=array_pop($a))foreach(c($a)as$p)foreach($u as$v)yield $p+[count($p)=>$v];}else yield[];} function p($a){foreach(c($a)as$i)if(max(array_count_values($i))<2)foreach($i as$k=>$v)$r[$k][$v]=$v;return$r?:[];} ``` I ran into memory issues on some of the test cases, with a recursive function for the cartesian product. Worked better with [this generator class](https://gist.github.com/martinezdelariva/621553a2b8bef8cd6f2b/) and `function c($a){$b=[];foreach($a as$i)$b[]=new \ArrayIterator($i);return new CartesianProductIterator($b);}`. But [my generator](https://stackoverflow.com/questions/6311779/finding-cartesian-product-with-php-associative-arrays/39174062#39174062) is shorter and does the same job. The larger examples, however, result in an Internal Server Error (both with the iterator and the generator) after a while on my machine. Currently no time to check the server logs, unfortunately. ]
[Question] [ Related: [Program my microwave oven](https://codegolf.stackexchange.com/q/8791/43319). Inspired by [Generate lazy microwave input](https://codegolf.stackexchange.com/q/73914/43319). The lazy value of the non-negative integer *N* is the smallest of the integers that are closest to *N* while all their digits are identical. Return (by any means) the lazy value of a given (by any means) *N*. *N* ≤ ~~the largest integer that your language represents in non-exponent form by default.~~ 1000000 (A lot of interesting solutions are lost because of this too-high requirement.) ## Test cases: ``` 0 → 0 8 → 8 9 → 9 10 → 9 16 → 11 17 → 22 27 → 22 28 → 33 100 → 99 105 → 99 106 → 111 610 → 555 611 → 666 7221 → 6666 7222 → 7777 ``` --- The colleague in question proved that there will be no ties: Except for 9/11, 99/111, etc. for which one is shorter than the other, two consecutive valid answers are always an odd distance apart, so no integer can be exactly equidistant from them. [Answer] ## JavaScript (ES6), 31 bytes ``` n=>~-(n*9+4).toPrecision(1)/9|0 ``` Directly computes the lazy value for each `n`. Edit: Only works up to 277777778 due to the limitations of JavaScript's integer type. Alternative versions: ``` n=>((n*9+4).toPrecision(1)-1)/9>>>0 ``` 35 bytes, works up to 16666666667. ``` n=>((n=(n*9+4).toPrecision(1))-n[0])/9 ``` 38 bytes, works up to 944444444444443. But that's still some way short of 253 which is 9007199254740992. [Answer] # Jelly, 16 bytes ``` ḤRµDIASµÐḟµạ³ỤḢị ``` [Try it online!](http://jelly.tryitonline.net/#code=4bikUsK1RElBU8K1w5DhuJ_CteG6ocKz4buk4bii4buL&input=&args=NjEx) ### How it works ``` ḤRµDIASµÐḟµạ³ỤḢị Main link. Input: n Ḥ Compute 2n. R Yield [1, ..., 2n] or [0]. µ Begin a new, monadic chain. Argument: R (range) D Convert to base 10. I Compute all differences of consecutive decimal digits. A Take the absolute values of the differences. S Sum the absolute values. µÐḟ Filter-false by the chain to the left. µ Begin a new, monadic chain. Argument: L (lazy integers) ạ³ Take the absolute difference of each lazy integer and n (input). Ụ Grade up; sort the indices of L by the absolute differences. This is stable, so ties are broken by earlier occurrence and, therefore, lower value. Ḣ Head; retrieve the first index, corresponding to the lowest absolute difference. ị Retrieve the item of L at that index. ``` [Answer] # Oracle SQL 11.2, 200 bytes ``` WITH v(i)AS(SELECT 0 FROM DUAL UNION ALL SELECT DECODE(SIGN(i),0,-1,-1,-i,-i-1)FROM v WHERE LENGTH(REGEXP_REPLACE(:1+i,'([0-9])\1+','\1'))>1)SELECT:1+MIN(i)KEEP(DENSE_RANK LAST ORDER BY rownum)FROM v; ``` Un-golfed ``` WITH v(i) AS ( SELECT 0 FROM DUAL -- Starts with 0 UNION ALL SELECT DECODE(SIGN(i),0,-1,-1,-i,-i-1) -- Increments i, alternating between negatives and positives FROM v WHERE LENGTH(REGEXP_REPLACE(:1+i,'([0-9])\1+','\1'))>1 -- Stop when the numbers is composed of only one digit ) SELECT :1+MIN(i)KEEP(DENSE_RANK LAST ORDER BY rownum) FROM v; ``` [Answer] # Pyth - 26 bytes ~~This answer doesn't always return the smallest value in a tie, but that isn't in the specs, so awaiting clarification~~ fixed for 3 bytes. ``` hSh.g.a-kQsmsM*RdjkUTtBl`Q ``` [Test Suite](http://pyth.herokuapp.com/?code=hSh.g.a-kQsmsM%2aRdjkUTtBl%60Q&test_suite=1&test_suite_input=107%0A105%0A104%0A7222%0A7221%0A8&debug=0). [Answer] # Pyth, 16 bytes ``` haDQsM*M*`MTSl`Q ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=haDQsM*M*%60MTSl%60Q&input=8&test_suite_input=8%0A9%0A10%0A16%0A17%0A27%0A28%0A100%0A105%0A106%0A610%0A611%0A7221%0A7222&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=haDQsM*M*%60MTSl%60Q&input=8&test_suite=1&test_suite_input=8%0A9%0A10%0A16%0A17%0A27%0A28%0A100%0A105%0A106%0A610%0A611%0A7221%0A7222&debug=0) ### Explanation: ``` haDQsM*M*`MTSl`Q implicit: Q = input number `Q convert Q to a string l take the length S create the list [1, 2, ..., len(str(Q))] `MT create the list ["0", "1", "2", "3", ..., "9"] * create every combination of these two lists: [[1, "0"], [1, "1"], [1, "2"], ..., [len(str(Q)), "9"]] *M repeat the second char of each pair according to the number: ["0", "1", "2", ..., "9...9"] sM convert each string to a number [0, 1, 2, ..., 9...9] D order these numbers by: a Q their absolute difference with Q h print the first one ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 25 bytes ``` 2*:"@Vt!=?@]]N$vtG-|4#X<) ``` Uses brute force, so it may take a while for large numbers. [**Try it online!**](http://matl.tryitonline.net/#code=Mio6IkBWdCE9P0BdXU4kdnRHLXw0I1g8KQ&input=MTA2) ``` 2*: % range [1,2,...,2*N], where is input " % for each number in that range @V % push that number, convert to string t!= % test all pair-wise combinations of digits for equality ? % if they are all equal @ % push number: it's a valid candidate ] % end if ] % end for each N$v % column array of all stack contents, that is, all candidate numbers t % duplicate G-| % absolute difference of each candidate with respect to input 4#X< % arg min ) % index into candidate array to obtain the minimizer. Implicitly display ``` [Answer] # Perl, 32 Based on the beautiful JavaScript solution by Neil. ``` $_=0|1/9*~-sprintf"%.e",$_*9+4.1 ``` Starts to fail at `5e15` [Answer] # Mathematica, 122 bytes ``` f@x_:=Last@Sort[Flatten@Table[y*z,{y,1,9},{z,{FromDigits@Table[1,10~Log~x+1-Log[10,1055555]~Mod~1]}}],Abs[x-#]>Abs[x-#2]&] ``` Function named x. [Answer] # JavaScript (ES6), 59 bytes ``` n=>eval(`for(i=a=0;i<=n;a=i%10?a:++i)p=i,i+=a;n-p>i-n?i:p`) ``` ### Recursive Solution (56 bytes) This is a bit shorter but does not work for `n > 1111111110` because the maximum call stack size is exceeded, so it is technically invalid. ``` f=(n,p,a,i=0)=>n<i?n-p>i-n?i:p:f(n,i,(i-=~a)%10?a:i++,i) ``` ## Explanation Iterates through every lazy number until it gets to the first which is greater than `n`, then compares `n` to this and the previous number to determine the result. ``` var solution = n=> eval(` // eval enables for loop without {} or return for( i=a=0; // initialise i and a to 0 i<=n; // loop until i > n, '<=' saves having to declare p above a=i%10?a:++i // a = amount to increment i each iteration, if i % 10 == 0 (eg. ) // 99 + 11 = 110), increment i and set a to i (both become 111) p=i, // set p before incrementing i i+=a; // add the increment amount to i n-p>i-n?i:p // return the closer value of i or p `) ``` ``` N = <input type="number" oninput="R.textContent=solution(+this.value)"><pre id="R"></pre> ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 18 bytes ``` 9*U+4 rApUs l¹/9|0 ``` [Try it online!](https://tio.run/nexus/japt#@2@pFaptolDkWBBarJBzaKe@ZY3B///mRkZGAA "Japt – TIO Nexus") Based on [Neil's technique](https://codegolf.stackexchange.com/a/73944/61613) Non-competing [solution](http://ethproductions.github.io/japt/?v=1.4.3&code=KjkrNCBoIC85fDA=&input=NzIyMg==): ``` *9+4 h /9|0 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes ``` 9Ývy7L×})˜ïD¹-ÄWQÏ{¬ ``` [Try it online!](https://tio.run/nexus/05ab1e#ASIA3f//OcOddnk3TMOXfSnLnMOvRMK5LcOEV1HDj3vCrP//MTA1 "05AB1E – TIO Nexus") ``` 9Ý # Push 0..9 vy7L×})˜ # For each digit, 0-9, push 1-7 copies of that number. ïD # Convert to integers, dupe the list. ¹ # Push original input (n). -Ä # Push absolute differences. WQ # Get min, push 1 for min indices. Ï{¬ # Push indices from original array that are the min, sort, take first. ``` [Answer] ## Mathematica, 56 bytes ``` Min@Nearest[##&@@@Table[d(10^n-1)/9,{n,0,6},{d,0,9}],#]& ``` Pure function with first argument `#`, works for inputs up to `10^6`. For a nonnegative integer `n` and a digit `d`, `10^n-1 = 99...9` (`9` repeated `n` times), so `d(10^n-1)/9 = dd...d` (`d` repeated `n` times). Creates a `Table` of values for `0 <= n <= 6` and `0 <= d <= 9`, then flattens the table, finds the list of elements `Nearest` to `#` and takes the `Min`. I believe this version will work for arbitrarily large integers: ``` Min@Nearest[##&@@@Table[d(10^n-1)/9,{n,0,IntegerLength@#},{d,0,9}],#]& ``` ]
[Question] [ Whilst trying to golf several of my answers, I've needed to write large integers in as few characters as possible. Now I know the best way to do that: I'll be getting *you* to be writing this program. # The challenge * Write a program that when given a positive integer, outputs a program that prints it to stdout or equivalent. * The output programs don't have to be in the same language as the creator. * The output must be at most 128 bytes. * You may accept input from stdin or equivalent (not function input) * You may output the resulting program to stdout or equivalent. * The number output must be in decimal (base 10) ## Scoring Your score is equal to the smallest positive integer your program can not encode. The entry with the largest score wins. [Answer] # Pyth, 252111 ≈ 3.593 × 10266 ``` Js[ "ixL-rC1`H``N" N s@L-rC1`H``NjQ252 N "252")$import sys$$sys.stdout.buffer.write(J.encode('iso-8859-1'))$ ``` Had to use a little bit of Python syntax, because Pyth's `print` can't print in `iso-8859-1`. The number gets encoded in base 252 and represent each digit in that base as an iso-8859-1 char. The chars `\` and `"` would need escaping, and therefore are not used. The char ``` isn't used because golfing... And additionally the null-byte is also not used, the Pyth compiler forbids it. The output is a program with an overhead of 17 bytes: ``` ixL-rC1`H``N""252 ``` Here's an example usage with the biggest number possible: [![Usage](https://i.stack.imgur.com/1r4X4.gif)](https://i.stack.imgur.com/1r4X4.gif) ### Explanation of the output program. ``` ixL-rC1`H``N""252 rC1`H create the range of chars: ['\x01', '\x02', ..., '{}'] ``N creates a string containing the 3 chars " ' \ - remove strings which consists of these 3 chars xL "" determine the index of each char in "" (encoded number) i 252 convert from base 253 to base 10 ``` [Answer] # CJam, 254109 ≈ 1.34 x 10262 ``` q~254b{_33>+_91>+c}%`"{_'[>-_'!>-}%254b" ``` I'm encoding the number in base 254 and represent each digit in that base as an ISO 8859-1 character, skipping `"` and `\`. The output has an overhead of 19 bytes, `""{_'[>-_'!>-}%254b`, so I can represent everything less than 254128-19, or explicitly ``` 13392914970384089616967895168962602841770234460440231501234736723328784159136966979592516521814270581662903357791625539571324435618053333498444654631269141250284088221909534717492397543057152353603090337012149759082408143603558512232742912453092885969482645766144 ``` As an example, `6153501` would be encoded as ``` "abc"{_'[>-_'!>-}%254b ``` [Here is a test program](http://cjam.aditsu.net/#code=q~254b%7B_33%3E%2B_91%3E%2Bc%7D%25%60%22%7B_'%5B%3E-_'!%3E-%7D%25254b%22%0A%0A%5Ds_oNo%0A%0A_%2Cp%0A~p&input=13392914970384089616967895168962602841770234460440231501234736723328784159136966979592516521814270581662903357791625539571324435618053333498444654631269141250284088221909534717492397543057152353603090337012149759082408143603558512232742912453092885969482645766143) which prints the encoded integer, and then prints its length, and then executes it right away to show its validity (this avoids the trouble of having to copy the unprintable characters into a new program, which doesn't always work with the online interpreter). [Answer] # Perl, 10216 ``` print"print unpack'h*',q{",(pack'h*',<>),"}" ``` Also base 100 encoding, slightly more elegant. Output for `12345678` would be: ``` print unpack'h*',q{!Ce‡} ``` The delimeters `{` and `}` correspond to hex values `b7` and `d7` respectively, which cannot appear in the input, and therefore do not need to be escaped. There are 20 bytes of overhead, leaving 108 for encoding, reaching a maximum value of 10216-1. --- ### Perl, 10206 ``` print"ord=~print\$' for'",(map chr"1$_",<>=~/.{1,2}/g),"'=~/.|/g" ``` Simple base 100 encoding. Output for `12345678` would look like this: ``` ord=~print$' for'p†œ²'=~/.|/g ``` There are 25 bytes of overhead, leaving 103 for encoding, reaching a maximum value of 10206-1. [Answer] # Common Lisp, 36114 - 1 ~ 2.62 × 10117 ``` (lambda(x)(format t"(lambda()#36r~36r)"x)) ``` The largest number is: 2621109035105672045109358354048170185329363187071886946329003212335230440027818091139599929524823562064749950789402494298276879873503833622348138409040138018400021944463278473215 Simply use base 36. For the largest input, the 128-bytes long output is: ``` (lambda()#36rzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes ~\$10^{305}\$ ``` øCṪ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDuEPhuaoiLCIiLCIzMDUiXQ==) Thanks to emanresu A for 2 more orders of magnitude Simple number compression builtin, then chop off the last char. Generates a Vyxal compressed number in base 255. Exceeds the 128 byte output limit at \$10^{305}\$, but can go up to \$10^{308}\$ if the ceiling is raised to 130 bytes. [Answer] # Python 3 → CJam, (163122 − 1)·255/162 + 1 ≈ 1.213·10270 ``` import sys n = int(input()) for b in range(163, 1, -1): s = [] m = n while m: m, r = divmod(m - 93, b) if m < 0: break s.append(r + 93) else: sys.stdout.buffer.write(b'"%s"%db' % (bytes(s[::-1]), b)) break else: sys.stdout.buffer.write(b'%d' % n) ``` It turns out that every integer from 1023 through (163122 − 1)·255/162 can be represented in at least one way by a base *b* ≤ 163 conversion from a string of at most 122 characters with codes 93 through *b* + 92, rather than the usual 0 through *b* − 1. This avoids the troublesome characters 34 (double quote) and 92 (backslash) without any extra output code. [Answer] # CJam, 233114 ≈ 7.561⋅10269 ``` ri233b{Kms/m]_34=+c}%s`"{iKms*}%233b" ``` The output program `"…"{iKms*}%233b` decodes the 8-bit characters of a string to base 233 digits with *n* ↦ ⌊*n* ⋅ sin 20⌋ = ⌊*n* ⋅ 0.913⌋. This transformation happens to be surjective without requiring the critical codepoints 34 (double quote) and 92 (backslash) as input. ]
[Question] [ Given (in any *structure*; flat list, two lists of lists, a tuple of matrices, a 3D array, complex numbers,…) the coordinates for two non-degenerate triangles `ABC=[[Ax,Ay],[Bx,By],[Cx,Cy]]` and `PQR=[[Px,Py],[Qx,Qy],[Rx,Ry]]`, determine if they are similar, that is, > > they both have the same shape, or one has the same shape as the mirror image of the other. More precisely, one can be obtained from the other by uniformly scaling (enlarging or reducing), possibly with additional translation, rotation and reflection.[[Wikipedia]](https://en.wikipedia.org/wiki/Similarity_(geometry)) > > > You may assume that all coordinates are integers. You must either return a truthy/falsey value indicating similar/dissimilar respectively, or two consistent values; please state your choice. Failing on some cases due to limitations in floating point precision is acceptable so long as the algorithm is correct in principle. **Bonus task:** Add a comment to this post stating whether you would like the same challenge generalised to polygons in N-space. ## Walked-through example case `ABC=[[0,0],[1,0],[0,1]]` and `PQR=[[1,0],[-1,0],[1,-2]]` 1. Reflect `ABC` in the x-axis: `[[0,0],[-1,0],[0,1]]` 2. Reflect in the y-axis: `[[0,0],[-1,0],[0,-1]]` 3. Enlarge by a factor of 2: `[[0,0],[-2,0],[0,-2]]` 4. Translate right by 1 unit: `[[1,0],[-1,0],[1,-2]]` This gives us `PQR`. ## Test cases ### Similar `[[8,4],[5,-5],[0,0]]` and `[[-4,-1],[5,-1],[-1,5]]` `[[-2,1],[4,-2],[6,2]]` and `[[-1,-1],[2,-1],[-1,1]]` `[[-1,0],[1,0],[0,2]]` and `[[-2,5],[2,5],[0,1]]` ### Dissimilar `[[0,0],[-1,0],[0,1]]` and `[[1,0],[-1,0],[2,-3]]` `[[2,1],[4,2],[6,2]]` and `[[-1,-1],[2,-1],[-1,1]]` `[[-1,0],[1,0],[0,3]]` and `[[-2,5],[2,5],[0,1]]` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~15~~ 12 bytes ``` ,i4:)d|S]/da ``` The program inputs two 3×1 vectors of complex numbers representing the coordinates; and outputs `0` for similar, `1` for not similar. [Try it online!](https://tio.run/##y00syfn/XyfTxEozpSY4Vj8l8f//aAttkywFU13TLAUDbYOsWK5oXRNdQ5AIkNA11DbNigUA) Or [verify all test cases](https://tio.run/##y00syfmf8F8n08RKM6UmOFY/JfG/uq6ueoRLyP9oC22TLAVTXdMsBQNtg6xYrmhdE11DkAiQ0DXUNgULGWkDeSa6RlkKZtpGYBFDkLwRVJEhRAioXwFMGEAVGQG1K4AJA4gakBUKulA1YBFDhIiRrjFIBGKXNvF2GWOzCwA). ### Explanation The code checks if the side lengths, sorted for each triangle, are proportional between the two triangles. ``` , % Do twice i % Take input: 3×1 vector of complex numbers 4:) % Modular index to repeat 1st number after the 3rd. Gives a 4×1 vector d % Consecutive differences | % Absolute value, element-wise S % Sort ] % End / % Divide, element-wise d % Consecutive differences a % Any: gives 0 if and only if all values are 0 % Implicit display ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes *Port of [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/194143/6484).* Outputs 1 for similar, 0 otherwise. ``` vyĆüαnO{}/Ë ``` [Try it online!](https://tio.run/##yy9OTMpM/f@/rPJI2@E95zbm@VfX6h/u/v8/OjraQsckVifaVEfXFEgZ6BjExuooREfrmujoGkLEQZSuoY5pbGwsAA "05AB1E – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṁ4IAṢ)÷/E ``` A monadic Link accepting a list of two triangles - lists of complex numbers (coordinates on the Cartesian plane). Similar triangles yield `1`, dissimilar ones yield `0`. **[Try it online!](https://tio.run/##y0rNyan8///hzkYTT8eHOxdpHt6u7/r/cNvD3d2H2///j46OttBRMInVUYg21VHQNQUxDHQUDGJBjGhdE6CYIUwSzNA11FEwjY2NBQA "Jelly – Try It Online")** (includes footer to translate from coordinate pairs for ease of use) Or see the [test-suite](https://tio.run/##y0rNyan8///hzkYTT8eHOxdpHt6u7/r/cNvD3d2H2zX//49WUFYIzszNzEks4lJQiI6OVjDQUTCI1VGIVjCEMYAihrEgFkJM1xChStcoNjaWSwes2UJHwQQsbKqjawrTbADRrGuio2sIkzSEmWIK16xrBLIHJG8CMlNBJ1rBTEfBCKrZEKbZCEmzIUgz0AcumcXFUE/ooHhClzhPAM00RngCyR1A60EMotwRCwA "Jelly – Try It Online"). ### How? ``` ṁ4IAṢ)÷/E - Link: list [[a, b, c], [d, e, f]] ) - for each: ṁ4 - mould like 4 [[a, b, c, a], [d, e, f, d]] I - deltas [[b-a,c-b,a-c],[e-d,f-e,d-f]] (i.e. vectors of sides as complex numbers) A - absolute value (i.e. side lengths) Ṣ - sort (ordered side lengths = [[G, H, I], [J, K, L]]) / - reduce by: ÷ - division [G÷J, H÷K, I÷L] E - all equal? ``` [Answer] # [J](http://jsoftware.com/), ~~39~~ ~~34~~ 32 bytes ``` 1=[:#@~.%&([:/:~#:@3 5 6|@-/@#]) ``` [Try it online!](https://tio.run/##dY1LC4JAFIX38ysOSaaQo@OLGBCkoFW4qKXJEKGkFEK5DP/6dH3UrsXlwD33@26jF3xVIZFYYQ0Pksbh2B0Pey2SXBppz5emlUtX9oZMA0SI36njpkZha5uxrnx1CUcuUV5vLSrTUj4a7p5RUJttOU71o75fnmyDkGAV0QMPAwYVQolhJ8ZkRAo6oojhzydj5c8pJmPWdj/rIKNmCDEh4rshKmCT8r9RfwA "J – Try It Online") Takes input as 3 complex numbers for each triangle. For each triangle, we get each possible pair of points using a boolean mask filter. Ie, `#:@3 5 6` translates 3, 5, and 6 to their binary representations, and each row selects one possible pair: ``` 0 1 1 1 0 1 1 1 0 ``` We then get the euclidean distances between of each of these pairs `|@-/` and then sort them `/:~`. Finally we pairwise divide the 3 sorted sides of the triangle `%`, take the length of the unique elements of that result `#@~.` and test if it equals one `1=`. [Answer] # JavaScript (ES7), ~~122 120 117~~ 112 bytes Takes input as `(a)(b)`, where both parameters are in the format used in the challenge. Returns *false* for similar or *true* for dissimilar. ``` a=>b=>(g=a=>a.map((c,i)=>(h=j=>(c[j]-a[-~i%3][j])**2)(0)+h(1)).sort((a,b)=>a-b))(a).some((x,i)=>a-(a=x/g(b)[i])) ``` [Try it online!](https://tio.run/##jY/BboMwDIbvfYpdJtmdAyQt1S7pi0Q5GEppEJQKqqmnvTozZK0mrZN2sa3f@f74b/iDx3IIl6s694dqOtqJ7b6we6itDJx0fAEoKaBIJ9tILV3jFTv1GV43XmZcrw1Chm8n0IjJ2A9XAKZCCFYFIvAsdhXAbbFhBWxvaQ0FuuARpzR9GUMXWh5WZX8e@7ZK2r6GIzj3TltPLieVS8so8x5FVVtSOupzU5pyWeAvWhma9/LaSNuR@cZ15MwD189xLR@SizV70IbyBY4nRXQlGQ5h/CtGtliou5OOTvqnKsdsnl5xz/CfCNMX "JavaScript (Node.js) – Try It Online") ### Commented ``` a => b => // a[] = 1st triangle; b[] = 2nd triangle ( g = a => // g is a helper function that computes the squared lengths // of the sides of the triangle a[] and sorts them: a.map((c, i) => // for each pair c[] of coordinates [x,y] at position i: ( h = j => // h is a helper function that computes ... ( c[j] - // ... the difference between either x(i) and x(i+1) a[-~i % 3][j] // or y(i) and y(i+1) (in a circular way) ) ** 2 // and squares it )(0) // compute (x(i) - x(i+1))² + h(1) // add (y(i) - y(i+1))² ) // end of map() .sort((a, b) => a - b) // sort the results in numerical order )(a) // computes the squared lengths for a[] .some((x, i) => // for each squared length x at position i: a - // compute the difference between the previous ratio (a = x / g(b)[i]) // and the new ratio defined as x / g(b)[i] // (always NaN for the 1st iteration) ) // end of some() ``` [Answer] # [Python 3](https://docs.python.org/3/), 85 bytes ``` lambda a:len({i/j for i,j in zip(*[sorted(map(abs,[p-q,q-r,r-p]))for p,q,r in a])})<2 ``` [Try it online!](https://tio.run/##lY1BDoIwEEX3nqLLYmciLWCM0ZNUFiVIbAOlFDZqPDtSMTERN25@ZjLvzXfX4dLaZKyOp7FWTVEqovb12dK73hhStZ5oMERbctOOrmXf@uFc0kY5qooepMMOOvTg0eVRFHAHHfggqDx6RAcxOq/tQCsq5Y6lBjLMDMQ5SEyRh3UK5Cwz@fRg9YFRsOmSojCwZcIEgQdWvAW@EDhwmEExvYNXLKgYAhcoHiaByTcx97L/epOfveMT "Python 3 – Try It Online") *-17 bytes thanks to [FlipTack](https://codegolf.stackexchange.com/users/60919/FlipTack)* *-7 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)* Takes a list of lists of coordinates represented by complex numbers as input. Calculates the distances between all points in each set and sorts by magnitude. Then, it checks for all pairs of distances between the two sets if there is a common scaling factor. If so, the triangles are similar. [Answer] # APL+WIN, 40 bytes Prompts for the co-ordinates of each triangle as a 4 x 2 matrix with first row repeated as last row. Confirmed with OP that this is compliant with the input rules ``` 0=+/2-/(y[⍋y←⍎c])÷x[⍋x←⍎c←'+/(-2-⌿⎕)*2'] ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4b2GrrG@nqa1RGP@rtrgSKP@rtS47VPLy9AiRQARUAUura@hq6RrqPevYDTdDUMlKP/Q804H8al4mC0aPeLRYKJgqmCofWmyoYKBhAxQ6tNwGKGILFDSEsrjS4nJGCoQJI3kjBTMEILgpRZwTXYQjXATQXLAKiDaFihnAxkA5juFqI2YRM5gIA "APL (Dyalog Classic) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 84 bytes ``` lambda*M:len({x/y for x,y in zip(*[sorted(abs(3*x-sum(l))for x in l)for l in M])})<2 ``` [Try it online!](https://tio.run/##lc3RCoIwFAbg@55il5s7I7dpRNQj@ATmhWKSY05RAy169uU0gqSbbg7/2T7O34z9tTbSFqez1WmV5akXHfTF4MewHVFRt2iAEZUG3csGe3FXt/0lx2nWYekNrLtVWBMyM4f0HLWLUUKe5Chs05amxwWO9zRQELJQgZ9AzALG3ToNxmmoEkI2H8oEnd4DJhTsqFCOcyfFm/MV58BhYWI6BfNYGR@ccoa7JJj8/l8a6T@N8lejfQE "Python 3 – Try It Online") Takes input as 3 complex numbers. Outputs True for similar, False for dissimilar. The first test case fails due to a float precision issue with two extremely close float values being unequal; the challenge allows this. This uses a bit of a different method than other answers that fingerprint congruent triangles by their edges having equal length. Instead of taking the distance between pairs of vertices, we use the distance between each vertex and the center-of-mass of the three vertices, that is their average. To demonstrate that a unique triangle satisfies this up to congruence, note that the three vectors emanating from the center of mass to the vertices must add by zero by definition, which means these vectors must themselves be able to make a triangle. Since their lengths are fixed and we only get to choose their angles (slopes), this is the same as arranging three sticks as the edges of a triangle, which as noted before is unique up to congruence. To check similarity, we sort the respective distances and check that their ratios are all equal. This alternative method is shorter, but I haven't proved that it doesn't give false positives. **79 bytes** ``` lambda a,b:g(a)==g(b) g=lambda l:{abs((x-y)/(3*x-sum(l)))for x in l for y in l} ``` [Try it online!](https://tio.run/##lY/NToQwFIX3PEUTN62047TAxBB5C3c4McUpWCy0aasCxmdHyox/Ezdubu7Pl3PONaN/1H0y18XdrHhXHTjguMobyFFRNLBCUVOc9ip/45WDcCAjuoLJ5UDccwcVQqjWFgxA9kCB0I5r@z5fgFvhPODGWD2AF2Gd1D3wGnCl9CuoleYeyM5Y8SDDyUVOW3//JMZPyymH08YKrvC0kR1vUFQXP1IuOrAMmUKkGyrIbvUf8JpgkgYGQXGA4R2Ev4ZqybxHUWSs7D2sYXkdpy3OSNbi7R6XJCU0jEshNM7aPULfKGHxsk8Ja/EuZm3AaSDZCadnOMUUHzG2SOG1nDFbHKjA0NAxkvy@Hx3j/zgmfznOHw "Python 3 – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~23~~ 21 bytes ``` {{{⊇Ċ-^₂}ᶠ}ᵐz+ᵐo}ᵐz/ᵛ ``` -2 bytes thanks to Unrelated String A predicate that only accepts similar triangles. Note that for negative values you have to type `_1` instead of `-1` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXfVw64RyJQVdOwWlcnsQp/pR24ZHTc2POpYrlRSVpuop1YCYaYk5xUB27cNdnbVARf@rq6sfdbUf6dKNe9TUVPtw2wKQaJU2kMgHs/Qfbp39/3@0QnR0tIWOSaxOtKlOvCmQMtAxiI3VAQrHm@jEG0LEQVS8oY5pLEQGrAYsYgDWYAgRNkQWNdKJN4YpjzfSAZkANM8ISJnpGEEtMISYbAS3wBCmA6aBCPUKsf8B "Brachylog – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~87 82 77~~ 74 bytes ``` ->*a{a.map!{|a,b,c|x,y,z=[a-b,b-c,a-c].map(&:abs).sort;[x/z,y/z]}.uniq!=a} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf104rsTpRLzexQLG6JlEnSSe5pkKnUqfKNjpRN0knSTdZJ1E3ORYkr6FmlZhUrKlXnF9UYh1doV@lU6lfFVurV5qXWahom1j7v0AhLTraQEfBEIgyY3UUooEMXRBH1ygzNpYLLK1rmIlLwX8A "Ruby – Try It Online") Given the 2 triangles as vectors of 3 complex numbers, calculate length of the three sides as distance between points, sort ascending, then check if a/b and a/c are the same for both. [Answer] # [Julia 1.0](http://julialang.org/), 65 bytes ``` !x=sort(abs.(diff(push!(x,x[1])))) g(a,b,z=!a./!b)=all(z.≈z[1]) ``` Revised to not abuse the "any input structure" statement, as people seemed down on that. Found extra golfing, so it's only 1 byte longer. The input is two vectors of complex numbers. `!` is a helper function that appends the first element to the end of each input list and returns the result, then takes the difference ob subsequent elements, elementwise absolute value, and sorts. Then calculate the ratios of the sorted lengths of the sides and check that they are all approximately equal. It costs the same number of bytes to compare square side lengths (replace `abs` with `abs2` and `≈` by `==`). [Try it online!](https://tio.run/##bY9NDoIwEIX3nALCpqQt0grGTRP/btGwKBKkBoKhEgkn0Gt6EWwbERZ2Mcl782a@6bWrpCD9OHo9U017ByJTIchlUYBbp0oP9KjnJA30cy5AoAwNzBPhyssCJqoKDOH79RxMYvSVrGUlWkenGN/CWNYowYmuEYxknSKX4xgT65qKCdTN1DmjnHFMofFiTHXdQGryHBMbpFOcmLifSzWR9ujAuN1u2pFFETtKlibFazN5RCfGvxy44Lj/QTtVNg/Xfjr4CX3sLDR@Fnp7MH4A "Julia 1.0 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 38 bytes ``` Equal@@Sort/@PolygonAngle/@Polygon/@#& ``` ~~[Try it online!](https://tio.run/##nZBBC4IwGIbv/g3D0zfcposuxTp0F4Iu4WGEmqAbmR1i@NuXbk4K6tJl43v3vNvDWtFfi1b09UWYcmsOt4doOD@qro95pppnpeReVk2xTDEPI5N1tezPIdqVPMyjmOtAa40BD6CJXTGQYdzmCZH5CNFhjCd4A@mYMEDM0tjSKAVEXExcjXkeUZiidLoC9BqoKxBH0qVAlgL50Jl5CszizDs6GL9rfnUfX0g87VX@M0l@mQRD4P51dSq6e61kbl4 "Wolfram Language (Mathematica) – Try It Online")~~ Takes a list containing two lists of coordinates. Checks if the two triangles' angles are equal. As [`PolygonAngle`](https://reference.wolfram.com/language/ref/PolygonAngle.html) was introduced in version 12.0, this code does not (yet) work on TIO. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes ``` ≔EAEιΣXEλ⁻ν§§ι⊕μξ²θUMθ×⟦⌊ι⌈ιΣι⟧Σ§θ¬κ⬤⊟θ⁼ι§§θ⁰κ ``` [Try it online!](https://tio.run/##XU47a8MwEN77Kzye4AROiCGQyZQOHloC6WY8CFskotL5ITn1v1dOCunQG/Tdne579De19KOyMdbemyvBp5qgoWkNILBIg8Hisjo4j796yb@W94ZWD4RFHRoa9AYv5OOG@kU7TUEP4ASLbCK9e5FhFqc3FnkfnVM0wIzFt3HaQ8uSxrGPybbbX3/J2D2blw3TvsYAP0mTBc@LoQC1tZxygplZH/OqrE9x/idkaskHmXqKseU64qHDtkJZMZRYdgytPKDcPdcJ5A6rjivKu30A "Charcoal – Try It Online") Link is to verbose version of code. Outputs `-` for similar, nothing for dissimilar. Accepts triangles in any N-dimensional space. Explanation: ``` ≔EAEιΣXEλ⁻ν§§ι⊕μξ²θ ``` Input the two triangles and calculate the squared lengths of their sides. ``` UMθ×⟦⌊ι⌈ιΣι⟧Σ§θ¬κ ``` Calculate the shortest, longest and sum of the squared sides of each triangle, then scale by the sum of the squared sides of the other triangle. ``` ⬤⊟θ⁼ι§§θ⁰κ ``` Check that the shortest and longest and sum of the squared sides are equal. (The middle squared side is the difference between the sum and the other two sides individually, so if they are all equal then the middle squared sides are also equal.) [Answer] # [Zsh](https://www.zsh.org/), ~~156 122~~ 116 bytes ``` s(){m= for a b x y;m+=($[(a-x)**2+(b-y)**2]) n+=(${(n)m})} s $=1 s $=2 ((r=(n[1]+0.)/n[4],r*n[5]-n[2]||r*n[6]-n[3])) ``` ~~[Try it online!](https://tio.run/##jY7BboMwEETv/oo5INkLcYsNVFUk1PwHciVSJc3FRAJUkSb@drqGVFFvvXh3dvfN@Hs4zUdFSgyHEXqaB0VXX4uxVsl1t31v@8@vgMSQOJ57tNhjwgW8q8etCeQzvmtUqydKU5upvb7ExpHw0UB15AMFMSDZNWZTONHx2FMcsHsZhFJ9rbrGuCx/omfPzaZPfWOd7vi53aIooigc0cy/gMQrSglZQVdccuQSgNQltGGNaq3aAJUUh4/TGclb5LRFXPCd5fICu3LmztkHZx5cBJeIZZEvgWYBcde/82hQ/Alc81AC/w@cfwA "Zsh – Try It Online") [Try it online!](https://tio.run/##jVLBbuIwEL37K0Y0UuwSlzhAVYGi7mEve969Rd7KLUmJljgodlVYyrezY5vQsKcaMvbMm/dm4sxfsz5VlFFiSgt8dzKUHZqcVG0HCp5hB/tlM85pVFDFd@z2NhvTZ753B8lIg8CBatYc2ZEYiHJBNIYa5p2MUNrlVBdCjtM7NmnwkHS3TZFJrtF8fDhn6pypZOzESAXxA8xgDnweTHr@YTQGXDGfARcOO5uB45CYlC/rFqJHJ8UzEKiGmzf3EB4Xjp2UZ2cXg/9PM5RyWq4JDJ9NCuL8pL4tiMUVjnrTYNC76im0lPmnbyj0E17vyz3dwLvSFpq2K8GWxsKLMqV5xPi2K7cKo9u21tbAe23XYNe1WZAQebLtk@pe3YcmrugNWPWnNH1@rUFtmhYVld4DzkGjrM/zA8IhOuTR4dtkUvwuFqv6tbYLecflBI5Hn/WmXZ7qOu@5MXIjFCq5hYgbpx1Ee/CWeSiQEczpKMKtmCYik@CPIsnkCEJYzBMu@jjmzOSIkSPx8@qvgXqhuCi4SFKZFMGmKCHxhVaAQJbMMRRsmggp457zkMwwhiUClH5yZq6sh9yG2vMBDRVdFHMy3O6HtUQgZBfesFzqe@N9i@JCE0MAudMBqa/1xVJsCavWc6@/PkTuugLQIQB8A3HuVwyjX/1ELUIeXv8PvX2zC3/zI0@rK6i8u8TxKvXlCwe5@HttTN3UG9WF1suNKeH/pJ/DjKomq1aXp38 "Zsh – Try It Online")~~ [Try it online!](https://tio.run/##jVLBbuIwEL3nK0Y0UmyISxwIqkBR97CXPe/eLG/llqRESxwUpyos5dvZsU1o2FMDHmfmzXszseev2ZxLQklgig7Y/mwIPdZ5UDYtKHiGPRxW9SQnoSCK7el4nE7IMzvYF0kDbZEj0bQ@0VNgIMy5s2lASJsTLbicJPd0qsVcxu1Yi0wyLVL58WGdhXVmktIzDUqIHmAOGbDMm@Tyw2gE@ERsDoxb7GIGjkWioHjZNBA@WimWAkc13JxZgF82HFkpx06vBv@fZihltWwTGL6YBPhlJa4tiPgNjnozb9C76cm3lLrVN@T78Z/35Z7u4F3pDuqmLaArTAcvyhTmEeO7ttgpjO6aSncG3qtuA92mMsvAR5665km1r/aKA1v0Djr1pzB9fqVBbesGFZU@AE5ArTqX50aDQXjMw@O36VT8Fst19Vp1S3nP5BROJ5f1pm2ealvn2QGyw@Mr2QcROy57CA/gLHWQJyOYk1GIm5jFPJXgXnmcyhH4MM9ixvs45szliAanwE2qOwbihCIhGI8TGQtvE5SQ@EFrQCCNMwx5m8RcyqjnPMQ4oQJLeCj55MxtWQfZDbWzAQ0VbRRzUtwWw1rcE9Irb1gucb2xvkV@pfEhgNzZgNTX@mIpuoJ147i3tw@hPS4PtAgA20KUuyeC0a9@opY@D4//h969dUt38iNHq0oonbvC8Sr09Ya9XPS9Mqaqq61qfevF1hTwf9LPYUZZBetGF@d/ "Zsh – Try It Online") Saves 34 bytes by abusing "any structure" for input. Given a pair of triangles: ``` [[1,2],[3,4],[5,6]] and [[7,8],[9,10],[11,12]] ``` The input should be the two strings: ``` '1 2 3 4 3 4 5 6 5 6 1 2' '7 8 9 10 9 10 11 12 11 12 7 8' ``` I believe this is within the rules; there is no calculation done beforehand, simply duplication. No sorting criteria is applied either. I provide a helper function in the TIO link to prepare an argument list from a string in almost any format (it removes all non-numeric characters and splits). Here is the first **156 byte** answer, which takes the input in a less abusive format. The abusive format removes line 2 in `s`, and reduces line 3: ``` s() { # helper function, calculates squares and sorts them for one triangle m= # unset m in case it was already used t=(${@:^argv} $1) # t=('x1 y1' 'x1 y1' 'x2 y2' 'x2 y2' 'x3 y3' 'x3 y3' 'x1 y1' for a b x y (${=t:1}) # Remove first element of $t, and split on spaces: m+=($[(a-x)**2+(b-y)**2]) # (a b x y): (x1 y1 x2 y2) (x2 y2 x3 y3) (x3 y3 x1 y1) m=(${(n)m}) # sort squared lengths in numeric order } s $@[1,3] # run s with the first three arguments n=($m) # save first result in n s ${@:4} # run s with the last three arguments ((r=(n[1]+0.)/m[1], r*m[2]-n[2] || r*m[3]-n[3])) # returns truthy if not similar ``` ]
[Question] [ The below pattern will form the basis of this challenge. ``` /\ \/ /\ / \ / \ /\/ \/\ \/\ /\/ \ / \ / \/ /\ \/ ``` Given an input width and height, each `>=1`, output the above ASCII art pattern repeated that many times, joining (and overlapping) at the small diamonds. For example, here is an input with `width = 2` and `height = 1`: ``` /\ /\ \/ \/ /\ /\ / \ / \ / \ / \ /\/ \/\/ \/\ \/\ /\/\ /\/ \ / \ / \ / \ / \/ \/ /\ /\ \/ \/ ``` Here is an input `width = 3` and `height = 2`: ``` /\ /\ /\ \/ \/ \/ /\ /\ /\ / \ / \ / \ / \ / \ / \ /\/ \/\/ \/\/ \/\ \/\ /\/\ /\/\ /\/ \ / \ / \ / \ / \ / \ / \/ \/ \/ /\ /\ /\ \/ \/ \/ /\ /\ /\ / \ / \ / \ / \ / \ / \ /\/ \/\/ \/\/ \/\ \/\ /\/\ /\/\ /\/ \ / \ / \ / \ / \ / \ / \/ \/ \/ /\ /\ /\ \/ \/ \/ ``` ### Rules and I/O * Input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * You can print it to STDOUT or return it as a function result. * Either a full program or a function are acceptable. * Any amount of extraneous whitespace is acceptable, so long as the characters line up appropriately. * [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. [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~26~~ ~~25~~ ~~24~~ ~~21~~ 18 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` 4/╬/╬⁰r:⤢n↷⁸{A×├m↷ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjE0JXVGRjBGJXUyNTZDLyV1MjU2QyV1MjA3MCV1RkY1MiV1RkYxQSV1MjkyMiV1RkY0RSV1MjFCNyV1MjA3OCV1RkY1QiV1RkYyMSVENyV1MjUxQyV1RkY0RCV1MjFCNw__,i=JTVCMyUyQzIlNUQ_,v=8) -3 bytes by fixing `m` not repeating canvas Explanation: ``` 4/╬ quad-palindromize a 4-long diagonal - big inner diamond /╬ quad-palindromize "/" - small diamond ⁰r join the two vertically, centered :⤢n overlap with transpose ↷ and rotate the thing clockwise ⁸{ for each input A× times 10 ├ plus 2 m mold the canvas to that width ↷ and rotate clockwise, setting up for the next iteration ``` [Answer] # JavaScript (ES8), ~~167~~ ~~161~~ 159 bytes *NB: This is encoding the pattern. See [my other answer](https://codegolf.stackexchange.com/a/175685/58563) for a shorter mathematical approach.* Takes input as `(width)(height)`. ``` w=>h=>(g=h=>h?g(--h)+` `+([4106,4016,31305,21504,17010]['0102344320'[h%=10]]+'').replace(/./g,c=>'\\/'[c^h>5]||''.padEnd(c-1)).repeat(w+1).slice(8):'')(h*10+2) ``` [Try it online!](https://tio.run/##HYxBboMwEEX3vUflmdgYj23SKpLpqqcgVLGMgxMhQAGFTe5OrWze4uv9d/dPv4THbV6LcerifnX75urkauhdZvrpoSgS8svHhUNjSR2FVXQUhoyqhKZKWUFfilTbsExtrDVasSZ9ury1nDGUjzgPPkQoZdmL4Gp2PpesCX@prtrXizE5@@537CAUhG87@hU2TiiX4ZZ/33jKGUgHUlzjHqZxmYYoh6mHKxgEjbj/Aw "JavaScript (Node.js) – Try It Online") ### How? We encode the upper half of the pattern with digits: * \$0\$ means `\` * \$1\$ means `/` * \$n=2\$ to \$7\$ means \$n-1\$ spaces This gives: ``` 0 ···/\····· --> [3 spaces] [/] [\] [5 spaces] --> 4106 1 ···\/····· --> [3 spaces] [\] [/] [5 spaces] --> 4016 0 ···/\····· --> [3 spaces] [/] [\] [5 spaces] --> 4106 2 ··/··\···· --> [2 spaces] [/] [2 spaces] [\] [4 spaces] --> 31305 3 ·/····\··· --> [1 space] [/] [4 spaces] [\] [3 spaces] --> 21504 4 /······\/\ --> [/] [6 spaces] [\] [/] [\] --> 17010 ``` For the lower half, we use the rows \$4,3,2,0\$ with `/` and `\` inverted. [Answer] # JavaScript (ES6), 139 bytes This is using quite a different approach from my initial answer, so I'm posting this separately. Takes input as `(width)(height)`. ``` w=>h=>(g=x=>y>8?` /\\ `[a=(x+y*9)%10,d=(x+y)%10,x?(y%10>3&&2*(a==8)|d==5)|(y%10<6&&2*(a==6)|d==7):3]+g(x--?x:--y&&w):'')(w=w*10+2,y=-~h*10) ``` [Try it online!](https://tio.run/##NcjbCoJAFIXh@56im3RvdcoDmUl7fJAMHDwW4kRGzoD06pMIXa1/fQ/xEWP5uj/fbJBVbRoyE/GOOLSkiGueZMX2kOeb4ioIlKudM@4C36vWs6bKQC/LI8sKHRBECc4V0RHn1S/x3@PVT5hGN7cFxVimUsa0ZU2Y2jbCRJMT@G7oaWLfbkk0pRxG2df7XrbQQIQQIpof "JavaScript (Node.js) – Try It Online") ### How? Given the width \$w\$ and the height \$h\$, we draw the output character by character over a grid which is: * \$10w+3\$ characters wide * \$10h+2\$ characters high with \$x\$ going from \$10w+2\$ to \$0\$ (left to right) and \$y\$ going from \$10h+10\$ to \$9\$ (top to bottom). Example for \$w=3\$ and \$h=2\$: $$\begin{matrix}(32,30)&(31,30)&\dots&(0,30)\\ (32,29)&(31,29)&&(0,29)\\ \vdots&&\ddots&\vdots\\ (32,9)&(31,9)&\dots&(0,9)\end{matrix}$$ The rightmost cells (at \$x=0\$) are simply filled with linefeeds. For all other cells, we compute: * \$a=(x-y)\bmod 10\$ (constant over anti-diagonals) * \$d=(x+y)\bmod 10\$ (constant over diagonals) We draw a `"/"` if: $$((y\bmod 10)>3\text{ and }d=5)\text{ or }((y\bmod 10)<6\text{ and }d=7)$$ ``` y | y % 10 | output (w = 3, h = 1) ----+--------+---------------------------------- 20 | 0 | ...../........./........./...... 19 | 9 | ....../........./........./..... 18 | 8 | ...../........./........./...... 17 | 7 | ..../........./........./....... 16 | 6 | .../........./........./........ 15 | 5 | /./......././......././......./. 14 | 4 | ./......././......././......././ 13 | 3 | ......../........./........./... 12 | 2 | ......./........./........./.... 11 | 1 | ....../........./........./..... 10 | 0 | ...../........./........./...... 9 | 9 | ....../........./........./..... ``` We draw a `"\"` if: $$((y\bmod 10)>3\text{ and }a=8)\text{ or }((y\bmod 10)<6\text{ and }a=6)$$ ``` y | y % 10 | output (w = 3, h = 1) ----+--------+---------------------------------- 20 | 0 | ......\.........\.........\..... 19 | 9 | .....\.........\.........\...... 18 | 8 | ......\.........\.........\..... 17 | 7 | .......\.........\.........\.... 16 | 6 | ........\.........\.........\... 15 | 5 | .\.......\.\.......\.\.......\.\ 14 | 4 | \.\.......\.\.......\.\.......\. 13 | 3 | ...\.........\.........\........ 12 | 2 | ....\.........\.........\....... 11 | 1 | .....\.........\.........\...... 10 | 0 | ......\.........\.........\..... 9 | 9 | .....\.........\.........\...... ``` Or we draw a space if none of these conditions is fulfilled. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 137 bytes ``` #include<cstdio> auto p(int x,int y){int n=10,t=x=++x*n;for(++y*=n;y>8;)t>7?putchar(t<9?y--,n:t%n-y%n+4&7?t%n+y%n-5&7?32:47:92),t--:t=x;} ``` [Try it online!](https://tio.run/##fY/BboMwDIbP4ymiTh1Jk0xdYWJNAkh7jl5QYG3U1kHUkUBVn52FHSbtsov/T7b1/7bte3m0dn52YC@h7Yhx/oZD11yr356xN2ydr5ImoCc9dYBkFEud2H0RKN@2Asux5HzcgP7yA@V82pSgp@pDM6yKug9oT81A0ezrSUoBCtcgpzXw/KWoI/PI8j1ytlN5ofY7JlBKFV31Y15Cro0Dysg9IfEapawPaMzq0wdoiT119vx6gJUxP8P4gYMjzbYilSkzJj1AqpOnnmYiZ/qPwz/7j/kb "C++ (gcc) – Try It Online") *Explanation* ``` _______________________________ 098765432109876.... 9 \/ . factor =y%10 - x10 8 /\ . if factor = -4 || 4. Print --> '\' 47 7 / \ . 6 / \ . factor =x%10+y%10; 5\/ \/*-. if factor = 5 || 13 --> / 92 4/\ /\ `. 3 \ / `-> * is 9,5 => \ 2 \ / 1 \/ 0 /\ 9 ``` [Answer] # [Haskell](https://www.haskell.org/), 179 bytes ``` k '\\'='/' k '/'='\\' k x=x f x=take(10*x+2) w#h=map(f w.cycle).f h.drop 9.cycle$(++).reverse=<<map(map k)$["\\/\\ /"," \\ / "," \\ / "," \\/ "," /\\ "] ``` [Try it online!](https://tio.run/##PcxRD4IgEAfwdz/FDd2QbFCulzb5BvXUY7TGDGdDzaGlfXq6ZMV28P/d7qj1YE3TeG@BKkUlFTTCKDAhMc5yjiq8R21Nut2s5ixn0RTXstV9WsHEy3fZGMYrqPnNPXrYh06SZhnjzryMG4wsiu84FliWnIlSQilYjiBrgk@ggKCFAn5CIv4Ku@TiW33vQAJ@e7xC/xxPozt0kMAuzv0H "Haskell – Try It Online") --- # [Haskell](https://www.haskell.org/), 181 bytes ``` k '\\'='/' k '/'='\\' k x=x f x=take(10*x+2) w#h=map(f w.cycle).f h.drop 9.cycle$(++).reverse=<<map(map k)$map t[49200,36058,31630,30010,29038] t 0="" t n="\\ /"!!mod n 3:t(div n 3) ``` [Try it online!](https://tio.run/##JcxLDoJADAbgPaeoQAIjBAqjRAxzA125FGMIDMHwkMAIeHoscdH@X5umVTbWsmnWtQYrTS1h@ZZG9Ek0EhexaCV1ldXSDnC/OCHTZqMSbdbbJcxe/s0bybwSKq8Y3j3E/41pOw7zBjnJYZQiSbZzKqiZuYW6H@IQ0eURHk8uDyJORgzQDWPkp4emAIWuU3RCT1Pw9d2ufRfQAT8ru3hNm9jaZq8OBNDH6xP6j7qp4dKBCQcjXH8 "Haskell – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~24~~ ~~22~~ 20 bytes ``` \/↘²‖M↘LF⊖NCχ⁰F⊖NC⁰χ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREMpJkZfSdOaC8KzcskvzwvKTM8o0VEwAooGpablpCaX@GYWFeUXocha@QCl0/KLFDRcUpOLUnNT80pSUzQ88wpKS/xKc5NSizQ0NTUVnPMLKjUMDXQUDIhWDVRsCFT9/78xl9F/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ´\/↘² ``` Draw one eighth of the original pattern. ``` ‖M↘L ``` Duplicate it three times to complete the original pattern. ``` F⊖NCχ⁰ ``` Copy the required number of times horizontally. ``` F⊖NC⁰χ ``` Copy the required number of times vertically. [Answer] # Powershell, 146 bytes ``` param($w,$h)0..9*$h+0,1|%{$y=$_ -join(0..9*$w+0,1|%{('3 /\33 \/33 /\33 / \3 /3 \ /\/33\\/\33/3\3 /3 \ /33 \/3'-replace3,' ')[$y*10+$_]})} ``` ## Explanation The pattern is 10x10 chars array: ``` /\ \/ /\ / \ / \ /\/ \ \/\ / \ / \ / \/ ``` The script: * repeats the pattern; * appends columns [0,1] to the end of each line; * appends lines [0,1] to the end of the output. Two things for golf: 1. The pattern array mapped to string with length 100 bytes; 2. The string reduced by simple `replace`. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 148 bytes ``` $_='3A3'x$_.$/.'3B3 3A3 2/2\\2 1/4\\1 A6A B6B 1\\4/1 2\\2/2 3B3 3A3 '=~s/^.*$/$&x$_/mger x<>.'3B3'x$_;s|A+|/\\|g;s|B+|\\/|g;s/\d/$"x$&/ge;s|^ | |gm ``` [Try it online!](https://tio.run/##NY1BCoMwFET3/xShBAMV802ibloLyb43@OimEgq1inbhIvToTWOhuxne8GYelkcdI@9bYawRG@8lRymMM5A6aNREGhRWRApsY8E1DhRRhQp2hBr@W9G@V@zkkSPPkgdHPyxsO19@tt18WoPNAxIFn6LLAxHuEemG/LDxDP2QQMcCY8GPMab/zzS/7tNzjcUci2stS1V@AQ "Perl 5 – Try It Online") [Answer] # PHP, 159 bytes pattern taken from mazzy; translated to 1-2-3, converted to base26 -> decoded by the program ``` while($y<$argv[2]*10+2)echo str_pad("",$argv[1]*10+2,strtr(base_convert([jng1,jnnb,jng1,jofn,k333,"1h4p5",23814,k94d,k02h,jnnb][$y++%10],26,4),312,"\ /"))," "; ``` requires PHP 5.5 or later. Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/bc42dffa84c94143ef2018a1a4d1a1aeea5d92e0). calculating may be shorter (as it was for Arnauld). I may look into that. [Answer] # [Kotlin](https://kotlinlang.org), ~~196~~ 135 bytes Saved 61 bytes thanks to ASCII-only's suggestion to use AZTECCO's C++ algorithm. ``` {h,w->var r="" for(l in 9..h*10+10){for(c in 9..w*10+10){r+=when{(l%10+c%10)%8==5->'/' (l%10-c%10+8)%8==4->'\\' else->' '}} r+='\n'} r} ``` [Try it online!](https://tio.run/##7VhLc9s2EL7rVyCeSSzVEmX5kdiayjPOo61n2qYTu9Np6x4gEhLRgAQDUpZdy789/XZBkFJi1@mht/IgE4vdxWIf3y793lZG5x@HQ/HKKVmpRMysE1WqSxHbRIm5NTMRp9IYlc/VuAPGtKqKcjwc0j5tR2Ul4/fqGlxgiWKbDT8sVFlpm5fD0YvD56NjEnvt5NIrTrTMbJ6IQlaVcjltXqRKTJWxy0AUS20M2ZJBBnuyhKCdsQISaEyKOrTkZ3jZvF4O76HiN7zzDy@Gl40Ir/EnyAUdTGgUXq69338OUen9W32lciFzofNiUeFGSZVimYhU6Xla9YWScSpOJqO@sIsKLCREt5VTe6XE6fmrszMhXdX4xKnCx6hKZSUymd@whM5U2Rd/Wp3rfC66dALknZFFAUJPgJe0lhlcRgK1/0vvum8Qb3Uts8KoPixzSsDTa0bDZm/5ROyR9ZwCfAFQRuN19wtxjysCccNVn3MOaz/fE6aHA/Zw6B4I4v3hFPcF9gvt3uQk6nef@9C7b38t@OTNB3z3yBmP2PWYZx/18Zd4@0v8/mgEHovFI1H5137434v/pRdp/93CqJKT/Gz4tk7ugTjjImBUYpQTMSpjitbC8Di9ETWO0RPbHEStcsCbqlKbREHLr3bBgoXT2NSANCvOL16//flCAMCcqhYASJAlDAjaZos8pjaE7XJhqkbXG4CackKCAU2mcHbuZEZqZCsinQpqZByropJToxoNpznMzuwCpqApqevKyVzZRSmWqa5UWciYIOBzBX1RWmEsYBp2EiijjzkZA91LgT6sxKJohAoYhtsC8M1Nc/B5BUdKl0CJLVLL/gbcoFFOdZKovGG8oE5bd/EBd3GcjAYgFuVCGu7r1C0chWztSHPT51Bxw0itw2UqPwl0NQUL6x4ALa@bx@RfPyT15rrAGehj6FIlOZsbuxJGZtNE@p6DMSJDGpR8oZeyBDdFxcytw3ZGeXP628WbV6/eRutDyXK5jEpr4Bjpcp5FfnJ2po0a7h/vHx/v7n06wXzCHV/F3x79cv7j8bn9EAaT0H7hzUwmFCMyWIrR7vVot9mlnkwS4Gr6tEd@btBkPfd7DjNf2PMH@bXe4OXreceWimXKCJVEAlMLnYl2ihPVp9FMO4pTSCbKZT7H52CuFHkbFYOY6zKlOrGzWZ@y1ZDbIQuzGzaSwVDnqpqRPbzaHe3tHxw@f3F0vMJ6sDNonh2sd1ctJND@aNUiCK33Vi100np/1YIXrQ9WLR7S@nDVYh@tn69axKP1i1ULcLQ@@uT840/O37S3mTkxV8brAUYOFJaTDb5fWpqV5jaXPDdxFLjeKY7sduuWVIwUuymGYF6U8Gfqi4pm6edrNR7xoRyZZzjKLDIAmvWjckCcach1OsApI3k31UVTJevi7Qzn7WktGAck@MEmSNUN6cIAqrINulcXkACeUB4kDymXRvuEHiRwVPNn4kYrk5TicNOCTS/8kw2Zzh8xgq08WrPlgG3Z@8yWIFCbdBB1AOOE67Eqyy4X4RjFU/XrAuNFbwwwdYSBt50OMmUIoq60NPovVfuemgbHluLYFq/m2HgZz0Ra6iTqh3PZsghcV9IFXROxtQUKqesGVcdR5K36arS7M9rteXNY@Tfh2DpVdL5m2MaZMkmCEHHUldziAbpNYuMFISro/H0RsQCb0qqHMeyu1hZfg7X9OxNABpp2bWJr5lrIkTEerhoWvupTaPTn4K339AitA5yDE7E93N7Q9nIzgxD0B9QNGnU7R7XCA1Z4ebmp8Zza8VgodJsbYTmTjI25rlqtygBnSVps17Q7kqXrdpoVvNUE5zRJal8vfVoAXgk9jKqU/84lqj@gdd/2ZU76G20ijC6epcMbdQZxYf0gdd6MKO23efv5S6megakr3bwci1Pn5M3XPrNPek1uf@9bK2ycq1w5WfkcrxPIpylGobHocp1QfZA36gqZeCWj/UM/AkQfb9P@cnDCqT1BTsOwrgnZXCfPLRHjkFWB6HYm5NPbruGM8MkwmRwOTigRmDqIQ0wnkwPQKZ4UHryK7bu7DlSQG/Fy95HtukBccTOnpA9JgoablwyqsxqXwkXFOzB1mkKhEGEmK4zmXofR0oqldUnpp6BMFr4Dewne8Uz4UXNG9DPGIMxgNIdRywCgA0euapnAuI4Lklo8/49EJev930s0Ey7GZer5PLX5tI3RG6Aplgskq8w9v7qm6bJO5gqu8EVL8eTvzxKwQ675Hnft9p48ifi63S2x1YvogrdNDegqqixC3@2JOybqGY19pCMqCRYn9D@AZ89qvb/v/iFOJmIESqvC74z8Tq@m85VM3i26jWS/Ze15NgpxzV@lzi7FGVJ8Ls2pmzNwvQn37G69RKC9@JOtXp3hb/PWE31fiaiKDTgWiZpJVFnfS1CEg7MjLkqAAtC2q5yzboxeDStoag84GK6xdn4f8zRVSK2Z7dm88V5f7PENubQRH1/jVLIf/wY "Kotlin – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~194~~ ~~192~~ ~~187~~ 127 bytes @ASCII-only's solution: ``` lambda w,h,n=10:"\n".join("".join([" /","\\"][(j%n-i%n)%8==4][(j%n+i%n)%8==5]for i in range(-1,w*n+1))for j in range(-1,h*n+1)) ``` [Try it online!](https://tio.run/##VcnRCsIgFIDhVzkcELS5ylYQgU8yd2GUeaSOQwajp7diddHVz8c/PqeYuavBunr3j/PFw6yjZmu2J3SM65SJJX7bI2xQo3M49DIJbkmwEkdr94ubnw9DyAUIiKF4vl1la/S84sYo9Rnpb8Rl1LEQTzLITu/eegE "Python 3 – Try It Online") --- Original Solution ``` n="\n" def f(w,h):a=[r" /\ "*w,r" \/ "*w,r" \ / "*w,r" \ / "*w,r"\/\ /"*w+r"\/"];return a[0]+n+n.join(([i.translate({47:92,92:47})for i in a]+a[::-1])*h)+n+a[1] ``` [Try it online!](https://tio.run/##VctLCsMgEIDhfU8hrjTapHlAiCUnURdCI7GESbCWUErPbk3Iop3FwDfDv7zCOEMdI/RYAT7dBossWflIhemlx2ibQqWFs5UfVsWf07f4sdqTw2pvt0My24z11Q/h6QEZedEMGOT32QEh0uXBG3hMJgzk3bSiq3hXiab9UDt75JBLiWZGCnEuNc1GmmIjSx0X7yAQS2peURq/ "Python 3 – Try It Online") -2 bytes thanks to @Black Owl Kai showing that the tops and bottoms can be accessed from the generated array instead of in separate variables. -5 more bytes thanks to @Black Owl Kai using a more creative way to store the diamonds Generates this portion of each diamond: ``` /\ \/ \ / \ / \/\ /\/ ``` A `/\` added at the end of each row to complete it. Then, the `/`s and `\`s are swapped to form the top of each diamond, and the order of the lines is reversed to form the bottom half. Finally, it adds in the very top row of `/\`s and the very bottom row of `\/`s to complete the image. ]
[Question] [ # Challenge You must write a program that takes a positive integer `n` as input, and outputs the `n`th Fibonacci number (shortened as Fib# throughout) that contains the `n`th Fib# as a subtring. For the purposes of this challenge, the Fibonacci sequence begins with a `1`. Here are some examples that you can use as test cases, or as examples to clarify the challenge (for the latter, please leave a comment down below explaining what you find unclear). ``` n=1 Fib#s: 1 ^1 1st Fib# that contains a 1 (1st Fib#) Output: 1 n=2 Fib#s: 1, 1 ^1 ^2 2nd Fib# that contains a 1 (2nd Fib#) Output: 1 n=3 Fib#s: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ^1 ^2 ^3 3rd Fib# that contains a 2 (3rd Fib#) Output: 233 n=4 Output: 233 n=5 Output: 6765 n=6 Output: 28657 n=7 Output: 1304969544928657 n=8 Output: 14472334024676221 n=9 Output: 23416728348467685 n=10 Fib#s: 1, ..., 34, 55, 89, ..., 63245986, 102334155, 165580141, ..., 2880067194370816120, 4660046610375530309 ^1 ^2 ^3 ^10 10th Fib# that contains a 55 (10th Fib#) Output: 4660046610375530309 ``` --- As always, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so go for the lowest byte count possible. If something is confusing/unclear, please leave a comment. (This challenge is based off another challenge I posted: [Print the nth prime that contains n](https://codegolf.stackexchange.com/questions/80379/print-the-nth-prime-that-contains-n)) [Answer] # [Haskell](https://www.haskell.org/), ~~85~~ 84 bytes EDIT: * -1 byte: Laikoni shortened `l`. * Typo (`x>=s` for `x<=s`) in explanation. `f` takes an `Int` and returns a `String`. ``` l=0:scanl(+)1l m=show<$>l f n|x<-m!!n=[y|y<-x:m,or[x<=s|s<-scanr(:)""y,x++":">s]]!!n ``` [Try it online!](https://tio.run/##FctBDoMgEADAu69A4kGjGG1vBPyI8UAUo@myNqyNkPh32t5nNkMvC5Cc2VHveFpv5rP4IOxoqXXmXa6tt2ap2uvwCyXQnaTZIJR11UPmNG3HpYoBspXhHZRweY56jHdUIkjXHH4MStNNSvybL2XFeWxCXXPJB5qmH0@pZw/2ZH33BQ "Haskell – Try It Online") # How it works * `l` is the infinite list of Fibonacci numbers, defined recursively as the partial sums of `0:1:l`. It starts with `0` because lists are 0-indexed. `m` is the same list converted to strings. * In `f`: + `n` is the input number, and `x` is the (string of the) `n`th Fibonacci number. + In the outer list comprehension, `y` is a Fibonacci number tested for whether it contains `x` as a substring. The passing `y`s are collected in the list and indexed with the final `!!n` to give the output. An extra `x` is prepended to the tests to save two bytes over using `!!(n-1)` at the end. + To avoid counting `y`s several times, the tests of each `y` are wrapped in `or` and another list comprehension. + In the inner list comprehension, `s` iterates through the suffixes of `y`. + To test whether `x` is a prefix of `s`, we check whether `x<=s` and `x++":">s`. (`":"` is somewhat arbitrary but needs to be larger than any numeral.) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 bytes 1 byte thanks to Jonathan Allan. ``` 0µ³,ÆḞẇ/µ³#ÆḞṪ ``` [Try it online!](https://tio.run/##y0rNyan8/9/g0NZDm3UOtz3cMe/hrnZ9EE8Zwtu56v///8YA "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 99 86 bytes * [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%c3%98rjan-johansen) Saved 7 bytes: starting with `b=i=x=-1 a=1` and dropping the `x and` * [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%c3%98rjan-johansen) again saved 3 bytes: `f and n==2` to `f*(n>2)` * [Felipe Nardi Batista](https://codegolf.stackexchange.com/users/66418/felipe-nardi-batista) saved 9 bytes: economic swap `a,b=a+b,a` shorthand `f-=str(x)in str(a)`, squeezed `(n<2)*f` * [ovs](https://codegolf.stackexchange.com/users/64121/ovs) saved 13 bytes: transition from python 3 to python 2. ``` f=n=input() b=i=x=-1 a=1 while(n>2)*f:i+=1;a,b=a+b,a;x=[x,a][i==n];f-=`x`in`a` print a ``` [Try it online!](https://tio.run/##BcFNCoAgEAbQvado2Y9Btky@LiKBIyQNxCRhZKe399KXj0vmWiMELOnJbacCGAWjUQSj3oPPvZV17vq48ABjSQfQEDTZAlc0bY4B2Wwc4Ytn8eRVullyQ7Wa6Qc "Python 2 – Try It Online") Explanation: ``` f=n=int(input()) # f is number of required numbers b=i=x=-1 # i is index(counter) set at -1 # In Two-sided fibonacci, fib(-1) is 1 # and b(fib before it) i.e. fib(-2) is -1 # Taking advantage of all -1 values, x is # also set to -1 so that the `if str(...` # portion does not execute until x is set a # value(i.e. the nth fibonacci) since there # is no way -1 will be found in the number # (ALL HAIL to Orjan's Genius Idea of using # two-sided fibonacci) a=1 # fib(-1) is 1 while(n>2)*f: # no need to perform this loop for n=1 and # n=2 and must stop when f is 0 i+=1 # increment counter b,a=a,a+b # this might be very familiar (fibonacci # thing ;)) x=[x,a][i==n] # If we have found (`i==n`) the nth # fibonacci set x to it f-=`x`in`a` # the number with required substring is # found, decrease value of f print a # print required value ``` # [Python 3](https://docs.python.org/3/), 126 120 113 112 110 101 99 bytes ``` f=n=int(input()) b=i=x=-1 a=1 while(n>2)*f:i+=1;a,b=a+b,a;x=[x,a][i==n];f-=str(x)in str(a) print(a) ``` [Try it online!](https://tio.run/##FcwxCsMwDAXQ3afIaCXOoHaL@b1IyCBDTQRBNalL3dO7ZHvTK7@6v@zee4ZBrXq18qmeyCUoGmZ2AnbfXY@nt8eNxrzoBI4SEmRKQWLD2oJsqwK2xTzjXU/fSG24IOTKecVCvTP/AQ "Python 3 – Try It Online") [Answer] # Java, ~~118~~ 111 bytes ``` i->{long n=i,p=0,q,c=1;for(;--n>0;p=c,c+=q)q=p;for(n=c;i>0;q=p,p=c,c+=q)if((""+c).contains(""+n))--i;return p;} ``` I keep thinking it should be possible not to duplicate the Fibonacci bit, but all my efforts somehow result in more bytes. Thanks to Kevin for improvements... guess it shows this was my first attempt at golfing :) [Answer] # [Perl 6](http://perl6.org/), 45 bytes ``` {my@f=0,1,*+*...*;@f.grep(/$(@f[$_])/)[$_-1]} ``` `$_` is the argument to the function; `@f` is the Fibonacci sequence, lazily generated. [Answer] # JavaScript (ES6), ~~96~~ ~~93~~ ~~92~~ ~~90~~ 86 bytes 0-indexed, with the 0th number in the sequence being `1`. Craps out at `14`. ``` f=(n,x=1,y=1)=>n?f(n-1,y,x+y):x+"" g=(n,x=y=0)=>x>n?f(y-1):g(n,x+!!f(y++).match(f(n))) ``` * ~~2~~ 6 bytes saved thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) --- ## Try it ``` f=(n,x=1,y=1)=>n?f(n-1,y,x+y):x+"" g=(n,x=y=0)=>x>n?f(y-1):g(n,x+!!f(y++).match(f(n))) oninput=_=>o.innerText=(v=+i.value)<14?`f(${v}) = ${f(v)}\ng(${v}) = `+g(v):"Does not compute!" o.innerText=`f(0) = ${f(i.value=0)}\ng(0) = `+g(0) ``` ``` <input id=i min=0 type=number><pre id=o> ``` --- ## Explanation Updated version to follow, when I get a minute. ``` f=... :Just the standard, recursive JS function for generating the nth Fibonacci number g=(...)=> :Recursive function with the following parameters. n : The input integer. x=0 : Used to count the number of matches we've found. y=0 : Incremented on each pass and used to generate the yth Fibonacci number. x>n? :If the count of matches is greater than the input then f(y-1) : Output the y-1th Fibonacci number. : :Else g(...) : Call the function again, with the following arguments. n : The input integer. x+ : The total number of matches so far incremented by the result of... RegExp(f(n)).test(f(y)) : A RegEx test checking if the yth Fibonacci number, cast to a string, contains the nth Fibonacci number. : (returns true or false which are cast to 1 and 0 by the addition operator) y+1 : The loop counter incremented by 1 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 65 bytes ``` AIθνAνφA±¹βAβιAβξA¹αW∧›ν²φ«A⁺ι¹ιA⁺αβχAαβAχαA⎇⁼ιναξξA⁻φ›№IαIξ⁰φ»Iα ``` [Try it online!](https://tio.run/##VZDNCoMwEITvPsUeNzRC7VUQRHotPfQF1tSfgESaaGspffY0aYTonnY@htlhRU9ajDRYWxojO4UVmQkfjINiebIyxaGN6tJ0NDWYOU8dac1B7tQSVcaBnHr1cmgAS3XHwmeemM9l8EnAzeo9oOTgs33ajpO/x0HsOYUWGyLCtQ25NVqRfuP5MdNg/AHlgsh3DD033hRbDgVW46ym8Axypv@yMLcdGQvf@CZXLaOH5dZmmU2fNjXDDw "Charcoal – Try It Online") Link to verbose code for explanation. [Answer] # [PHP](https://php.net/), 96 bytes ``` for($f=[0,1];$s<$a=$argn;$s+=$f[$a]&&strstr($f[$i],"$f[$a]")?:0)$f[]=$f[$i]+$f[++$i];echo$f[$i]; ``` [Try it online!](https://tio.run/##JYmxCsMgFEX3fIY8gmIKZq2RDCVDl3bpFiSImJhF5SVz/7qztRUu3HPPTT7lYUw@NQ4x4oIuRTz3sNH3tDyer/ttYrIBg1tQpBdE5jUihVXNouu1hGMAo/53Ya5gncHotj1OLKG/ueuOVE3YeBWssFb14KU4LyCd9bE6mfMnxIs11rsv "PHP – Try It Online") [Answer] # Mathematica, 85 bytes ``` (i=ToString;f=Fibonacci;For[n=t=0,t<#,If[i@f@n++~StringContainsQ~i@f@#,t++]];f[n-1])& ``` **input** > > [10] > > > *-4 bytes from @JungHwan Min* **output** > > 4660046610375530309 > > > [Answer] # R, ~~77~~ 72 bytes ``` F=gmp::fibnum;i=0;d=n=scan();while(n)if(grepl(F(d),F(i<-i+1)))n=n-1;F(i) ``` This makes use of the `gmp` library for the Fibonacci number. Fairly straight foward implementation of the question. ``` F=gmp::fibnum; # Alias Fibonacci function to F i=0; # intitalise counter d=n=scan(); # get n assign to d as well while(n) # loop while n if(grepl(F(d),F(i<-i+1))) # use grepl to determine if Fib of input is in Fib# and increment i n=n-1; # decrement n F(i) # output result ``` Some tests ``` > F=gmp::fibnum;i=0;d=n=scan();while(n)if(grepl(F(d),F(i<-i+1)))n=n-1;F(i) 1: 2 2: Read 1 item Big Integer ('bigz') : [1] 1 > F=gmp::fibnum;i=0;d=n=scan();while(n)if(grepl(F(d),F(i<-i+1)))n=n-1;F(i) 1: 3 2: Read 1 item Big Integer ('bigz') : [1] 233 > F=gmp::fibnum;i=0;d=n=scan();while(n)if(grepl(F(d),F(i<-i+1)))n=n-1;F(i) 1: 10 2: Read 1 item Big Integer ('bigz') : [1] 4660046610375530309 > F=gmp::fibnum;i=0;d=n=scan();while(n)if(grepl(F(d),F(i<-i+1)))n=n-1;F(i) 1: 15 2: Read 1 item Big Integer ('bigz') : [1] 1387277127804783827114186103186246392258450358171783690079918032136025225954602593712568353 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` 1,ÆḞw/ɗ#ÆḞṪ ``` [Try it online!](https://tio.run/##y0rNyan8/99Q53Dbwx3zyvVPTlcGsx7uXPX//38TAA "Jelly – Try It Online") Heartbroken. [This](https://tio.run/##y0rNyan8//9w28Md88oPLVUGMx417nq4c9X///9NAA) is a **9** byte version that unfortunately fails for \$n = 2\$ which otherwise, I'm really proud of due to the weird chain rules and the byte saves. ## How they work ``` 1,ÆḞw/ɗ#ÆḞṪ - Main link. Takes n on the left ɗ - Group the previous three links into a dyad f(k, n): , - Pair; [k, n] ÆḞ - n'th Fib; [fib(k), fib(n)] / - Run the previous dyad over the list with fib(k) on the left and fib(n) on the right: w - Index of fib(n) in fib(k)'s digits or 0 1 # - Count up k = 1, 2, 3, ..., until n integers return true for f(k, n) and return those k ÆḞ - n'th Fib for each Ṫ - Return the last value ``` And the version that fails for \$n = 2\$: ``` ÆḞw¥#ÆḞ⁺Ṫ - Main link. Takes n on the left ÆḞ - Yield the n'th Fibonacci number, x ¥ - Group the previous 2 links together as a dyad f(k, x): ÆḞ - k'th Fibonacci number w - Index of x in fib(k)'s digits else 0 # - Count up k = n, n+1, n+2, ... until n integers return true for f(k, x) and return those k ⁺ - Redo the previous link (ÆḞ), yielding the k'th Fibonacci number for each k returned by # Ṫ - Take the last k ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~15~~ 13 bytes ``` !fȯ€d!¹İfQdİf ``` [Try it online!](https://tio.run/##yygtzv7/XzHtxPpHTWtSFA/tPLIhLTAFSPz//98cAA "Husk – Try It Online") ``` !⁰fȯ€od!⁰İfQdİf !⁰ # get the input-th element of f İf # fibonacci numbers that satisfy: ȯ€ Qd # one of the subsets of their digits is od # the digits of !⁰ # the input-th element of İf # the fibonacci series ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` µNÅfDIÅfå ``` -2 bytes thanks to *@ovs*. [Try it online](https://tio.run/##yy9OTMpM/f//0Fa/w61pLp5A4vDS//@NAQ) or [verify the first 10 test cases](https://tio.run/##yy9OTMpM/R/i6mevpPCobZKCkr2fS@j/Q1v9DremuUQAicNL/9fq6B3a@h8A). **Explanation:** ``` µ # Loop until the counter_variable is equal to the (implicit) input: # (the counter_variable is 0 by default) N # Push the loop index Åf # Pop and push the index'th Fibonacci number D # Duplicate it IÅf # Get the input'th Fibonacci number å # Check that the index'th Fibonacci nr contains the input'th Fibonacci nr # (if this is truthy, implicitly increase the counter_variable by 1) # (after the loop, the top of the stack - the last index'th Fibonacci number # we've duplicated - is output implicitly as result) ``` [Answer] ## Clojure, 99 bytes ``` (def s(lazy-cat[0 1](map +(rest s)s)))#(nth(filter(fn[i](.contains(str i)(str(nth s %))))s)(dec %)) ``` A basic solution, uses an infinite sequence of Fibonacci numbers `s`. [Answer] # C#, 35 bytes ``` int u=1,b=1;for(;b<n;){b+=u;u=b-u;} ``` **Try it** ``` int n=int.Parse(t2.Text);int u=1,b=1;for(;b<n;){b+=u;u=b-u;t.Text+=b.ToString()+" ";}if(b==n){t.Text+="true";} ``` [Answer] # [NewStack](https://github.com/LyamBoylan/NewStack/), 14 bytes ``` N∞ ḟᵢfi 'fif Ṗf⁻ ``` ## The breakdown: ``` N∞ Add all natural numbers to the stack ḟᵢ Define new function will value of input fi Get the n'th Fibonacci number for ever element n 'fif Remove all elements that don't contain the (input)'th Fibonacci number Ṗf⁻ Print the (input-1)'th element ``` **In English:** *(with example of an input of 3)* `N∞`: Make a list of the natural numbers `[1,2,3,4,5,6...]` `ḟᵢ`: Store the input in the variable `f` `[1,2,3,4,5,6...]` `fi`: Convert the list to Fibonacci numbers `[1,1,2,3,5,8...]` `'fif`: Keep all elements that contain the `f`th Fibonacci number `[2,21,233...]` `Ṗf⁻`: Print the `f-1`th element (-1 due to 0-based indexing) `233` [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~16~~ ~~15~~ 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Would be 11 bytes but for a bug in Japt. ``` @µX¦skN}f!gM ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QLVYpnNrTn1mIWdN&input=OA) ]
[Question] [ ***See also: [Rotatagons](https://codegolf.stackexchange.com/questions/92431/hexagolf-rotatagons)*** ## Challenge Given a string as input, output its wordagon. ## Wordagons A wordagon is a way of representing a string in a hexagon. Now, let's create a wordagon from the string `hexa`: Firstly, you start with the first character in the string a place it in the centre: ``` h ``` Then, you take the next character in the string and add a hexagonal layer: ``` e e e h e e e ``` Then, add the next layer: ``` x x x x e e x x e h e x x e e x x x x ``` Finally, add the last layer: ``` a a a a a x x x a a x e e x a a x e h e x a a x e e x a a x x x a a a a a ``` And you now have the wordagon for the string `hexa`. ## Examples Here's some I prepared earlier: **`hello`** ``` o o o o o o l l l l o o l l l l l o o l l e e l l o o l l e h e l l o o l l e e l l o o l l l l l o o l l l l o o o o o o ``` **`PPcg`** ``` g g g g g c c c g g c P P c g g c P P P c g g c P P c g g c c c g g g g g ``` **`o *`** ``` * * * * * * o * * * * * * ``` **`(T_T)`** ``` ) ) ) ) ) ) T T T T ) ) T _ _ _ T ) ) T _ T T _ T ) ) T _ T ( T _ T ) ) T _ T T _ T ) ) T _ _ _ T ) ) T T T T ) ) ) ) ) ) ``` Note that trailing and/or leading newlines are allowed. ## Winning The shortest code in bytes wins. [Answer] # Python 2, 83 bytes ``` s=input() l=len(s) while 1:l-=1;y=abs(l);print' '*y+' '.join(s[:y:-1]+s[y]*y+s[y:]) ``` Prints the wordagon and then crashes (which only prints to STDERR). Example: ``` % python2.7 wordagon.py <<<'"abcde"' 2&>/dev/null e e e e e e d d d d e e d c c c d e e d c b b c d e e d c b a b c d e e d c b b c d e e d c c c d e e d d d d e e e e e e ``` xnor saved 5 bytes. Thanks! [Answer] # Vim, 92 bytes ``` :se ri|s/./ &/g ⓋCⓇ"Ⓓ␛$vpmlmrqqYpi ␛`ljxxhmlylv`rjlmr:s/\%V\(.\)./Ⓡ" /g @qq@qVdy2G:g/^/m0 Gp ``` Circled letters represent `Control` + letter; ␛ is escape. [![asciicast](https://asciinema.org/a/dp051rq4ssn6mhtxh9kndeyo7.png)](https://asciinema.org/a/dp051rq4ssn6mhtxh9kndeyo7) [Answer] # Mathematica ~~100~~ 219 bytes If ASCII-Art need not be Terminal-Art this should be valid. My earlier submission mistakenly drew a star rather than a hexagon. I can't see how I was so off! ``` c = CirclePoints@6; f@s_:=Graphics[{Text[s~StringPart~1,{0,0}],Flatten@Table[Text[StringPart[s,n+1],#]&/@Subdivide[Sequence@@#,n]&/@Partition[Riffle[(n)CirclePoints@6,RotateLeft[n CirclePoints@6]],2],{n,1,StringLength@s-1}]},BaseStyle->20] ``` `CirclePoints@6` returns the vertices of a unit hexagon, assuming that the center is at the origin. `Subdivide`ing the coordinates for neighboring vertices finds equally spaced positions along the respective edge. A counter from 1 through the `StringLength -1` of the input string allows each layer of the wordagon to be handled separately. As `n` increases, so does the respective distance of each vertex from the origin. `Text[s~StringPart~1,{0,0}]` prints the first letter of the input at the origin. --- f@"Wordagon" [![wordagon](https://i.stack.imgur.com/qGkXj.png)](https://i.stack.imgur.com/qGkXj.png) --- For the curious, this is what the star version looked like. I know, it was *way* off the mark. It only showed the letters at the hexagon's vertices. ``` Graphics@Table[Text[Style[StringPart[#, r + 1], 54], r {Cos@t, Sin@t}], {t, 0, 2π, π/3}, {r, 0, StringLength@# - 1}] &["Hexa"] ``` [![hexa](https://i.stack.imgur.com/TIBaJ.png)](https://i.stack.imgur.com/TIBaJ.png) [Answer] # Ruby, 82 bytes ``` ->s{n=s.size-1 (r=-n..n).map{|i|(" "*k=i.abs)+r.map{|j|s[[k+j,k,-j].max]}*" "}*$/} ``` iterates through `1-n..n-1` in both i=y and j=x directions. Without the leading spaces on each line, the output looks like the below, as a result of picking a character from `s` with the index `[[i.abs+j,i.abs,-j].max]`. Adding leading spaces forms the required hexagon. ``` f f f f f l l l f f l o o l f f l o G o l f f l o o l f f l l l f f f f f ``` **Ungolfed in test program** ``` f=->s{ n=s.size-1 n=string length - 1 (r=-n..n).map{|i| iterate from -n to n, build an array of lines (" "*k=i.abs)+ k=i.abs. Start each line with k spaces. r.map{|j| iterate from -n to n, build an array of characters. s[[k+j,k,-j].max] select character from s (store null string in array if index past end of string) }*" " concatenate the array of characters into a line, separated by spaces }*$/ concatenate the array of lines into a single string, separate by newlines } puts f[gets.chomp] ``` **Typical output** ``` f f f f f l l l f f l o o l f f l o G o l f f l o o l f f l l l f f f f f ``` [Answer] ## JavaScript (ES6), 118 bytes ``` s=>[...Array((l=s.length-1)*2+1)].map((_,i,a)=>a.map((_,j)=>s[Math.max(i-l,l-i,j-l,i-j,l+l-i-j)]||``).join` `).join`\n` ``` Where `\n` represents the literal newline character. Based on my answer to [Hexplosive ASCII-art challenge](https://codegolf.stackexchange.com/questions/92194/hexplosive-ascii-art-challenge) although parts of the solution resemble @LevelRiverSt's Ruby answer. The various components of the `Math.max` produce the following output for `l=3`: ``` i - l l - i j - l i - j l + l - i - j - - - - - - - 3 3 3 3 3 3 3 - - - 0 1 2 3 0 - - - - - - 6 5 4 3 2 1 0 - - - - - - - 2 2 2 2 2 2 2 - - - 0 1 2 3 1 0 - - - - - 5 4 3 2 1 0 - - - - - - - - 1 1 1 1 1 1 1 - - - 0 1 2 3 2 1 0 - - - - 4 3 2 1 0 - - 0 0 0 0 0 0 0 0 0 0 0 0 0 0 - - - 0 1 2 3 3 2 1 0 - - - 3 2 1 0 - - - 1 1 1 1 1 1 1 - - - - - - - - - - 0 1 2 3 4 3 2 1 0 - - 2 1 0 - - - - 2 2 2 2 2 2 2 - - - - - - - - - - 0 1 2 3 5 4 3 2 1 0 - 1 0 - - - - - 3 3 3 3 3 3 3 - - - - - - - - - - 0 1 2 3 6 5 4 3 2 1 0 0 - - - - - - ``` The maximum value is taken, and the values greater than `l` are removed, thus producing the hexagon shape, while the remaining values map to characters from the string: ``` 6 5 4 3 3 3 3 3 3 3 3 a a a a 5 4 3 2 2 2 3 3 2 2 2 3 a x x x a 4 3 2 1 1 2 3 3 2 1 1 2 3 a x e e x a 3 2 1 0 1 2 3 3 2 1 0 1 2 3 a x e h e x a 4 3 2 1 1 2 3 3 2 1 1 2 3 a x e e x a 5 4 3 2 2 2 3 3 2 2 2 3 a x x x a 6 5 4 3 3 3 3 3 3 3 3 a a a a ``` [Answer] # Pyth - 29 bytes ``` j+_K.e+*kdjdjF+*bhk*L2>zhkztK ``` [Test Suite](http://pyth.herokuapp.com/?code=j%2B_K.e%2B%2akdjdjF%2B%2abhk%2aL2%3EzhkztK&test_suite=1&test_suite_input=hello%0APPcg%0Ao+%2a%0A%28T_T%29%0AWordagon&debug=0). [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 31 bytes ``` R.pvy`¹gN-©×NFs.ø}Sðý®ð×ì})¦«» ``` **Explanation** Utilizing symmetry to only generate the top part of the hexagon, then mirroring that to form the lower part. ``` R.pv } # for each prefix of the reversed string # ['f', 'fl', 'flo', 'floG'] y` # split into chars, ex: 'f', 'l', 'o' ¹gN-©× # repeat the last char len(input)-N times, # where N is the 0-based list index of the current prefix # ex: 'oo' NF } # N times do s.ø # surround current char with the next char on stack # ex: 'floolf' Sðý # insert spaces between each letter, ex: 'f l o o l f' ®ð×ì # prefix string with len(input)-N spaces # ex: ' f l o o l f' ) # wrap all strings in a list ¦ # create a reversed copy of the list and # remove the first item (as we only need the middle once) «» # concatenate the lists and merge with newlines ``` [Try it online!](http://05ab1e.tryitonline.net/#code=Ui5wdnlgwrlnTi3CqcOXTkZzLsO4fVPDsMO9wq7DsMOXw6x9KcOCwqbCq8K7&input=aGVsbG8) [Answer] ## Python 2, 104 bytes ``` def f(s): for n in range(len(s)*2-1):x=abs(n-len(s)+1);print' '*x+' '.join(s[x+1:][::-1]+s[x]*x+s[x:]) ``` [Answer] # PHP - 202 bytes ``` $w=$argv[1];$l=$i=$a=strlen($w)-1;while(-$l<=$i){$s=join(" ",str_split(str_repeat($w[$l],($a-1)/2).substr($w,$a?$a:1,$l+1),1));echo str_pad("",$a).strrev($s).($a%2?" ":" {$w[$a]} ")."$s ";$a=abs(--$i);} ``` Usage from command line: ``` php.exe -r "put the escaped code here" "put your desired word here" ``` for example: ``` php.exe -r "$w=$argv[1];$l=$i=$a=strlen($w)-1;while(-$l<=$i){$s=join(\" \",str_split(str_repeat($w[$l],($a-1)/2).substr($w,$a?$a:1,$l+1),1));echo str_pad(\"\",$a).strrev($s).($a%2?\" \":\" {$w[$a]} \").\"$s\n\";$a=abs(--$i);}" "example" ``` [Test Suite](http://codepad.org/wXarmGNO). ]
[Question] [ Here is some example input, so I can explain what the problem is: ``` ((1 2)(3 (4 5) moo)) (i (lik(cherries)e (woohoo))) ``` Think of this line of text as a topographic map of some mountains. Each set of parentheses illustrates one unit of altitude. If we "view" this from the side, so that we see the mountains vertically, we will see: ``` 4 5 cherries woohoo 1 2 3 moo lik e i ``` Given one of these topographic maps, output the map, but on a vertical scale, like the output above. Seperate the different items in the map with the number of characters to the next item. For example, there are 4 spaces in the output between `moo` and `i`. Likewise, there are 4 characters in the input between `moo` and `i`. The code which does this in the least amount of characters wins. [Answer] ## J, 87 79 72 70 67 57 56 characters ``` '( ) 'charsub|.|:(+/\@('('&=-')'&=)(],~' '$~[)"0])1!:1[1 ``` Takes input from the keyboard. Example: ``` '( ) 'charsub|.|:(+/\@('('&=-')'&=)(],~' '$~[)"0])1!:1[1 ((1 2)(3 (4 5) moo)) (i (lik(cherries)e (woohoo))) 4 5 cherries woohoo 1 2 3 moo lik e i ``` Explanation: This explanation is based on the first version of my program: ``` |.|:('( ) 'charsub x)((' '$~{.@]),[{~{:@])"1(('('&([:+/=)-')'&([:+/=))\,.i.@#)x=.1!:1[1 ``` `x=.1!:1[1` take input from keyboard and put it into `x` for later `(('('&([:+/=)-')'&([:+/=))\,.i.@#)` creates a list of all indeces into the string (`i.@#`) and stitches (`,.`) it together with the result of the `(('('&([:+/=)-')'&([:+/=))\` verb. `(('('&([:+/=)-')'&([:+/=))\` this verb is applied to all the prefixes of the string (so on input `hello` it would apply to `h`,`he`,`hel`,`hell`, and `hello`. It is a [fork](http://www.jsoftware.com/help/learning/09.htm), which counts the number of open brackets `('('&([:+/=)` and then subtracts the number of close brackets `')'&([:+/=)`. This gives me list of indeces into the string and the level the character at that index should be at in the output. On simple input this gives me the following: ``` (('('&([:+/=)-')'&([:+/=))\,.i.@#)x=.1!:1[1 (one(two(three))) 1 0 1 1 1 2 1 3 2 4 2 5 2 6 2 7 3 8 3 9 3 10 3 11 3 12 3 13 2 14 1 15 0 16 ``` `((' '$~{.@]),[{~{:@])"1` this is a verb which takes the list I just generated and also the output of `('( ) 'charsub x)` (which just does a string replacement to replace all brackets with spaces in `x`). It takes the tail of each item of the list `{:@]` and uses it as an index into the string to get the character `[{~{:@]`. Then it prefixes it `,` with the number of spaces as indicated by the head of each item in the list`(' '$~{.@])`. On the previous example this gives me: ``` ('( ) 'charsub x)((' '$~{.@]),[{~{:@])"1(('('&([:+/=)-')'&([:+/=))\,.i.@#)x=.1!:1[1 (one(two(three))) o n e t w o t h r e e ``` I then transpose the array `|:` and reverse it `|.` to get the desired output. [Answer] ## GolfScript 69 ``` 0:§;{.'()'?))3%(.§+:§' ':s*\@s\if\n}%n/.{,}%$)\;:μ;{.,μ\-s*\+}%zip n* ``` Online demo [here](http://golfscript.apphb.com/?c=OycoKDEgMikoMyAoNCA1KSBtb28pKSAoaSAobGlrKGNoZXJyaWVzKWUgKHdvb2hvbykpKScKCjA6wqc7ey4nKCknPykpMyUoLsKnKzrCpycgJzpzKlxAc1xpZlxufSVuLy57LH0lJClcOzrOvDt7LizOvFwtcypcK30lemlwIG4q&run=true). Explanation: ``` 0:§; # declare the variable §, representing the # current vertical level and initialize it at 0 { # iterate for each char in the string: .'()'?))3% ( # add on the stack the amount by which # the current vertical level should be # adjusted: # * +1 if the character is '(' # * -1 if the character is ')' # * 0 otherwise .§+:§ # adjust the value of § ' ':s* # add as many spaces as § tells us # and save the space in variable s \@s\if\ # return current char, if it's printable, # or a space if it's '(' or ')' n # add a newline char }% n/ # split by newline char; now we have # an array of strings on the stack. # Each string is a vertical line of the # final output. .{,}%$)\;:μ; # Iterate through the strings and find the # maximum length { .,μ\-s*\+ # Add spaces at the end to make all the strings # the same length }% zip # Transpose the strings n* # Join the transposed strings by newline characters ``` [Answer] ## APL (59) ``` ⊖↑{⊃,/T\¨⍨⍵×P=0}¨R∘=¨(⍴T)∘⍴¨⍳⌈/R←1++\P←+/¨1 ¯1∘ר'()'∘=¨T←⍞ ``` I have assumed that the 'base' needs to be usable as well. (i.e. `(a(b))c(d)` is valid). If this is not necessary two characters can be saved. Explanation: * `T←⍞`: store a line of input in T * `'()'∘=¨T`: for each character in T, see if it is an opening or closing parenthesis. This gives a list of lists of booleans. * `1 ¯1∘ר`: multiply the second element in each of these lists by -1 (so an opening parenthesis is 1, a closing one is -1 and any other character is 0). * `+/¨`: take the sum of each inner list. We now have the ∆y value for each character. * `P←`: store in P. * `R←1++\P`: take a running total of P, giving the height for each character. Add one to each character so that characters outside of the parentheses are on the first line. * `(⍴T)∘⍴¨⍳⌈/R`: for each possible y-value, make a list as long as T, consisting of only that value. (i.e. 1111..., 2222...., etc.) * `R∘=¨`: for each element in this list, see if it is equal to R. (For each level, we now have a list of zeroes and ones corresponding to whether or not a character should appear on that level). * `⍵×P=0`: for each of these lists, set it to zero if P is not zero at that spot. This gets rid of the characters with a non-zero delta-y, so that gets rid of the parentheses. * `⊃,/T\¨⍨`: for each depth, select from T the characters that should appear. * `⊖↑`: create a matrix and put it right-side-up. [Answer] ## Tcl, 50 ``` puts \33\[9A[string map {( \33\[A ) \33\[B} $argv] ``` Kind of cheating, but well.. I use ascii escape sequences to get the line difference, `^[[A` means move the curser 1 line up, `^[[B` is move curser 1 line down. [Answer] # APL, 41 chars/bytes\* ``` {⊖⍉⊃(↑∘''¨-⌿+/¨p∘.=,\⍵),¨⍵/⍨1-2×⍵∊p←'()'} ``` Tested on Dyalog, with a `⎕IO←1` and `⎕ML←3` environment. It's a function that takes the required input and returns the output. Given the question's wording, I believe it's acceptable. In case it's not, here is a version that reads from stdin and writes to stdout, for 4 chars more: ``` ⍞←⊖⍉⊃(↑∘''¨-⌿+/¨'()'∘.=,\a),¨a/⍨1-2×'()'∊⍨a←⍞ ``` **Explanation**: ``` { p←'()'} p is the string made of two parentheses ⍵∊ ______ check which characters from ⍵ are parens 1-2× ________ -1 for every par., 1 for every other char ⍵/⍨ ____________ replace () with spaces in the orig. string ( ),¨ _______________ append every char to the following items ,\⍵ _____________________ for every prefix of the original string p∘.= ________________________ check which chars are '(' and which ')' +/¨ ____________________________ sum: compute the number of '(' and ')' -⌿ _______________________________ subtract the no. of ')' from that of '(' ↑∘''¨ _________________________________ generate as many spaces as that number ⊖⍉⊃ ____________________________________ make it into a table, transpose and flip ``` **Examples:** ``` topo '((1 2)(3 (4 5) moo)) (i (lik(cherries)e (woohoo)))' 4 5 cherries woohoo 1 2 3 moo lik e i ```   ``` topo 'a ( b ( c(d)e ) f ) g' d c e b f a g ``` \*: APL can be saved in a variety of legacy single-byte charsets that map APL symbols to the upper 128 bytes. Therefore, for the purpose of golfing, a program that only uses ASCII characters and APL symbols can be scored as chars = bytes. [Answer] ## J, 56 chars ``` '( ) 'charsub|.|:((,~#&' ')"0[:+/\1 _1 0{~'()'&i.)1!:1]1 ``` Another 56-character J solution... I count depth by translating `(` into ⁻1, `)` into 1 and all other characters into 0, and then taking the running sum of this: `[: +/\ 1 _1 0 {~ '()'&i.`. The rest is largely similar to @Gareth's solution. [Answer] ## Python, 161 chars ``` S=raw_input() R=range(len(S)) H=[S[:i].count('(')-S[:i].count(')')for i in R]+[0] for h in range(max(H),0,-1):print''.join((' '+S[i])[H[i]==H[i+1]==h]for i in R) ``` [Answer] # Python, 130 ``` a=[""]*9 l=8 i=0 for c in raw_input():o=l;l+=c==')';l-=c=='(';a[l]=a[l].ljust(i)+c*(o==l);i+=1 print"\n".join(filter(str.strip,a)) ``` [Answer] ## Ruby 1.9 (129) Reads from stdin. ``` l=0 $><<gets.split('').map{|c|x=[?(]*99;x[l+=c==?(?-1:c==?)?1:0]=c;x}.transpose.map(&:join).*(?\n).tr('()',' ').gsub(/^\s+\n/,'') ``` [Answer] ## C, 132 characters ``` char*p,b[999];n; main(m){for(p=gets(memset(b,32,999));*p;++p)*p-41?*p-40?p[n*99]=*p:++n>m?m=n:0:--n; for(;m;puts(b+m--*99))p[m*99]=0;} ``` The description failed to specify how much input the submission had to accept in order to be accepted, so I settled on limits that were most consistent with my golfing needs (while still working with the one given example input). Allow me to take this opportunity to remind folks that it's often a good idea to specify minimum maximums in your challenge descriptions. There are two main loops in the code. The first loop farms out all the non-parenthesis characters to the appropriate line of output, and the second loop prints each line. [Answer] # C, 149 chars ``` #define S for(i=0;c=v[1][i++];)h+=a=c-'('?c-')'?0:-1:1, c,i,h=0,m=0;main(int a,char**v){S m=h>m?h:m;for(;m;m--){S putchar(a||h-m?32:c);putchar(10);}} ``` run with quoted arg, e.g. a.out "((1 2)(3 (4 5) moo)) (i (lik(cherries)e (woohoo)))" [Answer] # Octave, 128 [Very similar to my last answer...](https://codegolf.stackexchange.com/a/52516/41245) ``` p=1;x=[0];y=input(0);for j=1:numel(y);p-=(y(j)==")");x(p,j)=y(j);p+=(y(j)=="(");end;x(x==40)=x(x==41)=x(x==0)=32;char(flipud(x)) ``` ### Test **Input:** `"((1 2)(3 (4 5) moo)) (i (lik(cherries)e (woohoo)))"` **Output:** ``` 4 5 cherries woohoo 1 2 3 moo lik e i ``` [Answer] ## C#, 229 bytes If there's no restriction on leading vertical space, you can use this (indented for clarity.) It'll initialise the cursor down one line for every `(` found before printing, then move the cursor up and down as brackets are read. ``` using C=System.Console; class P{ static void Main(string[]a){ int l=a[0].Length,i=l; while(i>0) if(a[0][--i]=='(')C.CursorTop++; while(++i<l){ char c=a[0][i]; if(c=='('){ c=' '; C.CursorTop--; } if(c==')'){ c=' '; C.CursorTop++; } C.Write(c); } } } ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~120~~ 119 bytes ``` (($h=($c=$args|% t*y)|%{($l+=(1,-1)[$_-40])})|sort)[-1]..0|%{$x=0;$y=$_ -join($c|%{"$_ "[$h[$x++]-ne$y-or$_-in40,41]})} ``` [Try it online!](https://tio.run/##Nc7BbsIwEATQe75iZS32biEogfTSKqd@Qo9RhNJgsNs0RnYqiCDfnpqiXmdGo3dyZ@2D0V034wFKuM5EaErCtsTGH8NtAcPTyLfFlbBblpSv0pwr3KVFVvPEt@D8wFWa1@t1Fkd4KbNXHEvcJemns338ianAHYgKTYWX5bJOe41j6nw8sX2RrYq8nniapySRkSCIctgwbYEKeGb4do4ZyAJ19otao723OrAGOjtn7iWLJBHvdq9BHw66HcILvJnGB5DQ9HtQ0JqmP@oARtujGaAJQH8Nr@DjZ4C9DaeuGcNaPABSRoCSW5ARoO4ApUBakBEg/wFKg3wAlFJi/gU "PowerShell – Try It Online") Side effects: Chars `&` and `'` changes height as `(` and `)`, but displays. Compare results for: ``` &$f "((1 2)(3 (4 5) moo)) (i (lik(cherries)e (woohoo)))" &$f "&&1 2'&3 &4 5' moo'' &i &lik&cherries'e &woohoo'''" ``` Less golfed: ``` $chars=$args|% toCharArray $heights=$chars|%{ $level+=(1,-1)[$_-40] # 40 is ASCII for '(', 41 is ASCII for ')' $level } $maxHeight=($heights|sort)[-1] $maxHeight..0|%{ $x=0;$y=$_ $line=$chars|%{ "$_ "[$heights[$x++]-ne$y -or $_-in40,41] } -join($line) } ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` FS≡ι(«↘»)«↗»«ι ``` [Try it online!](https://tio.run/##VY49C8IwFEXn9lc8Mr03dPBraVcXB0EUJ3EIMW2CsQlp2g7S3x5jEaHjvffAuUJxLyw3MdbW46F1fbgEr9sGiaAbdRAKNcE7zzLBOwkMWTmn7GgHieXeju1ZNypQlcrpj9ESu7ol9JA17034MackDElT5fM8xXhjiCtYE24At7AjeFmbDqEGNPqJQknvtexIAo7Wqu9I7B4LM8SicE40Hw) Link is to verbose version of code. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 145 bytes ``` x=split($0,a,b){for(;""!=e=a[++b];d+=(e=="(")-(e==")"))for(c=0;c++<x;f=f<d?d:f)z[c]=z[c](c==d?e=="("||e==")"?" ":e:" ")}END{for(;f;)print z[f--]} ``` [Try it online!](https://tio.run/##JY3NDoIwEIRfZW087KaQ@HuhbLjo1RcgHLC0oQEtARONyrNXkMtkkm@@TPlsQnjx0LXugetNVEZX@ljfoxJixYbLXMproSrJaJgFCor/hQTRPNO8UVrK9KUs27TKqsTSO9cFzzFRrrLF@34XLRMgEpNMSeP5clq@rKKud/cHvHMbx8UYAuIWdoR7wAMcCW7eEwE6wNY1qGvT984MZACf3tczpB8 "AWK – Try It Online") This code takes advantage of the spacing rules of the contest, which makes it possible to process single characters and build up a set of output lines one character at time. For each character in the input string, one character is appended to all the output lines. All but one line get (space) characters. Only the line associated with the current topological height get a non-space character. Here's a breakdown... ``` x=split($0,a,b){ ... } ``` The input line is split into a character array stored in `a` with the number of characters found saved in `x`. ``` for(;""!=e=a[++b];d+=(e=="(")-(e==")")) ``` The code block is one statement, a `for` loop with one statement, which is also a `for` loop. The outer loop just iterates over all the characters. The top of loop test `""!=e=a[++b]` stores the current character in `e` to save some characters later. The annoying `""!=` check is needed to keep AWK from bailing if a `0` is included in the input... The "end of loop" statement `d+=(e=="(")-(e==")"` increments and decrements the `d` topological depth indicator. ``` for(c=0;c++<x;f=f<d?d:f) ``` The inner `for` loop appends a character to all the output strings the code is assembling. It uses `x` (the number of characters in the input string) as the upper bound for the number of strings to construct since we don't know now many parenthesis are in the input. That's at least 2x too large, but the code is shorter if we just assemble lines that are never used. The "end of loop" statement `f=f<d?d:f` just sets `f` to the maximum topological depth the code sees, which is used to figure out how many lines to print out later. ``` z[c]=z[c](c==d?e=="("||e==")"?" ":e:" ") ``` The body of the inner loop just appends a character to the current output string `z[c]`. The input character is appended only if the current line matches the topological depth, and the character isn't a paren. ``` END{for(;f;)print z[f--]} ``` One all the characters have been processed, the code just prints all the assembled lines up and including the largest topological depth reached while parsing the input. [Answer] ## VB.net (For S&G) Not the prettiest of code. ``` Module Q Sub Main(a As String()) Dim t = a(0) Dim h = 0 For Each m In (From G In (t.Select(Function(c) h += If(c = "(", 1, If(c = ")", -1, 0)) Return h End Function).Select(Function(y, i) New With {.y = y, .i = i})) Group By G.y Into Group Order By y Descending Select Group.ToDictionary(Function(x) x.i) ).Select(Function(d) New String( t.Select(Function(c,i)If(d.ContainsKey(i),If(c="("c Or c=")"c," "c,c)," "c)).ToArray)) Console.WriteLine(m) Next End Sub End Module ``` ]
[Question] [ In this challenge, you'll create some programs which behave similarly to genes. When you run one, it will return one of its two "alleles" (a half of its source code), and concatenating any two alleles from your programs will result in a new, functioning program (which returns its own alleles). As an example, say you write two programs, \$A\$ and \$B\$. These in turn each consist of two "alleles", \$A\_0A\_1\$ and \$B\_0B\_1\$. Running \$A\$ would return either \$A\_0\$ or \$A\_1\$ randomly, and \$B\$ would return \$B\_0\$ or \$B\_1\$. Combining any two of these alleles should form a program \$C\$. For example, \$A\_0B\_0\$, when run, should return one of \$A\_0\$ or \$B\_0\$, similarly to its parents. If \$C\$ was instead \$A\_1B\_0\$, it'd return one of those two alleles instead. One possibility if you had multiple generations, starting with three programs, could look like this: [![There are three initial programs, A, B, and C. Two programs are formed in the next generation, A0C1 and B1C0. These then form a third program (in a third generation), B1C1.](https://i.stack.imgur.com/U1Y5pm.png)](https://i.stack.imgur.com/U1Y5pm.png) ## Rules You must write at least two genetic quines, with each initial one having two unique alleles (the total number of unique alleles should be twice the number of initial programs). All permutations of alleles must form a functioning genetic quine. A genetic quine takes no input when run, and returns the source code of one of its two alleles, randomly. It consists only of the code in its two alleles, concatenated. For example, if `print(xyz)` and `if 1` were two alleles, `print(xyz)if 1` and `if 1print(xyz)` should both work. Note that standard quine rules must be followed, so the genetic quines should not read their own source code, and alleles should be non-empty. The random choice must have a uniform probability of choosing either quine, and the quines must follow standard rules (so non-empty). You may not use the current time (directly) or some undefined behavior for randomness; a properly seeded PRNG or source of randomness should be used. ## Scoring Your score (lowest score per language wins) will be the average byte count of all of your alleles, **plus** an amount determined by \$\frac{b}{2^{n-1}}\$ (making your total score \$b+\frac{b}{2^{n-1}}\$), where \$b\$ is your average byte count and \$n\$ is the number of genetic quines you wrote. This means that writing two initial programs with four alleles would give you a "bonus" (more like a penalty) of \$\frac{1}{2}\$, three would give you \$\frac{1}{4}\$, four would be \$\frac{1}{8}\$, and so on. **This is a penalty, not a multiplier: your score will never be lower than your average byte count.** [Answer] # [Haskell](https://www.haskell.org/) + System.Random\*, score ~120 bytes. I've built a way to make an arbitrary number of alleles which grow in length at a rate of \$O(\log(n))\$ So you can add as many of them as you want to the bonus to asymptotically approach 0. I would have to do a lot of math to figure out what the exact optimum number of alleles is, but I can do at least 52. For the smallest 52: The following is the base allele: ``` ;main=randomRIO(0,1)>>=([putStr x>>print x,main]!!)where x=";main=randomRIO(0,1)>>=([putStr x>>print x,main]!!)where x=" ``` To get other alleles: * Replace all the `x`s with any letter of the alphabet. * Optionally replace both instances of `[putStr x>>print x,main]` with `[main,putStr x>>print x]`. You can use longer names too to get as many alleles as you want. [Try it online!](https://tio.run/##y0gszk7NyfmfmVuQX1SiEFxZXJKaqxeUmJeSn/vfOjcxM8@2CMwJ8vTXMNAx1LSzs9WILigtCS4pUqiwsysoyswrUajQAamMVVTULM9ILUpVqLBVoqXeSpjeSjS9lZTp/f8fAA "Haskell – Try It Online") Each allele is also a quine on it's own, which is fun! But even more fun, you can also concat as many alleles as you want together and it will output one of the given alleles randomly. Unfortunately later alleles will be less likely than earlier alleles if you do more than 2. --- \* Since it's basically impossible to import stuff properly with the allele stuff going on I take the import via command line flag. [Answer] # [Lost](https://github.com/Wheatwizard/Lost) -A, score ~~249~~ \$66+\frac{66}{2^{1404}}\$ = ~66 Starting with [Jo King's 66 byte Lost quine](https://codegolf.stackexchange.com/a/155002/46076): ``` :2+52*95*2+>::1?:[:[[[[@^%?>([ " //////////////////////////////// ``` There are several ways of making non-functional tweaks to this code that make it still a quine. In this answer, I'm focusing on the numeric operations. For example, you can change `52*` to `19+`,`28+`,`37+`,`46+`,`55+`,`5:+`,`64+`,`73+`,`82+`,`91+`,or `25*`. This totals 12 different possibilities. Another set of tweaks is in the operation `95*2+`. You can swap the order of operations of the multiplication (`59*2+`) or the addition (`295*+`), or rewrite the entire expression as `85*7+` or `76*5+`. All of these things are independent of each other, so there are 3\*2\*2 = 12 ways of writing the same expression. You can also (thanks to Jo King in the comments for pointing this out), write it as `:4*7+`. Because this depends on the stack before the instruction is executed, it can't be combined with any other permuters, so only adds one more way of writing the expression, bringing the total to 13. A third set of tweaks (also thanks to Jo King in the comments) is that the `1` can be changed to to `2`,`3`,`4`,`5`,`6`,`7`,`8`, or `9`, making 9 possibilities. Likewise, the `1?` sequence can be moved one space to the left, making a total of 9\*2=18 possibilities. I'm sure someone more familiar with the language than me could write even more of these trivial tweaks. The tweaks shown there are independent of each other, so you can multiply the 12 ways of writing the first expression by the 13 ways of writing the second expression and the 18 ways of writing the third expression to get 2808 unique quines. If a Lost program consists of two of these quines concatenated together, then Lost's built-in random placement of the IP will result in the program executing one of the quines at random (and thus producing its source code). Each quine, by itself, makes a valid allele, and thus combining two of them produces a genetic quine, resulting in a total of 1404 valid genetic quines. Similarly to the Haskell answer, you can concatenate any number of alleles together rather than just two, and one of them will be chosen uniformly randomly. As an example, one could consider program A to be: ``` :2+52*295*+>::1?:[:[[[[@^%?>([ " //////////////////////////////// :2+25*295*+>::1?:[:[[[[@^%?>([ " //////////////////////////////// ``` [Try it online!](https://tio.run/##y8kvLvn/38pI29RIy8jSVEvbzsrK0N4q2ioaCBziVO3tNKIVlLj0CQAuoAlGppSY8P//f13HQAA "Lost – Try It Online") and Program B to be: ``` :2+52*259*+>::1?:[:[[[[@^%?>([ " //////////////////////////////// :2+25*259*+>::1?:[:[[[[@^%?>([ " //////////////////////////////// ``` [Try it online!](https://tio.run/##y8kvLvn/38pI29RIy8jUUkvbzsrK0N4q2ioaCBziVO3tNKIVlLj0CQAuoAlGppSY8P//f13HQAA "Lost – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~81~~ base allele : 71 bytes, score ~= 71 ``` a=r";from random import*;print('a=r\"'+a[:-8]+'%r))'%choice(a[-7]+'A')) ``` ``` a=r";from random import*;print('a=r\"'+a[:-8]+'%r))'%choice(a[-7]+'A'))a=r";from random import*;print('a=r\"'+a[:-8]+'%r))'%choice(a[-7]+'B')) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P9G2SMk6rSg/V6EoMS8FSGXmFuQXlWhZFxRl5pVoqAPlY5TUtROjrXQtYrXVVYs0NdVVkzPyM5NTNRKjdc2BYo7qmppUMMYJaMz//wA "Python 3 – Try It Online") Other alleles can be created by replacing the char `A` by (almost) any char (except simple quote `'`, double quote `"`, backslash `\`, newline, line feed, tabulation, and null char) ## Old solution : [Python 3.8 (pre-release)](https://docs.python.org/3.8/), base allele : 81 bytes, score ~= 81 ## Base allele ``` exec(_:="A,a,*id=id or print('exec(_:=%r)'%choice([a,_])),_;from random import*") ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P7UiNVkj3spWyVEnUUcrM8U2M0Uhv0ihoCgzr0RDHSarWqSprpqckZ@ZnKoRnagTH6upqRNvnVaUn6tQlJiXAqQycwvyi0q0lDS54CY6UcnE//8B "Python 3.8 (pre-release) – Try It Online") Other alleles can be created by replacing the first char of the string (here `A`) by any char which can be used as variable name (except `_`) ## How it works: I started from the quine `exec(_:="print('exec(_:=%r)'%_)")` * Since `id` is a python built-in, it is evaluated as `True`. So `id or print(...)` won't do anything in the first allele. * `A,a,*id= ...,_` assigns `A` to something, `a` to the string of the current allele and `id` to `[]` When come the second allele, `id` is no evaluated as `False` and `a` store the first allele. * `id or print(...)` will now print the quine * `choice([a,_])` will either be `a` (the first allele) or `_` (the current allele) `'exec(_:=%r)'%choice([a,_])` equals the full code of either one of the allele [Answer] # [Python 3.8](https://docs.python.org/3.8/), score ~ ~~105~~ ~~104~~ ~~98~~ ~~97~~ 95 Base allele: ``` (lambda A:exec(_:="from random import*;.5>random()!=print('(lambda A:exec(_:=%r))'%_)or A(A)")) ``` The other alleles can be obtained by replacing all `A`s with lowercase and uppercase alphabets for a total of 52 alleles [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/XyMnMTcpJVHB0Sq1IjVZI97KVimtKD9XoSgxLwVIZeYW5BeVaFnrmdpBRDQ0FW0LijLzSjTUMbWqFmlqqqvGa@YXKThqOGoqaWrC1DiRb7wTNuOdNJxAxv//DwA "Python 3.8 (pre-release) – Try It Online") Heavily based on the [JavaScript answer](https://codegolf.stackexchange.com/a/236629/91267) -6 thanks to [@Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) -2 thanks to [@Jakque](https://codegolf.stackexchange.com/users/103772/jakque) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 9 bytes, 10 alleles ## single : ``` `1ȮḢ+"℅qṪ ``` ## combined : ``` `1ȮḢ+"℅qṪ`2ȮḢ+"℅qṪ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiYDHIruG4oitcIuKEhXHhuapgMsiu4biiK1wi4oSFceG5qiIsIiIsIiJd) The digit can be replaced by any digit from 0 to 9 for a total of 10 alleles ## Explanation ``` `1ȮḢ+"℅qṪ` # push `1ȮḢ+"℅qṪ` => [ 1ȮḢ+"℅qṪ ] 2 # push 2 => [ 1ȮḢ+"℅qṪ , 2 ] Ȯ # push the second-last item => [ 1ȮḢ+"℅qṪ , 2 , 1ȮḢ+"℅qṪ ] Ḣ+ # remove the first char and add => [ 1ȮḢ+"℅qṪ , 2ȮḢ+"℅qṪ ] "℅ # listify and pick at random => [ 1ȮḢ+"℅qṪ ] or [ 2ȮḢ+"℅qṪ ] qṪ # quote and remove the last char => [ `1ȮḢ+"℅qṪ ] or [ `2ȮḢ+"℅qṪ ] # implicit output ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 55 bytes per allele, 23 alleles ``` ≔´θ´F´‽´⎚´F´¬´ⅈ´«´´´≔´F´θ´⁺´´´´´κ´θ´»θF‽⎚F¬ⅈ«´≔Fθ⁺´´κθ» ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9R55RDW87tOLTl/Z5lh7Y8atgLJPpmQbmH1gB5rR1AxmogBkKwarAUSMujxl0QYRA8twsieGj3uR1AFUCTgOaAlK4BmbAarBfIPbcDquvcLqDq3RDrt5Nu/XZs1m8HW78dn/XbEdZvP7T7/38A "Charcoal – Try It Online") Link is to sample program of two alleles. Any of the 22 variables `αβγδεζηλμνξπρςστυφχψω` can be used in place of `θ`. (I think it might also be possible to replace the third and sixth `F`s with `⭆` to double the number of alleles but I haven't tested this. I think I could have also started with the Charcoal quine of the same length from [Minimal distinct character quine](https://codegolf.stackexchange.com/questions/230024/) which would give me a further set of 25 alleles, since that quine doesn't use the `ι` or `κ` variables.) Explanation: Mostly based on the Charcoal quine from [Golf you a quine for great good!](https://codegolf.stackexchange.com/questions/69/). ``` ≔´θ´F´‽´⎚´F´¬´ⅈ´«´´´≔´F´θ´⁺´´´´´κ´θ´»θ ``` Assign the string `θF‽⎚F¬ⅈ«´≔Fθ⁺´´κθ»` (a suffix of the entire allele) to a variable. ``` F‽⎚ ``` Clear the canvas 50% of the time. (This is only relevant to the second allele, since it's always clear when the first allele runs.) ``` F¬ⅈ«´≔Fθ⁺´´κθ» ``` If the canvas is clear, then print a `≔`, then print the variable twice, the first time prefixing `´` to each character. Note that if multiple alleles are concatenated then each has half the chance of the previous allele of appearing except the last allele which has the same chance as the penultimate allele. [Answer] ## [Ruby](https://www.ruby-lang.org/en/), score 66 + 66 / (2 ^ (26\*3)) ~ 66 ``` eval$a=%q[($r==false||$r=rand<0.5)&&$><<"eval$a=%q[#$a]\n"&&exit] eval$b=%q{($r==false||$r=rand<0.5)&&$><<"eval$b=%q{#$b}\n"&&exit} ``` «Genetic diversity» comes from global variable name («a» - «z») and paired delimiters for `%q` string notation (`()`, `[]` and `{}`). Non-paired delimiters (as well as `'`) won't work since they have to be the same inside. And other `%` notations won't work due to interpolation. [Answer] # [Julia 1.0](http://julialang.org/), score ~86 ``` (a=:(push!(ARGS, "$(0 < rand(length(ARGS):1) < print("(a=:($(a)))|>eval;"))")))|>eval; (b=:(push!(ARGS, "$(rand(length(ARGS):1) > 0 > print("(b=:($(b)))|>eval;"))")))|>eval; ``` [Try it online!](https://tio.run/##dcy/DoIwEAbwvU9xNgx3CQM4opI4uesTXKFKTS2kFiOJ714RYhzU4Rvuz/c799Zwfo/H1oMB4yAvlpkIfhD60oVhgdv97kDiZFvFFjhVEXlTYNdfm/mWgkwwgzV4djVa7U6hmUtFTuO688YFlFMrQSaiR6lvbFeSSH4mgeqb/UmWkI15s2pi1T82VhyqRkzf1iEJ7epX4hM "Julia 1.0 – Try It Online") (the line break is here only for readability, it should be removed) 4\*52=208 alleles, 4 for the different comparison orders and 52 for the variable name (`[a-zA-Z]`). Ends with an error, I believe it is allowed (not so sure for quines?) Based on the following quine, which is explained in this [answer by Dennis](https://codegolf.stackexchange.com/a/92455/98541) (adapted for Julia 1.0): `(q=:(print("(q=:($(q)))|>eval")))|>eval` [Try it online!](https://tio.run/##yyrNyUw0rPj/X6PQ1kqjoCgzr0RDCcxW0SjU1NSssUstS8xRgrP@//8PAA "Julia 1.0 – Try It Online") ]
[Question] [ # Objective Given an ASCII string, decide whether it is a valid C integer literal. # C integer literal A C integer literal consists of: * One of: + `0` followed by **zero or more** octal digits (`0`–`7`) + A nonzero decimal digit followed by **zero or more** decimal digits (`0`–`9`) + `0X` or `0x`, followed by **one or more** hexadecimal digits (`0`–`9`, `A`–`F`, and `a`–`f`) * optionally followed by one of: + One of `U` or `u`, which are the "unsigned" suffixes + One of `L`, `l`, `LL`, or `ll`, which are the "long" and "long long" suffixes + Any combination of the above, in any order. Note that there can be arbitrarily many digits, even though C doesn't support arbitrary-length integers. Likewise, even if the literal with `l` and co would overflow the `long` type or co, it is still considered a valid literal. Also note that there must **not** be a leading plus or minus sign, for it is not considered to be a part of the literal. # Rules * It is implementation-defined to accept leading or trailing whitespaces. * Non-ASCII string falls in *don't care* situation. # Examples ## Truthy * `0` * `007` * `42u` * `42lu` * `42UL` * `19827489765981697847893769837689346573uLL` (Digits can be arbitrarily many even if it wouldn't fit the `unsigned long long` type) * `0x8f6aa032838467beee3939428l` (So can to the `long` type) * `0XCa0` (You can mix cases) ## Falsy * `08` (Non-octal digit) * `0x` (A digit must follow `X` or `x`) * `-42` (Leading signature isn't a part of the literal) * `42Ll` (Only `LL` or `ll` is valid for the `long long` type) * `42LLLL` (Redundant type specifier) * `42Uu` (Redundant type specifier) * `42Ulu` (Redundant type specifier) * `42lul` (Redundant type specifier) * `42H` (Invalid type specifier) * `0b1110010000100100001` (Valid C++, but not valid C) * `Hello` * Empty string # Ungolfed solution ## Haskell Doesn't recognize leading or trailing whitespaces. Returns `()` on success. Monadic failure otherwise. ``` import Text.ParserCombinators.ReadP decideCIntegerLit :: ReadP () decideCIntegerLit = do choice [ do '0' <- get munch (flip elem "01234567"), do satisfy (flip elem "123456789") munch (flip elem "0123456789"), do '0' <- get satisfy (flip elem "Xx") munch1 (flip elem "0123456789ABCDEFabcdef") ] let unsigned = satisfy (flip elem "Uu") let long = string "l" +++ string "L" +++ string "ll" +++ string "LL" (unsigned >> long >> return ()) +++ (optional long >> optional unsigned) eof ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~60~~ 59 bytes ``` i`^(0[0-7]*|0x[\da-f]+|[1-9]\d*)(u)?(l)?(?-i:\3?)(?(2)|u?)$ ``` [Try it online!](https://tio.run/##JY1Pa8MwDMXv/hwb2B0G@U8taRcfdlgPuQ4GSUZd6kLArFAW6CHfPVNaofeTEOK9W/2bfsv6qj@P63T80dCDxXG3wL0fzsVexreld5bH4bwzejZZN1G20/sQstFZe7PM2bysqwIFgCr6WdQ2fHXKMXmMxJj2TC4xUkTigIlJIFtMewxz1ym40yWVAsFToJjwVGsNHDh6agq@P4rYk3wpG714d22D1JbzCGvP3O1@UHByzgFIP/Cc6lBbu/4D "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 1 byte thanks to @FryAmTheEggMan. Explanation: ``` i` ``` Match case-insensitively. ``` ^(0[0-7]*|0x[\da-f]+|[1-9]\d*) ``` Start with either octal, hex or decimal. ``` (u)? ``` Optional unsigned specifier. ``` (l)? ``` Optional length specifier. ``` (?-i:\3?) ``` Optionally repeat the length specifier case sensitively. ``` (?(2)|u?)$ ``` If no unsigned specifier yet, then another chance for an optional specifier, before the end of the literal. [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~65~~ 61 bytes *@NahuelFouilleul shaved 4 bytes* ``` $_=/^(0[0-7]*|0x\p{Hex}+|[1-9]\d*)(u?l?l?|l?l?u?)$/i*!/lL|Ll/ ``` [Try it online!](https://tio.run/##hVJta9swEP7uX3FjhcnJHMsvsSXKKCNfMnBXGHQU2m4osZxq3CRjS1tCs79eT3a2L/3Q6uXRSffccfegVna4HPoYFrM4Pu/F4Rzewg/XW3iQnYTGdLBF0Sl7ANOAfZCgdOssCF2DcXY0R46VvVV6txjOvn@IvxF6S6Pyfnak@7v2cS33f@bH2yTi93f1LCTuAv08juAuwrNYzd7EWB0rjIeBBpSWQZ46v3GE6ypIOEvLnPGyWHKWFLxkecl4VhacefBWXizLzFVVQPesKYSgWcoylhflRkqZ8YznKcOA3qyET8@AfDY6MlsrEGq1Uzb0cUA@ni7wc@y9MYjmN9yAb20fBlGeAqmkqH2L0KudFtZ5cVSv33kloBWd/a8OKis7gaEvvUIgVxoPUFVjHkQfAL8Eqvok2cg2PuEE9tDKKcgPIF9k7XQttJ3eoW/lVjVKdiPj2r3ix1cI6PBlwhrIJ30q9LmTbpIkodSvCU4nkK8TeTWfv4eN/xHa2H@NrsJgLb2WT6a1yuh@iC6XCx82RC3@BQ "Perl 5 – Try It Online") [Answer] # Java 8 / Scala polyglot, ~~89~~ 79 bytes ``` s->s.matches("(?!.*(Ll|lL))(?i)(0[0-7]*|[1-9]\\d*|0x[\\da-f]+)(u?l?l?|l?l?u?)") ``` -10 bytes thanks to *@NahuelFouilleul* [Try it online in Java 8.](https://tio.run/##PVKxbtswEN3zFVdOoh0JpESLZILWQ5YMajoEBQo4HiiaTuXScmBSqYvY3@6StBxIeHe8e7r3dOBGvat8s/pz1lY5B99V13/cAHS9N/u10gae4hHgR7sx2oPOnv2@61/B4ftQP90EcF75TsMT9PD17PJvrtgqr38bl6Fs/qWYZI092gbjbN7hjCxIzpeT44LmcvnyspocyWERosrXyynOhrkNzzHCMMcIn@@jwtvQ2qAwCr3vuhVsg9HRy2IJCl9crnf7q0FvnH9QzsAd9OYvXKkfiKBbRAgPyMohIrUplD@b2Pn1oBLjINa1UqQqRSVYzVtjTCUryUphQ5tKUXImJK9nUtBacsG4kBWvpQgQMlbPeDU0cSS6BUREmhkgZ2VSa@wlNIkT1EcToxk7XPqP8buWUkpIeBNcYqg/Gmt30UxDk/WDage9SgOueUyL@D@UFCw2aFlZNqujkcgJx5GtQ1oQgk44bRLg@Z/zZlvsBl@8hd1522fXnU7RHaBpX@jPCh6vw@n8Hw) [Try it online in Scala](https://tio.run/##NVFNb8MgDL33VzBO0I8IEhqgUhptu/SQnapJk9oeaErWTizpGjJVWvfbMyCdQO/Z2NgP3JbKqL7Zf@jSghd1qoG@Wl0fWvB4Pv@MAPhWBlQLsLaXU/0OsiV4ahqjVQ2yvs2WbfSpbHnULYIof4jGqDA3U2CM8hNGZENmfDe@behM7rbbw/hGrhvHalbtJhh1uXHr5qHLMcT90Mzq1rYgA2v9hSCBU0gId8jiziM1geLXwkfenlXIuIoqVYoksUgES/lea53IRLJYGBemUsScCcnTuRQ0lVwwLmTCUykcOIulc550hS8JpwASEWo6mLE4dCvMQEXIcd3vIu5iTDfEV/7enlJKiNsBBnbnK21M48UUNEi/qn1XHkKBf9ubkX8PJRHzARonhs1TL8TnOPeeXTozIgRiN6DwX1HVXLQqj8j6EZ3drKypnTMBcAGgowpZjPHot/8D) (except with `=>` instead of `->` - thanks to *@TomerShetah*). **Explanation:** ``` s-> // Method with String parameter and boolean return-type s.matches( // Check whether the input-string matches the regex "(?!.*(Ll|lL))(?i)(0[0-7]*|[1-9]\\d*|0x[\\da-f]+)(u?l?l?|l?l?u?)") ``` *Regex explanation:* In Java, the [`String#matches`](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/String.html#matches(java.lang.String)) method implicitly adds a leading and trailing `^...$` to match the entire string, so the regex is: ``` ^(?!.*(Ll|lL))(?i)(0[0-7]*|[1-9]\d*|0x[\da-f]+)(u?l?l?|l?l?u?)$ ``` ``` (?! ) # The string should NOT match: ^ .* # Any amount of leading characters ( ) # Followed by: Ll # "Ll" |lL # Or "lL" # (Since the `?!` is a negative lookahead, it acts loose from the # rest of the regex below) (?i) # Using case-insensitivity, ^ ( # the string should start with: 0 # A 0 [0-7]* # Followed by zero or more digits in the range [0,7] | # OR: [1-9] # A digit in the range [1,9] \d* # Followed by zero or more digits | # OR: 0x # A "0x" [ ]+ # Followed by one or more of: \d # Digits a-f # Or letters in the range ['a','f'] )( # And with nothing in between, )$ # the string should end with: u? # An optional "u" l?l? # Followed by no, one, or two "l" | # OR: l?l? # No, one, or two "l" u? # Followed by an optional "u" ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 197 191 bytes @nwellnhof shaved 6bytes: ``` using c=System.Console;class P{static void Main(){c.WriteLine(System.Text.RegularExpressions.Regex.IsMatch(c.ReadLine(),@"^(?!.*(Ll|lL))(?i)(0[0-7]*|[1-9]\d*|0x[\da-f]+)(u?l?l?|l?l?u?)$"));}} ``` Original: ``` using c=System.Console;using System.Text.RegularExpressions;class P{static void Main(){c.WriteLine(Regex.IsMatch(c.ReadLine(),@"^(?!.*(Ll|lL))(?i)(0[0-7]*|[1-9]\d*|0x[\da-f]+)(u?l?l?|l?l?u?)$"));}} ``` [Try it online!](https://tio.run/##LYxdC4JAFET/ikUPey0X@4CICIPoIVCICnowg2W92cKm4V1jI/vtZhEDA3PgjCRPFiU2TUUqzxy52D/J4I2vipwKjXOpBZGzfZERRknnUajUiYTKGbwkP5bKYKhyZH/rgNbwHWaVFuXa3kskUu3RF6HlG4qEkVcm2y3SnweDZffMgg53WahrHQKwQAHzY9@bJm4dD71Zckrd2rfxKRXeJekDqwLdpv5WFUCvCzB/v5vGt6Px5AM "C# (.NET Core) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 103 bytes ``` import re;re.compile("^(0[0-7]*|[1-9]\d*|0[xX][\dA-Fa-f]+)([uU](L|l|LL|ll)?|(L|l|LL|ll)[uU]?)?$").match ``` [Try it online!](https://tio.run/##XY5da8MgFIavl18RZBfaLUWjjdoxwhiMXuS2ULAO0tbQgPkgTUYH@e9ZvrovkPc9@p7jecrP@lzktEuzsqhqtzJO8mw@YgsBAD@PT5VZHousTK2B4B1ihT2uF60intT706LF6rrTan968d5iL9EPCKpmq2HU2jbqxaKw/XUZshCF9wAts7g@nrt@lyJkrZGTFJV7cdPcVQCDRxdgzAdjfjOZnX0bDU6k8DkTkgcrKUgguWBcSMoDKXrpKxasOG2isRlfRRLEMaa@oIIF/GCMoZJK5gs75rvXGAO9du7KKs1rmMALQs4fIjH9M6jH/IkksrNPW3q0G6L9Zp5bNuP4gRCCcX9GmXwINsbaYij@M3Rf "Python 3 – Try It Online") just a basic regex, probably very suboptimal returns a match object for truthy and None for falsy; input may not contain surrounding whitespace -3 bytes thanks to Digital Trauma (on my Retina answer) -1 byte thanks to FryAmTheEggman (on my Retina answer) -3 bytes thanks to pxeger [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 73 bytes ``` ^(0[0-7]*|[1-9]\d*|0[xX][\dA-Fa-f]+)([uU](L|l|LL|ll)?|(L|l|LL|ll)[uU]?)?$ ``` [Try it online!](https://tio.run/##K0otycxL/P8/TsMg2kDXPFarJtpQ1zI2JkWrxiC6IiI2OibFUdctUTctVltTI7o0NFbDpyanxgdI5Gja1yBxQHL2mvYq//8bVFikmSUmGhgbWRhbmJiZJ6WmphpbGluaGFnkAAA "Retina 0.8.2 – Try It Online") Just the same regex I used. First time using Retina, I'm sure this can be optimized with some Retina golf things! -3 bytes thanks to Digital Trauma -1 byte thanks to FryAmTheEggman [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 76 bytes ``` ≔⊟Φ³¬⌕↧θ…0xιη≔✂↧θη⁻LθL⊟Φ⪪”{“↧←;⭆δa”¶⁼ι↧…⮌θLι¹ζ›∧⁺Lζ¬⊖η⬤ζ№E∨×⁸ηχ⍘λφι∨№θLl№θlL ``` [Try it online!](https://tio.run/##XVBNb4MwDL3vVyBORmJSu1II6ol1Hxe6oXXHXhD1SiQ3tCHpNv48cyga0yLZsi0/v/dS1aWumpL6PmtbeVBQNCd4kmRQwyL0XhrDndpD3nyirsoW4RyE3vq7IlzXvOrPvvzQk4F7oVcHq5vxzpZkhf9gdehtpLIt5KgOph5mY/mHdnsiacDfKUvk0k6R5SDLRDz1GfR4tiW1IBn@SzBpesML6pFyPH8VOGicc3Sss9BSGXjWWDrSjD0WNEnrgqv5B6w0HlEZ3EM94DMi6PgLGsvwTXmCVw3v8ogtCPcBTDDjdM@StoYpDkCh9@GAcoDz9hV6Zjc5OTdTT7nvRK76fp6KuyQSaRIvUzGP00REiUgXSZwKTlxF8TJZ2Dzvby/0Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⊟Φ³¬⌕↧θ…0xιη ``` Find the length of the longest prefix of `0x` in the lowercased input. ``` ≔✂↧θη⁻LθL⊟Φ⪪”{“↧←;⭆δa”¶⁼ι↧…⮌θLι¹ζ ``` Slice off the prefix and also check for a lowercase suffix of `ull`, `ul`, `llu` or `lu`, and if so then slice that off as well. ``` ›...∨№θLl№θlL ``` The original input must not contain `Ll` or `lL`. ``` ∧⁺Lζ¬⊖η ``` The sliced string must not be empty unless the prefix was `0`. ``` ⬤ζ№E∨×⁸ηχ⍘λφι ``` Convert the prefix length to `10`, `8` or `16` appropriately, then take that many base 62 digits and check that all of the remaining lowercased characters are one of those digits. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~63~~ ~~61~~ 62 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` „Uuõª„LLæDl«âDí«JéRʒÅ¿}нõ.;Ðć_ilDć'xQiA6£мÐþQë\7ÝKõQë\þQ}sõÊ* ``` This isn't too easy without regexes.. :/ Can definitely be golfed a bit more, though. +1 byte as bug-fix for inputs like `"u"`, `"l"`, `"LL"`, etc. (thanks for noticing *@Neil*) [Try it online](https://tio.run/##yy9OTMpM/f//UcO80NLDWw@tAjJ8fA4vc8k5tPrwIpfDaw@t9jq8MujUpMOth/bXXth7eKue9eEJLkfa4zNzgKR6RWCmo9mhxRf2HJ5weF/g4dUx5ofneh/eCmIB@bXFh7ce7tL6/9@gwiLNLDHRwNjIwtjCxMw8KTU11djS2NLEyKLUxwcA) or [verify all test cases](https://tio.run/##NU/LSgMxFP2Vko0gdUgmaR64KOIsis6mQkFQkZk6QiHQRYm0i4IbLbgq3etCQahFd7PzAbldueo39EfGJK0Qzj3JOffek/4gy3tFdTNqotr6flZDzVFi59X69qljoLRvjqQpvCbaLuA5gXe7OIL5ye/Mfgzgzv6MV19QRvsJTJeTy55OlpOdYbt3wO3L6hOm8N2GxbmAx2MoPXP38QBKeNit6tUZwqiOMBYOWWw8Eh1K3Em9cnqYBcdQXvMswzSWVDIu8qIoqKKKxVI7mSgZCyaV4A0lCVdCMiEVFVxJB44x3hDUpH4kqtcQlmGmgz0Wh22p3pQ0eNz2bYhtGG02esv35YQQjN0JsKnuvVVo3fdhUhKiD7PcdK/CgH/uaeT/Q3DEvEBiqlmD@yDe465bd9fRCHurt/nGEMwYdPEH). **Explanation:** ``` „Uu # Push string "Uu" õª # Convert it to a list of characters, and append an empty string: # ["U","u",""] „LL # Push string "LL" æ # Take its powerset: ["","L","L","LL"] Dl # Create a lowercase copy: ["","l","l","ll"] « # Merge the lists together: ["","L","L","LL","","l","l","ll"] â # Create all possible pairs of these two lists Dí # Create a copy with each pair reversed « # Merge the list of pairs together J # Join each pair together to a single string éR # Sort it by length in descending order ``` We now have the list: ``` ["llu","LLu","llU","LLU","ull","uLL","Ull","ULL","ll","LL","lu","lu","Lu","Lu","lU","lU","LU","LU","ll","LL","ul","ul","uL","uL","Ul","Ul","UL","UL","l","l","L","L","u","u","U","U","l","l","L","L","u","u","U","U","","","",""] ``` ``` ʒ # Filter this list by: Å¿ # Where the (implicit) input ends with this string }н # After the filter: only leave the first (longest) one õ.; # And remove the first occurrence of this in the (implicit) input ÐD # Triplicate + duplicate (so there are 4 copies on the stack now) ć # Extract head; pop and push remainder-string and first character # separated to the stack _i # If this first character is a 0: l # Convert the remainder-string to lowercase D # Duplicate it †¹ ć # Extract head again 'xQi '# If it's equal to "x": A # Push the lowercase alphabet 6£ # Only leave the first 6 characters: "abcdef" м # Remove all those characters from the string Ð # Triplicate it †² þ # Only keep all digits in the copy Q # And check that the two are still the same # (thus it's a non-negative integer without decimal .0s) ë # Else: \ # Discard the remainder-string 7Ý # Push list [0,1,2,3,4,5,6,7] K # Remove all those digits õQ # Check what remains is an empty string ë # Else: \ # Discard the remainder-string þ # Only keep all digits Q # And check that the two are still the same # (thus it's a non-negative integer without decimal .0s) }s # After the if-else: Swap the two values on the stack # (this will get the remaining copy of †² for "0x" cases, # or the remaining copy of †¹ for other cases) õÊ # Check that this is NOT an empty string * # And check that both are truthy # (after which the result is output implicitly) ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 86 bytes ``` {print/^(0[0-7]*|[1-9][0-9]*|0[xX][0-9A-Fa-f]+)([uU](L|l|LL|ll)?|(L|l|LL|ll)[uU]?)?$/} ``` [Try it online!](https://tio.run/##TY1fS8MwFMXf8ylKmdA6427@LLl5sYgge8jrYNBVSF0LYlBRiwO7z15vuj14yf3l5J5wT/h5nX4/Pl/evvss3@dXX/s843dZfpMt4HRxVk8F1MBtcz3WgruGtCMN9XE363v@GHjfLMuiHrZN4cc4ekIsq/HfI3lVWS1Wp2kCBmCZlgN1TNh6JhxKq9FZs3YojLOoLTpljUMCKW3WVg3eMzhib0IAJVGhNrbtuk455bTEyGD3EGg90i/GtaTdPiZQpZw5LJ5z03zDoBVCANCZcb7ZpovxnTFxK5nwImWGdng@xOEP "AWK – Try It Online") Simply prints truthy or falsey depending on whether or not the input line matches the regex. Doesn't accept leading or trailing whitespaces. [Answer] # [Elixir](https://elixir-lang.org/), 74 bytes ``` &(&1=~~r/^(0[0-7]*|[1-9]\d*|0x[\da-f]+)(u?l?l?|l?l?u?)?$/i&&!(&1=~~r/Ll/)) ``` [Try it online!](https://tio.run/##S83JrMgs@p9m@19NQ83Qtq6uSD9OwyDaQNc8Vqsm2lDXMjYmRavGoCI6JiVRNy1WW1Oj1D4HCGtARKm9pr2KfqaamiJMr0@Ovqbmf09/vYLSkmKFND0NIDM9taRYyU5J879BRUpqYkpSamqaj08pAA "Elixir – Try It Online") [Answer] # JavaScript (ES6), ~~77~~ 76 bytes *Saved 1 byte thanks to @l4m2* ``` s=>/^(0x[\da-f]+|0[0-7]*|[1-9]\d*)(u?l?l?|l?l?u?)$/i.test(s)>/Ll|lL/.test(s) ``` [Try it online!](https://tio.run/##dZBdS8MwFIbv/RlDaDvpmjRZPi62XQiyi1wqCG2FbE11cmhlaWVC/3uNE0HxjIQ3yZOTj/d9te/W74@Htz5tu9pNzWryq3X2FJNTUdY2baqbkRQkldV8LGiqq7KeJ/GwgdDGLxk2yXV2WPTO97FP1pmBEUz2s572Xes7cAvonuOouD8O/ctHFSVXv3kTz8gs@c@IRCjPB5QCjh8MgqlWueRKS7HUigotFZdKMym0ChJmXCwlGwx2lpxUI6wlLFdMcSF3zjmmmea5Aqz88daezf3ZiMq2uLPg0SgU@ioCU56jng3g2KCGQkYXooNLSeP3b7F/7yilhIR@lu8Rqds6gA7hAU2f "JavaScript (Node.js) – Try It Online") ### How? The first regex is case-insensitive. The only invalid patterns that cannot be filtered out that way are `"Ll"` and `"lL"`. So we use a 2nd case-sensitive regex to take care of them. [Answer] # [Haskell](https://www.haskell.org/), 169 bytes ``` import Data.Char s!p=s>""&&dropWhile p s`elem`do u<-["","u","U"];l<-"":words"L l LL ll";[u++l,l++u] f('0':x:s)|elem x"xX"=s!isHexDigit|1<2=(x:s)!isOctDigit f s=s!isDigit ``` [Try it online!](https://tio.run/##ZVFda9swFH3Pr7i9D22CmyB/1JbzMRgtIw@GPYyyQglUnaVaTLGFJW0e9L9n127KBhW@x9bR8T1HUiPcT2nM6aSPtus93AkvVreN6Gfuwu7cJ8TLy7rv7PdGGwkW3JM08vhUdxC2y0fEawxU93jYmO0Scf2762uHFRioCAxuHkMUmWsTReEwU/MrdrUe1m7xOnaBAYcH3LkL7fZyuNMv2r/G22Q3HxVEfv3hJ3KmwE2qaXY6Ct3CDupuBmCkB98H3/whZvIGZMBYDlkSqMwI9xXEJU@KjJdFflPyOC8LnhW8TIu85AT0leU3RRooMxu4yoVgacJTnuXFs5QyLdMyS7gB9nArGJ59lTBO/u/LyZhqgGWWkG1lRqAxRphymLdII78H9hzHMWP0TPD2hj1dRocQRUCHe3h3GvertPGyh3nb@ZVanHf9LrD/BOocjJZs8N98D/hlJKCVL8LrX9KtATdge92OnT/IbOf0B5klmVbQBmNgrtooUpYiNLI9/1y1gJ9pzUvnHVjhnKxXCHJqGHoJ88XpLw "Haskell – Try It Online") ]
[Question] [ ## PROBLEM Given two words, find the winner in a **digital root** battle. Define the **digital root** of a word this way: 1. Each letter of the alphabet is assigned a number: *A = 1, B = 2, C = 3, ..., Z = 26* 2. Add the values for each letter to total the word. Take "CAT", for example. *C+A+T = 3+1+20 = 24* 3. Add all the single digits that make up that result: *24 => 2 + 4 = 6* 4. Repeat step #3 until you reach a single digit. That single digit is the **digital root** of the word. **Rules:** 1. A winner is declared if its **digital root** is larger than the other. 2. If the **digital root** values are equal, shorten the words by removing every instance of the highest value letter from both words and recalculating. 3. Repeat steps #1 and #2 until there is a winner **or** one of the words has only a single letter (or no letters) remaining. 4. If the **digital root** values are equal after going through the shortening process, the longer word is declared the winner. 5. If the words are of equal length and no winner is found after going through the shortening process, no winner is declared. **Special rules:** 1. No use of modulus is allowed in the calculation of the **digital root** itself. It can be used anywhere else. 2. Assume words will consist only of uppercase letters - no punctuation, no spaces, etc. ## INPUT Pull the words in through stdin (comma-separated). method parameters, or however you want. Make it clear in your solution or the code how the words are parsed or prepared. ## OUTPUT Display the winning word. If there is no winner, display "STALEMATE". **Examples:** intput: CAN,BAT ``` CAN = 18 = 9 BAT = 23 = 5 ``` output: CAN intput: ZOO,NO ``` ZOO = 56 = 11 = 2 NO = 29 = 11 = 2 OO = 30 = 3 N = 14 = 5 ``` output: NO ***UPDATE**: Input must be read using stdin with the words as a comma-separated string.* ***UPDATE**: Added a couple examples to test against.* ***UPDATE**: clarified the removal of the highest valued letter in the case of a tie - this also alters slightly the stop condition as well - if a word is one letter or zero letters long, the shortening process is stopped* [Answer] ## J, 100 ``` z=:"."0@":@(+/)^:9@(64-~a.i.])@(#~' '&i.)"1 f=:*@-/"2@(z@((]#~]i.~{.@\:~)"1^:([:=/z))){'STALEMATE'&, ``` runs like this: ``` f 'NO',:'ZOO' NO f 'CAN',:'BAT' CAN f 'FAT',:'BANANA' FAT f 'ONE',:'ONE' STALEMATE ``` it doesn't *yet* accept input exactly as asked. [Answer] ## APL (Dyalog) (~~91~~ 86) ``` ⎕ML←3⋄{Z≡∪Z←{2>⍴⍕⍵:⍵⋄∇+/⍎¨⍕⍵}¨+/¨⎕A∘⍳¨⍵:G[↑⍒Z]⋄1∊↑¨⍴¨⍵:'STALEMATE'⋄∇1∘↓¨⍵}G←Z⊂⍨','≠Z←⍞ ``` Explanation (in order of execution): * `⎕ML←3`: set ML to 3 (this makes `⊂` mean partition, among other things). * `G←Z⊂⍨','≠Z←⍞`: read input, separate by commas, store in G and pass to the function. * `+/¨⎕A∘⍳¨⍵`: calculate the score for each word. (`⎕A` is a list containing the alphabet.) * `Z←{2>⍴⍕⍵:⍵⋄∇+/⍎¨⍕⍵}¨`: calculate the digital root for each score (by summing all digits as long as there is still more than one digit) and store them in Z. * `Z≡∪Z`: if all scores are unique... * `:G[↑⍒Z]`: ...then output the word with the highest score (from the original list). * `⋄1∊↑¨⍴¨⍵:'STALEMATE'`: otherwise (if there's a tie), if one of the words is of length 1, output STALEMATE. * `⋄∇1∘↓¨⍵`: otherwise, take the first letter off each word and run the function again. [Answer] # Ruby - 210 ``` d,e=(a,b=$<.read.chop.split(/,/)).map{|w|w.bytes.sort} r=->w,o=65{n=0;w.map{|c|n+=c-o};n>9?r[n.to_s.bytes,48]:n} d.pop&e.pop while r[d]==r[e]&&d[1]&&e[1] $><<[[:STALEMATE,a,b][a.size<=>b.size],a,b][r[d]<=>r[e]] ``` Tests: ``` $ ruby1.9 1128.rb <<< CAN,BAT CAN $ ruby1.9 1128.rb <<< ZOO,NO NO $ ruby1.9 1128.rb <<< ZOO,ZOO STALEMATE ``` [Answer] ## Haskell, 205 characters ``` import List s b=d.sum.map((-b+).fromEnum) d q|q<10=q|1<3=s 48$show q f=map(s 64.concat).tails.group.reverse.sort w(a,_:b)=f a#f b where x#y|x<y=b|x>y=a|1<3="STALEMATE" main=getLine>>=putStrLn.w.span(/=',') ``` Sample runs: ``` > ghc --make WordVsWord.hs [1 of 1] Compiling Main ( WordVsWord.hs, WordVsWord.o ) Linking WordVsWord ... > ./WordVsWord <<< CAN,BAT CAN > ./WordVsWord <<< ZOO,NO NO > ./WordVsWord <<< FAT,BANANA FAT > ./WordVsWord <<< ONE,ONE STALEMATE ``` --- * Edit: (227 -> 219) better picking of winner, shortened pattern match in `w`, imported older, shorter module * Edit: (219 -> 208) Incorporate JB's suggestions * Edit: (208 -> 205) handle negative numbers, exploiting odd rules in Haskell about hyphen [Answer] ## Perl, 224 ~~225~~ ~~229~~ Basic golfing (nothing smart yet): ``` split",",<>;$_=[sort map-64+ord,/./g]for@a=@_;{for(@b=@a ){while($#$_){$s=0;$s+=$_ for@$_;$_=[$s=~/./g]}}($a,$b)= map$$_[0],@b;if($a==$b){pop@$_ for@a;@{$a[1]}*@{$a[0]}&& redo}}say+("STALEMATE",@_)[$a<=>$b||@{$a[0]}<=>@{$a[1]}] ``` Perl 5.10 and above, run with `perl -M5.010 <file>` or `perl -E '<code here>'` ``` $ perl -M5.010 word.pl <<<CAN,BAT CAN $ perl -M5.010 word.pl <<<ZOO,NO NO $ perl -M5.010 word.pl <<<NO,ON STALEMATE ``` [Answer] # K, 106 ``` {a::x;@[{$[(>). m:{+/"I"$'$+/@[;x].Q.A!1+!26}'x;a 0;(<). m;a 1;.z.s 1_'x@'>:'x]};x;"STALEMATE"]}[","\:0:0] ``` Uses exception handling to catch stack errors, which result in cases of stalemate. [Answer] ## VBA (242 462) ``` Function s(q,Optional l=0) s=-1:t=Split(q,","):r=t:m=t For j=0 To 1 m(j)=0:w=t(j) While Len(w)>1 Or Not IsNumeric(w) b=0 For i=1 To Len(w) a=Mid(w,i,1):a=IIf(IsNumeric(a),a,Asc(a)-64):b=b+a If m(j)+0<a+0 Then m(j)=a Next w=b Wend r(j)=b Next s=IIf(r(0)>r(1),0,IIf(r(0)<r(1),1,s)) For j=0 To 1 r(j)=Replace(t(j),Chr(m(j)+64),"",,1) Next If s<0 And Len(t(0))+Len(t(1))>2 Then s=s(r(0) & "," & r(1),1) If l=0 Then If s>=0 Then s=t(s) Else s="STALEMATE" End Function ``` Turns out the below code didn't match the spec, so I had to re-work, adding much length (see above). :-/ This may be able to be golfed further, but it's already pretty compact and I doubt I'll be able to bring it back down to a competitive score. The original (below) did not remove the highest-valued letter from the words when there was a tie. ``` Sub s(q) t=Split(q,",") r=t For j=0 To 1 w=t(j):b=0 For i=1 To Len(w) b=b+Asc(Mid(w,i,1))-64 Next While Len(b)>1 d=0 For i=1 To Len(b) d=d+Mid(b,i,1) Next b=d Wend r(j)=b Next MsgBox IIf(r(0)>r(1),t(0),IIf(r(0)<r(1),t(1),"STALEMATE")) End Sub ``` [Answer] This really took my fancy and is my first post. Although it is old I noticed no one had done a php version so here is mine. ``` <?php $f='CAN,CBN';$w=explode(',',$f);$a=$ao=$w[0];$b=$bo=$w[1];$c=''; function splice($a,$t){$s=$h=0;$y=array();$x=str_split($a); foreach($x as $k=>$v){$s=$s+ord($v)-64;if($v>$h){$h=$k;}} $y[0]=$s;if($t==1){unset($x[$h1]);$y[1]=$x;}return $y;} while($c==''){$y1=splice($a,0);$y2=splice($b,0);$y3=splice($y1[0],1); $y4=splice($y2[0],1);if($y3[0]>$y4[0]){$c=$ao;}else if($y3[0]<$y4[0]){$c=$bo; }else if((strlen($a)<1)OR(strlen($b)<1)){if(strlen($a)<strlen($b)){$c=$ao;} else if(strlen($b)<strlen($a)){$c=$bo;}else{$c='STALEMATE';}}} echo $c; ?> ``` 534 Characters. Now I am unsure as to the rules for starting off so I started with $f='CAN,CBN' as my input. I hope that was right. I have run all the tests and it passes all of them although it is not particularly elegant. I really must get some sleep now but I had great fun working this out - thank you for a great puzzle. Coded on <http://codepad.org/ZSDuCdin> [Answer] # D: 326 Characters ``` import std.algorithm,std.array,std.conv,std.stdio;void main(string[]a){alias reduce r;auto b=array(splitter(a[1],","));auto s=map!((a){int n=r!"a+b"(map!"cast(int)(a-'A')+1"(a));while(n>9)n=r!"a+b"(map!"cast(int)(a-'0')"(to!string(n)));return n;})(b);int v=r!"a>b?a:b"(s);writeln(count(s,v)>1?"STALEMATE":b[countUntil(s,v)]);} ``` More Legibly: ``` import std.algorithm, std.array, std.conv, std.stdio; void main(string[] a) { alias reduce r; auto b = array(splitter(a[1], ",")); auto s = map!((a){int n = r!"a + b"(map!"cast(int)(a - 'A') + 1"(a)); while(n > 9) n = r!"a+b"(map!"cast(int)(a - '0')"(to!string(n))); return n; })(b); int v = r!"a > b ? a : b"(s); writeln(count(s, v) > 1 ? "STALEMATE" : b[countUntil(s, v)]); } ``` [Answer] ## Mathematica Some details still missing ``` a = {"ZOO"}; b = {"NO"} f = FixedPoint[IntegerDigits@Total@# &, #] & If[(s = f /@ NestWhile[(# /. Max@# -> 0 &) /@ # &, (ToCharacterCode @@ # - 64) & /@ #, f[#[[1]]] == f[#[[2]]] &, 1, 5] &@{a, b})[[1, 1]] > s[[2, 1]], a, b, "STALMATE"] {"NO"} ``` [Answer] # Mathematica 220 207 After writing this, I noticed that this follows the same reasoning that Belisarius used, ``` h@u_ := ToCharacterCode@u - 64; m@w_ := FromCharacterCode[Most@Sort@h@w + 64]; f@v_ := FixedPoint[Tr@IntegerDigits@# &, Tr@h@v]; x_~g~y_ := If[f@x == f@y, g[m@x, m@y], If[f@x > f@y, 1, 2]]; x_~z~x_ := "STALEMATE"; x_~z~y_ := {x, y}[[x~g~y]] ``` **Usage** ``` z["ZOO", "NO"] z["CAN", "BAT"] z["FAT", "BANANA"] z["ONE", "ONE"] ``` ![results](https://i.stack.imgur.com/adw3w.png) Because the response is not competitive (being so long-winded), I decided to use an input format more congenial to Mathematica. [Answer] # CoffeeScript - 335 ``` z=(a,b,g=a,h=b)->c=y a;d=y b;e=a.length;f=b.length;return g if(c>d);return h if(d>c);return g if(e<2&&f>1);return h if(f<2&&e>1);return "STALEMATE" if(f==e&&f<2);z(x(a),x(b),a,b) y=(a)->t=0;t+=c.charCodeAt(0)-1 for c in a;t-=9 while 9<t;t x=(a)->for i in[90..65] b=new RegExp(String.fromCharCode(i));return a.replace b, "" if b.test a ``` Not as happy with this one as I might have been, but I'll put it up anyway. The actual scoring is very concise (`y` function), but the `if`s to compare results (in `z`) get pretty long. To use it call `z` with your two words (e.g. `z 'FOO','BAR'`). It will score both words and return the higher scoring word. If it's a tie, it will recurse with the modified words (keeping the originals to return eventually, hence the extra two parameters) which it gets from the `x` function. The equivalent (expanded) javascript for those interested: ``` var x, y, z; z = function(a, b, g, h) { var c, d, e, f; if (g == null) { g = a; } if (h == null) { h = b; } c = y(a); d = y(b); e = a.length; f = b.length; if (c > d) { return g; } if (d > c) { return h; } if (e < 2 && f > 1) { return g; } if (f < 2 && e > 1) { return h; } if (f === e && f < 2) { return "STALEMATE"; } return z(x(a), x(b), a, b); }; y = function(a) { var c, t, _i, _len; t = 0; for (_i = 0, _len = a.length; _i < _len; _i++) { c = a[_i]; t += c.charCodeAt(0) - 1; } while (9 < t) { t -= 9; } return t; }; x = function(a) { var b, i, _i; for (i = _i = 90; _i >= 65; i = --_i) { b = new RegExp(String.fromCharCode(i)); if (b.test(a)) { return a.replace(b, ""); } } }; ``` [Answer] ## Racket 479 bytes ``` (define(dl n)(let p((ol '())(n n))(let-values(((q r)(quotient/remainder n 10)))(if(= q 0)(cons r ol)(p(cons r ol)q))))) (define(dr N)(let p2((n N))(define s(apply +(dl n)))(if(< s 10)s(p2 s)))) (let p3((l(for/list((i(string->list s)))(-(char->integer i)64)))(k(for/list((i(string->list t)))(-(char->integer i)64)))) (let((a(dr(apply + l)))(b(dr(apply + k))))(cond[(> a b)s][(< a b)t][(equal? l k)"STALEMATE"][else(p3(remove*(list(apply max l))l)(remove*(list(apply max k))k))]))) ``` Ungolfed: ``` (define (f s t) (define (getDigitList n) ; sub-fn to get digit list (let loop ((ol '()) (n n)) (let-values (((q r) (quotient/remainder n 10))) (if (= q 0) (cons r ol) (loop (cons r ol) q))))) (define (digit_root N) ; sub-fn to get digital root of a number (let loop2 ((n N)) (define s (apply + (getDigitList n))) (if (< s 10) s (loop2 s)))) (let loop3 ((l (for/list ((i (string->list s))) ; actual fn to compare 2 strings (- (char->integer i) 64))) (k (for/list ((i (string->list t))) (- (char->integer i) 64)))) (let ((a (digit_root (apply + l))) (b (digit_root (apply + k)))) (cond [(> a b) s] [(< a b) t] [(equal? l k) "STALEMATE"] [else (loop3 (remove* (list (apply max l)) l) (remove* (list (apply max k)) k) )] )))) ``` Testing: ``` (f "CAN" "BAT") (f "ZOO" "NO") ``` Output: ``` "CAN" "NO" ``` [Answer] **JAVA** ``` public static void main(String args[]) throws Exception{ String input=(new BufferedReader(new InputStreamReader(System.in)).readLine()); StringTokenizer st = new StringTokenizer(input, ","); String w1 = st.nextToken();String w2 = st.nextToken();int s1=0;int s2=0; String flag=""; do{ Integer sum1=0;Integer sum2=0; for (int i=0;i<w1.length();i++) sum1+=((int)w1.charAt(i) - 64); for (int i=0;i<w2.length();i++) sum2+=((int)w2.charAt(i) - 64); while (sum1.toString().length()>1){ s1=0; for (int i=0;i<sum1.toString().length();i++) s1+=((int)sum1.toString().charAt(i)-48); sum1=s1; } while (sum2.toString().length()>1){ s2=0; for (int i=0;i<sum2.toString().length();i++) s2+=((int)sum2.toString().charAt(i)-48); sum2 =s2; } flag=(s1>s2)?w1:(s1!=s2)?w2:""; if (flag!="") {st = new StringTokenizer(input,","); if (s1>s2) System.out.println(st.nextToken()); else{ st.nextToken(); System.out.println(st.nextToken()); } } int max=0; for (int i=0;i<w1.length();i++){ max=((int)w1.charAt(i)>max)?(int)w1.charAt(i):max; } w1 = w1.replace((char)max, (char)64); max=0; for (int i=0;i<w2.length();i++){ max=((int)w2.charAt(i)>max)?(int)w2.charAt(i):max; } w2 = w2.replace((char)max, (char)64); }while(flag=="" && !w1.equals(w2)); if (flag.length()<1) System.out.println("STALEMATE"); } ``` [Answer] C++, 473 (I'm borrowing a course iron) ``` #include<iostream> #define $ string #define _ return using namespace std;$ S($&s){int i=-1,m=i,x=0;while(++i<s.length())if(s[i]-'@'>x)m=i,x=s[i];s.erase(m,1);_ s;}int M($ w){int i,v=0;for(i=0;i<w.length();++i)v+=w[i]-'@';while(v>9){i=0;while(v)i+=v-v/10*10,v/=10;v=i;}_ v;}$ B($ x, $ y){while(!(M(x)-M(y)))S(x),S(y);if(M(x)>M(y))_ x;if(M(x)<M(y))_ y;_"STALEMATE";}int main(int c,char**v){$ s;cin>>s;$ x=s.substr(0,s.find(',')),y=s.substr(s.find(',')+1);cout<<B(x,y)<<endl;_ 0;} ``` I'm sure I could shorten it up somehow, but I'm tired. Edit: originally took command line argument, modified to use cin. It's probably a few characters longer now but I'm too tired to recount it. [Answer] **Python :383 chars** run the function `c('CAN','BAT')`: ``` def k(j): l=list(j);l.remove(max(j));return''.join(l) def f(x): x=str(x) if len(x)==1 and x.isdigit():return int(x) return f(sum('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.index(y)+1 for y in x)) if x.isalpha() else f(sum(map(int,x))) def c(a,b): v=f(a);u=f(b); if v>u:return a if v<u:return b return'STALEMATE' if v==u and (len(a)==1 or len(b)==1)else c(k(a),k(b)) ``` [Answer] # F#, ~~559~~ ~~533~~ 530 bytes Not competitive as of yet. I'm sure *c* can be made shorter as well as the last few lines. Not having easier access to command line args is also hurting here. ``` open System let m=Seq.map let a s=s="";s.ToUpper()|>m(fun c->int c-64) let rec c i=if i>9 then string i|>m(int>>(-))|>m(fun x->x 48)|>Seq.sum|>c else i let b i=Seq.fold(fun(r,a)j->(Seq.sum i-a)::r,a+j)([],0)(Seq.sortBy(~-)i)|>fst|>m c [<EntryPoint>] let x z= let y=z.[0].Split(',') let u,v=y.[0].Length,y.[1].Length printf"%s"(Seq.fold2(fun s l r->if l=r then 3::s else if l>r then 0::s else 1::s)[](b<|a y.[0])(b<|a y.[1])|>Seq.tryFind((>)3)|>function|None when u>v->y.[0]|None when u<v->y.[1]|Some x->y.[x]|_->"STALEMATE") 0 ``` [Try it online!](https://tio.run/nexus/fs-mono#TVDRboIwFH3nK25IFtsMjEyzbEyauMQ9OV2Ce5khC2LRGiiMFieG7NdZC8zsqfece@85PbfJcsrBr4SkqZFQCann069hGuYtCkF4wjPNJzFcZ@95TguEa5KiuOQQ2YRxqZ77CW6HCxpBBMxjMTDyCPKglIUsGN8D00tqmhBk46vC2SZnmDworD1FmdYkApoICqwV3Cox3YmzZKcXUGGF@GgT1I8Ds0Psuoq9PWK0CawR7lpZIZ8r9GNjprRjIZUhRMZmOueyqN4y/ZGgdTjDxTNAV5V3GW5GwdDPEybRwBrgji@tk1e1nQXle3mwFHD@gAG5iidj80aY6O@nd202AQkU6kIxJF7R3WLsuqKPp1jSs6Mr66gKbwK0ndYhtJ74WjtBfyUV4IXxHUIEj3W4kkeSZbxeZpzCtxYsyckm7fp/ctqRTlD7WUr16RU6B/WnTUx/PVvMX2frualCj5qm@VitrOXqFw "F# (Mono) – TIO Nexus") * Saved 3 bytes by constraining s to string by comparing it with string # Ungolfed version ``` open System let m=Seq.map // this is just to save some characters and I'll use Seq.map for this version let toIntList s = s = "" // constrain s to type string s.ToUpper() |>Seq.map (fun c -> int c - 64) // converts char value to int and offsets it so that A=1 let rec digitSumUntilSingle i = if i > 9 then string i // convert number to string |>Seq.map ( int>>(-) ) // convert individual char to int and partially apply substraction // this returns a function |>Seq.map (fun x -> x 48) // provide last parameter for substraction, this is equivalent to // charValue - 48 |>Seq.sum // sum over all digits |>digitSumUntilSingle // recursively call this function again in case we are >9 else i let calculateDigitalRoot input = Seq.fold(fun (result, acc) current -> // calculate digital root for all possible iterations (Seq.sum input - acc)::result, // basically, this calculates Rule 3 until the end for a given word acc + current ) ([], 0) (Seq.sortBy (~-) input) // sort input by value descending |>fst // only interested in the lits, not the final accumulator |>Seq.map digitSumUntilSingle [<EntryPoint>] let main (args) = let y = args.[0].Split(',') let leftLength = y.[0].Length let rightLength = y.[1].Length Seq.fold2 (fun state left right -> if left = right then 3::state else if left > right then 0::state // 0 is chosen because this represents y[0] index else 1::state ) [] (calculateDigitalRoot (toIntList y.[0])) (calculateDigitalRoot (toIntList y.[1])) |> Seq.tryFind ((>) 3) // try to find first variation where left and right digital root isn't equal |> function | None when leftLength > rightLength -> y.[0] | None when leftLength < rightLength -> y.[1] | Some x -> y.[x] | _ ->"STALEMATE" |>printf "%s" 0 ``` [Answer] # PHP, 339 (not to spec), 410 382 359 339 337 Bytes ``` $b=$w=fgetcsv(STDIN);function a($c){for(;a&$g=$c[$p++];)$f+=ord($g)-64;$f=trim($f);for(;$f[1]&a;$f=$h)for($h=0;a&$r=$f[$q++];$h=bcadd($h,$r));return$f;}function d($f){return strtr($f,[max(str_split($f))=>'']);}for(;$c==$d;$b=[$e,$f]){$x=$z++?d:trim;$e=$x($b[0]);$f=$x($b[1]);$c=a($e);$d=a($f);$e||die(STALEMATE);$c!=$d&&die($w[$c<=$d]);} ``` **EDIT 1**: +71 bytes. Using `STDIN` instead of `fopen('php://stdin','r');` and short tags. Also, full conformance to the spec. **EDIT 2**: -28 bytes. Using `fgetcsv(STDIN)` instead of `explode(',',trim(fgets(STDIN)))`, and used `for` loop instead of `while` loop. **EDIT 3**: -23 bytes. Merged functions `a` and `b`, merged for loops. **EDIT 4**: -20 bytes. Turned `c` from a recursive into a loop. Then, removed function `c` and put its code into the global namespace. **EDIT 5**: -2 bytes. Thanks to @Titus for the `-r` flag. [Answer] # PHP, ~~296 281~~ 267 bytes ``` function f(&$s){for(;$c=$s[$i++];$m>$c||$m=$c)$p+=ord($c)&31;for($s=str_replace($m,'',$s);9<$p=array_sum(str_split($p)););return$p;}for(list($a,$b)=$x=fgetcsv(STDIN);$s==$t&&$a&$b;$t=f($b))$s=f($a);echo($s-=$t)||($s=strlen($x[0])-strlen($x[1]))?$x[+($s<0)]:STALEMATE; ``` run with `-n` or [try it online](http://sandbox.onlinephpfunctions.com/code/3566230223fa0542e4edc7dd9ef85cd26fc8a3a9) (TiO includes breakdown). Back in Feb 2011, the current PHP version was 5.3.5; so I could not * use shorthand list assignment (`[$a,$b]=fgetcsv(...)` and such) * alias `count_chars` inline * index function results directly * use negative string indexes instead of `substr` But neither would have saved a lot; so it doesn´t matter much. Most costly things were the loops (of course) and rule #4 (~~40~~ 36 bytes). ]
[Question] [ I like golfing in [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp): ``` (d M(q((x)(i x(i(disp x)0(M x))0 ``` But I also like posting explanations with nicely formatted code: ``` (d M (q ((x) (i x (i (disp x) 0 (M x)) 0)))) ``` Can you help me generate the ungolfed code for my explanations? ## The task Given a line of tinylisp code, return or output the same code, formatted to the following specifications: ### Input syntax Tokens in tinylisp are `(`, `)`, or any string of one or more printable ASCII characters excluding parentheses or space. (I.e. the following regex: `[()]|[^() ]+`.) A non-parenthesis token is called an *atom*. Spaces are ignored, except insofar as they separate tokens. For this challenge, the input code will consist of a single parenthesized list containing 0 or more items. The items in the list may be either (arbitrarily deeply nested) lists or single-token atoms (or a mixture). Two items may be separated by a single space; the space may also be omitted, unless it is necessary to separate two adjacent atoms. There will not be spaces anywhere else in the input; in particular, there will never be spaces immediately after an opening parenthesis or immediately before a closing parenthesis. Closing parentheses at the end of the expression may be omitted. Some examples: ``` () (1 2 3) (1 2 3 (1 (2)) (1(2)) (1(2 (1((2 3))4 (((((xyz))))) ((((( ``` ### Nesting levels We define a *nesting level* for a tinylisp expression as follows: * Atoms and the empty list `()` have a nesting level of 0. * A nonempty list has nesting level N+1, where N is the maximum nesting level of its items. Some examples: ``` Expression Nesting level () 0 (1 2 3) 1 (1 2 ()) 1 (1 (2)) 2 (1 ((2)) 3) 3 ((((())))) 4 ``` ### How to ungolf To ungolf a tinylisp expression, first **supply any missing closing parentheses**. Then, **add newlines and whitespace** according to the following rules: * For an expression of nesting level 0, do not add any whitespace. * For a list of nesting level 1 or 2, make sure the elements of the list are separated by a single space. * Lists of nesting level 3 or higher must be broken across multiple lines: + The first element of the list should be on the same line as the opening parenthesis, with no whitespace in between. - More specifically, the first element should *begin* on the same line. If the first item itself has nesting level 3 or higher, it will of course be spread over multiple lines itself. + IF the second element of the list has nesting level 0 or 1, place it on the same line as the first, with a space in between; otherwise, if its nesting level is 2 or higher, place it on its own line. + The third and subsequent elements of the list must each be on their own line. * Elements on their own line must be indented by a number of spaces equal to how deeply they are nested in the expression. The top-level list should be indented 0 spaces, its elements 1 space, their elements 2 spaces, etc. * The closing parenthesis at the end of a list should immediately follow the last element of the list, with no whitespace in between. ### A worked example Suppose this is our input: ``` (d E(q((n)(i(l n 2)(s 1 n)(E(s n 2 ``` First, supply missing close-parens: ``` (d E(q((n)(i(l n 2)(s 1 n)(E(s n 2)))))) ``` The outermost list has nesting level 6, so it must be split over multiple lines. Its second element is `E` (nesting level 0), so we keep that on the same line. We place the third element on its own line, indented by one space. ``` (d E (q((n)(i(l n 2)(s 1 n)(E(s n 2)))))) ``` The next list has nesting level 5. Its second element has nesting level 4, so it goes on its own line, indented by two spaces. ``` (d E (q ((n)(i(l n 2)(s 1 n)(E(s n 2)))))) ``` The next list has nesting level 4. Its second element has nesting level 3, so it goes on its own line, indented by three spaces. ``` (d E (q ((n) (i(l n 2)(s 1 n)(E(s n 2)))))) ``` The next list has nesting level 3. Its second element has nesting level 1, so it goes on the same line as the first element, separated by a space. We place the third and fourth elements on their own lines, indented by four spaces. ``` (d E (q ((n) (i (l n 2) (s 1 n) (E(s n 2)))))) ``` The list `(s 1 n)` has nesting level 1 and thus goes on one line. It has spaces between its elements, so it is already ungolfed. The list `(E(s n 2))` has nesting level 2 and thus goes on one line. It needs spaces between its elements. Final result: ``` (d E (q ((n) (i (l n 2) (s 1 n) (E (s n 2)))))) ``` ## I/O requirements and clarifications Your solution may be a program or function. You may use any of the [default I/O methods](https://codegolf.meta.stackexchange.com/q/2447/16766). Input must be a string, a list of characters, or the nearest equivalent in your language. You may not take input as a nested list; parsing the input is part of the challenge. Output may be a multiline string; it may also be a list of strings, each string representing one line. It may optionally contain trailing spaces and/or leading or trailing newlines. It may not contain extra leading spaces. The input will always represent a single (possibly nested) list. Thus, it will always start with `(`, never an atom. The number of opening parentheses will be greater than or equal to the number of closing parentheses. The input will not have any leading or trailing whitespace. The input will consist only of printable ASCII characters; in particular, it will not contain newlines or tabs. ## Reference solution Here's a reference solution in Python 3: [Try it online!](https://tio.run/##dVHBasMwDL3nK0ROMh0l7W5l3aWnwS5l0EuaQUoV6tV1MscdK@zfM8mxS1fYzdZ7enp66i7@0NrHYdCnrnUeHGWZb49kX3XvYcn/aaPtvjYG8/IdFVSTn@1b/gDadmePSmXZnhroatcThsYXT04tMvCOiAXKKgNDX2T4XWTQtA4CjQXgymc66CYCyyXkKpcS7BzVx3sMR6w/7@KI@@GCppGn@hvD@yE1lEUFE5gFVhCYsMmIsVcg09PiH4m7rjCSexz5s7NQBpaoC4NzvLWn2Rleky1niyplx5Gcao/Cllj3ZP0y5wjYhOx96ShgCnQPhnvFnKP@bOQ@nEYWsmD9Uy95Rzn5Jzl2JIIhfKmH7CUKdlHFeGMyzzAPy3PJkI2DU/GPn3JeBUu29cEWyGXHugg9pZ7klQNLNscTsKWRcOP@ymBn4cjUyZJbm3PDuMztiSIchOIR0jTBph@ttpg0lcxUTE3tsWM8Vue09XhzC6WGAfewwk/ENWwUalijRgNrKFTBvw3WuMKeqweGFTNW/PbyVoVSs18) ## Test cases ``` () => () (load library => (load library) (q(1 2 => (q (1 2)) (q((1)(2 => (q ((1) (2))) (q '"""\ => (q '"""\) ((((( => ((((())))) (d C(q((Q V)(i Q(i(l Q 0)0(i V(a(C(s Q(h V))V)(C Q(t V)))0))1 => (d C (q ((Q V) (i Q (i (l Q 0) 0 (i V (a (C (s Q (h V)) V) (C Q (t V))) 0)) 1)))) ((q (g (c (c (q q) g) (c (c (q q) g) ())))) (q (g (c (c (q q) g) (c (c (q q) g) ()))))) => ((q (g (c (c (q q) g) (c (c (q q) g) ())))) (q (g (c (c (q q) g) (c (c (q q) g) ()))))) (d f(q((x y z p)(i p(i(l p 0)(f(s x p)y(a z p)0)(i x(f(s x 1)(a y 1)z(s p 1))(i y(f x(s y 1)(a z 1)(s p 1))(f x y z 0))))(c x(c y(c z( => (d f (q ((x y z p) (i p (i (l p 0) (f (s x p) y (a z p) 0) (i x (f (s x 1) (a y 1) z (s p 1)) (i y (f x (s y 1) (a z 1) (s p 1)) (f x y z 0)))) (c x (c y (c z ()))))))) (def even? (lambda (num) (divides? 2 num))) => (def even? (lambda (num) (divides? 2 num))) (def odd? (lambda (num) (not (divides? 2 num)))) => (def odd? (lambda (num) (not (divides? 2 num)))) (def divides? (lambda (divisor multiple) (if (negative? divisor) (divides? (neg divisor) multiple) (if (negative? multiple) (divides? divisor (neg multiple)) (if (less? multiple divisor) (zero? multiple) (divides? divisor (sub2 multiple divisor))))))) => (def divides? (lambda (divisor multiple) (if (negative? divisor) (divides? (neg divisor) multiple) (if (negative? multiple) (divides? divisor (neg multiple)) (if (less? multiple divisor) (zero? multiple) (divides? divisor (sub2 multiple divisor))))))) ``` This is code-golf; the shortest answer in each language (in bytes) wins. [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 1022 bytes ``` (load library (d ? contains? (d r reverse (d O last (d _(q((S T C)(i S(i(e(h S)32)(_(t S)(i C(c(r C)T)T)())(i(?(q(40 41))(h S))(_(t S)(c(h S)(i C(c(r C)T)T))())(_(t S)T(c(h S)C))))(r(i C(c(r C)T)T (d @(q((T A D)(i T(@(t T)(c(+(w T)D)A)(+(w T)D))(r(c(+(w T)D)A (d w(q((T)(-(e(h T)40)(e(h T)41 (d #(q((T A)(i A(#(c 41 T)(- A 1))(r T (d E(q((T)(max(@ T()0 (d p(q((L A)(i A(p(c 32 L)(- A 1))L (d n(q((D T A)(i(l 0(h D))(n(t D)(t T)(c(h T)A))(r(c(h T)A (d N(q((T)(n(@ T()0)T( (d H(q((T A)(i T(i(*(e(h T)40)(e(cadr T)41))(H(t(t T))(c(q(40 41))A))(H(t T)(c(h T)A)))(r A (d W(q((L)(i(c()L)L(c L( (d :(q((I L)(i I(:(- I 1)(t L))L (d ;(q((L)(:(s(last-index(r(@(r L)()0))1)1)L (d }(q((D T)(i(l 0(h D))(}(t D)(t T))(t T (d f(q((T S P)(i T(f(t T)(concat S(i(e(h T)41)(c 41())(i(+(l(E(N(concat(; P)T)))3)(*(not((q((T)(}(@ T()0)T)))(t(; P))))(l(E(N T))2)))(p(W(h T))(- 1(?(q(()40))(O P))))(i(e(O P)40)(W(h T))(c 10(p(W(h T))(O(@ P()0))))))))(insert-end(h T)P))S (d F(q((S)(string(f(H((q((T)(#(r T)(last(@ T()0)))))(_(chars S)()()))())()( ``` [Try it online!](https://tio.run/##zVVNT@MwEL3zKyxxGe@qku2mJYEDrfgQSBUgNRJHlE3LEqmk3TRa4MBv786M7XwUaLuLVrsttOPxzHvzxuO0zPKXWbZcrFYwmycTMcu@FUnxsgcTcSzSeV4mWb48pmUhiunPabGc0uJazJJlSdYd/AAYi1icSMjEGDKYwoMYy66RcAclWug@gRQKjIjxDRI9cIxpgRKBxhWFV8EpL9dyOMkGxC7iROILinYgFTSggmIxFKeEEsMA02LC/QpPaJzKoaxMAmhsUPoTp0vosI5YBkp6S9P@voMn8CHsQ4oaCL@DjCSmEFzFmYN5TJ5hgFVIRd4FeUc@eYHJXSNGVfKIYnKKORWWAmZCITlVmqMOlOTEUEFDVz/blHrlSHNHic0i90Wj5Bgxv7SkpcmkYHWIdgElExBDdT5Du9HiJZ1MecuKqNIU5EiOUNKISQ9p45LEZeISDlHiJUpEmJHTeeQyD2EJNEydLJ9Mn1HQALHRj@VLjW8OfnVNabfktW4Jf1LkvRU7FjdW7r2rfJ6nSVnNJ@vls7Pj@BVmcAZXLgyOMBsxZVdis/J5Ca6xr1VjqQU2jixOpioMrRZwyxR0rponHajXEq5dONVANh2AD02FVo3Ma2S64R7YF@A1nBZlZ5pPOAKBxiT3nK@fhGVZZPl3VHvha92nUZTcWl81A91B@pAUS7pkdK34aklYUevmxSP26Fzu7e2BWzhgAfiQKIWbCPnxtlah0FqL6ABNRePNHtUTEW0EvIFf2mzB0V1miwiip3aK5XC8jWjskIG4XUQP3F9kNmY0/ihuUwNYdf@gXVmoyRv2XX3UEFpXC9c668PPIOTIsBncp0XEwB6@hRI0KHTNhbF1kO63ghyHNaLNyuq@MZu3omjdcFEsXtsR8NYfxNeF6tr5HxRiL8L2SdDKtEdBG@s3lsIYy2nao8GO9dkgZz0cqsa2KQ7YQhG@nZe3LOEal1EfolVXygPp2kuojQRXXOQb1MCvqm2w6d4bwPV6K@8mCtPU3mpqPdo@2h61q8AvWjtmpxuula6YydSh@8brVk9maB@DET/7lNfGcujf7tUzrWzDLFiv5kHtFrTnzreVXI3izgVr7VyfKZad2j9QPlm@v0y793wb1xZJ6/m659QEFj5yJYYs0Ib4n7LmY4i5TbMnXGTX/sz1GyTaFbaJ@jdGYY1uJ@C/K2tn7G3SthzOe8q3cn8kTYUVebOAzXg7n6LxT4eAN/9Jp3pMhhfA3b5Pa3vvZ3D1Cw "tinylisp – Try It Online") This took several ~~hours~~ days, but now it actually works. This emits a couple of errors, which I think are unavoidable, and now a lot more which are avoidable. -18 thanks to DLosc. Because tinylisp doesn't have string literals, you'll need to pass your input through [this python script](https://tio.run/##hY1BDoIwEEX3nGLChpmNC9254SgGaMEx0JJ2IEHj2bEIAokxdtX8@e/9dpCrNadxVLoEsRdhM9TsW/Ti2FR0jgDAaemcgTJeUsBQEXgkkBxuls0Uo3UKC6LSOiiADSyCJ1EcRW34C@79MU6LintW2qfBmDW5ygCnxAdH09XCba0JkEtAo6tMuNcpLAWaqzMcrlv@k9wdVvQz91ashQWttfcbtlu@a2f/@HyXH7/R@cVE4/gC). [Ungolfed](https://tio.run/##zVhLb@M2EL77V7CnSl0YEOVHrF6C3nvsvWBkOhIiS67EbJJfnw7JITmUZMvpomgBryORw5lvPs7Lq@r2o6mHy@dn0nTiyJr6qRf9R7pKyu58lq1aMaa6F9myQQklf2W/gcigWHdiyaD6un222wMrX/se5NfmNYVjf4gXOTDh5ctK9AN7kqV4HSRTVQffopdMiqGWPahhb13/wt5qVaWrVXKUJ/Yn6k4acX46CmOS2gvGkvoECHt4ss8Av1WibodHOKwBbHLGs5QllRZLUyNoRYMiXIRlb1gZcaMO3nr5XfYAm9hGOCDilc6cd69pZHkCcpuxLZ@AvApzaohsMQe6mu6wOxwa6Yrer/FTUW9T6u4NTqKjBIg77EAuXNmiQ17UOagNYJyVR3lRVYgzxGZXRVmmDGPMblhc/pTyHjMH8hueTd6quqzWFwj0dswsQr4paozP86BPB/fvMcistuA3lR35bj1eW8vyr1fRPOrwhHuKlPotTrcos9350kglJ9yKc/faKk@sfXXE@kOGIlDuQ2qNkoyPaCHG0fY109YmMTLSoOUhGf39IuDMxHNQL98v/Xo2bkxBOnXNsWFn8Z6jF9mixgsUYK@q8RRNGWKJETVqobA1s8To5XAPrXxXaw15PsgHExpoKWmYuWm743imKkLEwyOK@diHgiZ7kGyPJCZoIN8Q8ICv4jUgCRZXRua4tfw6CirRHhu5butmGozBeZrh9cn59EvINIx4gnybpdPtUhz7IMFD1kc4FOHSl1HaCwJt06P@DlwJjamM0yOm91lipx5oxGFmBCsrrDQ2U1ajSt7ojmY4joh@68Xlp0itiyv1cZGP@tjv4KHF1yDVxufGpS8OHyyJcGqR4oEVB1YUmh94huj3r1AmNM/@vk9dfxZqctd6hqjbo1Z/AXLWJKwm1z972zzchzMR7oL07BDlgCzqwZCsiICnsweIOYqRDA8k4GBgkj3tzo0c9EhBCxRJJwiWUmMemrqUkfpQQtkmavdPnaricaAe1oMETccxh/fC8DGfx0PCDUaZx@4mPb9uyiHGXTU/wRjW@WiJTWewxOQz9oCI/DSegb65O5yvCJHs/Vf7FQ7Y6E5OUaeeOjDmY5EwU1d4xqaszRM@7pzEemh2ETFiJhHu4wv1mEHZpfw44zHp3C@VwCwtK/Z3idGjL9/hRJUmS9anvjtHrVmjfnc1w7zYkkHFlWvMZt/3ZduW9ROxMCmXRJErkYPvsJrltdUawiYeD@MJ1TUBDSijcznSzmmf7OW5@w7lf2FiWJgWplrmhgaUVtPpbQmFnQMmUrfGgXTltYf6Nae27ZTmbOoAFk1SEW53K8hDzje6S20KttmaT65X4ftQwAcUfIIGF5cuUMkEABaubvPsAPq5boQ8y@xvXFjJdropcr41G/CH5wt6AKO2VmgVu@wuWSOuW252z4mIAcCV3zxBPgv@G6f3DzGwAzf87hGe5kO/@xdkzq7p@zgYyQMV3uOAAd9OfaRlS0zwYGv/QIT4PhJCG/ahWCIAWTPG3FNRjB9QyvjObQC4p38gH3DysPg/AOLGOpdoqqoH1rXy54G9QBkUrHp9hgkXshnK3AfUW3k61WVt//tqKXp4lsfhw3O7nltceW6B5nE4mYVxPOnFEFBZ0G2PoGKrSuv3Q@zIymFkK8@uavNZ6BTxsKq1kgMIrnCsEv0eLbHGdxOFY7x@9ZaJnPoekRrSwUnb@EAE7iXayW1RSFe3ywLPuDetH/kB/0KOhng@2NJZmHqZOeeMP/qf3QuZkFnGrLJdsAPOW6U7vODosA/guwFzjks/AtYscleFfhD@JAVFM3Qm7b5wDUvmF7wcn@c7dHBr1ReI@mB8tiKuI9J6ZmznlCYDcmO75Z4Y4QjslukvRMfI3F2K/1237ta95NrC5cx5vmj7mmvZwRunAG7ru/sWc1cwtmbzP2FqZ4xBAmBC/rBvc/00/fwb). I only sorta understand this, but here's the basic algorithm the code follows: * Convert the string to a list of characters for easier manipulation. * Parse the string into a list of tokens + Parentheses are left on their own, other tokens are grouped into lists. * Iterate through the string, keeping a list of the previous tokens: + If it's a `)`, immediately append it. Else: + If: - Backtrack through the previous tokens to the start of the parent expression. - Use this index to get the depth of the parent expression, is it less than 3? + *or*: - Backtrack to the parent expression - Remove the first parenthesis and remove the first expression after that. - Is it empty? - *and*: * is the current expression depth less than 2? + If so, this token should go on the same line, possibly with a space. + Else, it should be on a new line - get the depth of the current expression and indent by that. * Finally, return the string. [Answer] # Python3, 629 bytes: ``` import re d=lambda x,c=0:c if type(x)!=list or not x else max(d(i,c+1)for i in x) def p(s): r=[];S=str.lstrip while s: if(c:=s[0])==')':s=S(s[1:]);break if c=='(':s=(l:=p(s[1:]))[1];r+=[l[0]] else:r+=[l:=re.findall('[^() ]+',s)[0]];s=S(s[len(l):]) return r,S(s) def f(r,t=0): j=lambda x:x if type(x)!=list else'()' k,s=[],0 if all(d(i)<2 for i in r):k=[f(i,t+1)if d(i)else j(i)for i in r] else: for i,a in enumerate(r): D=d(a);F=f(a,t+1)if D else j(a) if not i:k+=[F] elif i==1 and D<2:k+=[F] else:k+=['\n'+' '*(t+1)+F] return'('+' '.join(k)+')' g=lambda x:f(p(x+')'*((c:=x.count)('(')-c(')')))[0][0]) ``` [Try it online!](https://tio.run/##jVNNb9pAEL37V0xz8UwgyNBLZbLKIVHuUaRegEoLXpMNi212TWr483TGfKVCJbXA9r735uutt9rUb2Xx/Ufldzu7rEpfgzdRppxeTjMNTXemknQGNod6Uxls6JtyNtRQeijKGhowLhhY6gYztN1Zp085UxZsAQ1FmcmhwkBpBF6NJsNXFWrfc3yzVQS/36wzEJjk/DhLVRglE1IqpjgN6hXDqJ9OaDj1Ri9aDcyYRCHRpao6CGjUnwx9R40ch09YKC2lLZAqb3q5LTLtHMajX0gw6cTdQKIc7ms4U6AjzsM9mnrtC/BdxvfN5@i7tUpkgPeTJ2lz6YfUjJHiCBbdwKN2k0hEUpeNofsBnHzxlC7UKGe7araLRSJobXznl7OMR2kn4YlasKsFNsV6abyuDXrpCuBJZahp@Kxy1MeMT3DIp0kkjMhm2XTBpjyLRcwzaJXqgy4yeLof/MVxVVnG4yLuxBDfouTtCLu3iDdB8N57aQtcUId3LJqf/cmxwkbAW5RtbXqzcl3UhBxGdzO@xUSyBbLdu8rbosY5intE0X4Z38W3g@S4EtKVOgNnp177zTXdCvswuC7APuF1CYzjm5ub8fiaSK5rfAaPUusFfhJaeEGLDl4goYRXP1HjIwZG35gmVjzyey3vlBD1r9ZdAc4BZ@1vBSuCOV0sSS74fyldnySXSRrYwBYqmaZqp6l4Gsx5jIbRDeqWTYRvDjAbrTmqT1teVvwUcoM5C0KLt0H8OLLMtFUS6YnbbPi/4f/2utV8Us2HKR4AD98g8inh2TL7YTMTHmAAAnwxJmcps@wiiRydy0xfpjpFnNIJEvgkL9eutpUznJsPIRZmrmv7YR7gIPjcuLBn/J@Rn4hT6LFcm@IkOIQ6E8I57FPlrfHlF/nCejq4DD19R7s/) [Answer] # Python 3, 388 bytes Basically a golfed version of the reference solution @DLosc gave ``` import re k=" " def p(e,*t,l=0): for n in e: if")"==n:break if")">n:z=p(e);l=max(l,z[0]+1);t+=z, else:l=max(l,1);t+=n, return[l,*t] t=p(iter(re.findall("[^() ]+|\S",input())[1:])) def f(t,d=k): if[*t]==t: r="(";s=[f(i,d+k)for i in t[1:]] if t[0]>2: if len(t)>2and""in t[2]or t[2][0]<2:r+=s[0]+k;s=s[1:] q="\n"+d else:q=k return r+q.join(s)+")" return t print(f(t)) ``` [Try it online!](https://tio.run/##NVHNboMwDL7zFFZO9kAVZTe69CV2pExiJWgZaQghlQDt3ZnDBhfj78fxl7glfA32ddv0ww0@gFdJLwWIpFUdOFTZS8iMzKlMoBs8WNAWFDegO0FCSlt@etX0B3C15SrZRhcjH82MJlurvE7PdAmpXDOWKTOp8iD/cMu4V@HpbWX4vDoJPEIH5dGrU6dt2xiDovpAgjr9ub2LTFv3DEhUncuaaN@1w5C1so@L6q7iKVKGuKeXAsVlklWHOmvTnmIMHWOE6K73zfk/r69F1MfOKIuBrkVjWyF2ZVGzKxbWvRWlT@UUc/U8eIpjonGU4mZF2h4hRxmv5S8Y@HQ8fQ/a4kQp39MRGELivLYBeX2ibcOWg4yIMyywgiPU/AgaDTjIiUUTzIwu2OxsHvn5Hz4TowuXlVvHNZILdiyYdnw3cTlYZvZTcuIP76y7s/4OK/4C) The regex used in the code `[^() ]+|\S` is the a shorter way of writing the regex `[()]|[^() ]+` given in the question by 2 bytes `[*t]==t` is a sneaky trick to cut back 6 bytes instead of `type(t)==list` `""in t[2]` is another trick to cut down 7 bytes instead of `type(t[2])!=list` -3 thx to @pxeger -1 thx to @aidenchow [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 330 bytes ``` ^((\()|(?<-2>\))|[^()])+ $&$#2$*) [^ (](?=\()|\)(?=[^) ]) $& {%`^(( *)\(+?([^() ]+ |((\()|(?<-5>\))|[^()])+(?(5)^) )+)(\(([^() ]+ |\(\) )*\([^)]) $1¶$2 $6 ¶ ¶ %+`^(( *)\(([^() ]+|((\()|(?<-5>\))|[^()])+(?(5)^))( [^() ]+| \([^()]+\))+)( [^() ]+| \([^()]+\))+$ $1¶$2$7 %+`^(( *)\(([^() ]+|((\()|(?<-5>\))|[^()])+(?(5)^))\)) $1¶$2 ``` [Try it online!](https://tio.run/##nVDNjpswEL77KUYpaWeCKgHStpe2HHLoOZe9xETrFJNaIoEAiUKa59oH2BdLZyghkdLVVrVAtr@/@aCyjduY8xi/P50XiBrphPGXj9E3TXSaL5AS8pX33nsXeRNS8wVggvFXkWniw3xBkBALQP0aP3EATEijH6NYIfHhdM18uM3EGB@IzeQTC65yjZrBiWaEJDh8efYi8D4peHlW/Iz9YcrF9MYIQrgIQXeexGeV/xru9UO9z/8zjCHoA85nJIV5YVLI3bIyVatwiyFEsmFIKAf4MBqNtEJZClOYCjeDR0IHM3SYwwwCCvj2iAanWDP6k2lixZTPjZwpIAo5Ywu4AvzRPVvYEqzo7kqy4N@lJK0yaXWAFo5QSrOya1ZyM8y40oHRFk3HBsIfepg/0rArpCNfS96FbDFjQd3hnYm3C8tMNyWQyVzmwG/L71F@js3A7u0mBszNepkawM1uzT1Tt3eprWOIQICuMmuLNL2TbormL/reMOCDSZC6qGC9yxtX5pYTXMYpdmUat7cx9ILbEsJe8VedN8RgvYzrIgZBb81tXV9tN5OPtireyKt3y@je@mf9Bg "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ^((\()|(?<-2>\))|[^()])+ $&$#2$*) ``` Use a .NET balancing group to count how many extra `(`s there are and append that many trailing `)`s. ``` [^ (](?=\()|\)(?=[^) ]) $& ``` Insert spaces before `(`s and after `)`s where necessary. ``` {` ``` Repeat until no more transforms can be made. ``` %`^(( *)\(+?([^() ]+ |((\()|(?<-5>\))|[^()])+(?(5)^) )+)(\(([^() ]+ |\(\) )*\([^)]) $1¶$2 $6 ¶ ¶ ``` Split lists of nesting level 3 or more. ``` %+`^(( *)\(([^() ]+|((\()|(?<-5>\))|[^()])+(?(5)^))( [^() ]+| \([^()]+\))+)( [^() ]+| \([^()]+\))+$ $1¶$2$7 ``` For those lists, where there are only lists of nesting level 0 or 1 left, put all but the first on their own line. (We need to check explicitly to ensure that the list was in fact split in the first place.) ``` %+`^(( *)\(([^() ]+|((\()|(?<-5>\))|[^()])+(?(5)^))\)) $1¶$2 ``` Lists of nesting level 0 or 1 after a list of nesting level 2 or more also need to go on their own line. (We know they can't have also nesting level 2 or more because they would have been split off earlier, so we don't actually need to check their nesting level.) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 166 bytes ``` ⊞υ⟦⟧≔ωηF⁺θ×)⁻№θ(№θ)«F№( )ιF›ηω«⊞§υ±¹⟦η¹⟧≔ωη»≡ι ω(⊞υ⟦⟧)«≔∨⊟υ⟦⟦ω⁰⟧⟧ι≔∧⊖Lι›³§§ι¹±¹δ≔⌈Eι⊕⊟κζF›⁴ζ≔⊖Lιδ≔E§ι⁰⁺§ (¬λκεFδ⊞ε⁺⁺⊟ε ⊟§ι⊕κFΦι›λδFκ⊞ε⁺ λ⊞ε⁺⊟ε)⊞εζ⊞§υ±¹ε»≔⁺ηιη»✂⊟⊟υ⁰±¹ ``` [Try it online!](https://tio.run/##dVLBbqMwED3DV4w4jSVWIto9tadoV60qbdtI21uUAzImWHGAYmgIVb@dzhhYoFI5YPnNm3lvxiOzuJJFbPp@19gMmxD2B3Hrb63VxxwvIWR0S4sKcGcai68hvOizshiIIIRHnRP2u2jymiMBoSHMVxEI/uDd91yFIRIgcK6mgEPvKxXXqsIshMtA9pyVbf2QJ6plS0/qSBTcCCq/J96GLXre2qT34Xv2omuZAWpXR8ZWQQDBDewqTcoXZg0gMrhseMQF4e9z6ecKd0WJDevuSSc6HARbX6hv8wT/KFmps8prleBflR/rjBwQcWrtZwhTN9OpqQux7Iz5ybLwY9zqc3Oms2T2Qz5rsKfTkNK5lNUgfzEqYCzznbcvWuXSWURx99wTFgDSkz0VNRrOPfFPzcqJGIapxrThRyYV8egBuFyxUlh24zqZi91pw13oeXyG3U7rcvqiReVDMEP@2sSkz2u4jHbz7ZsdU@M6JSqNG1PfTLN0dTNegP8r9@EPu/XPaKmc5rAwxIhWz3vb95hAiq@ILVyhg1KgBnpaNFDSxDFFCy2hV4xdNOJ4O8IbQeiVjo6uJZ0cvGJKBOtwl0THFKWIU4l4tiiJJ4kvoUO///FmPgE "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υ⟦⟧ ``` Add a dummy container to the predefined empty list to hold the final result. ``` ≔ωη ``` Start off with no atom. ``` F⁺θ×)⁻№θ(№θ)« ``` Append enough trailing `)`s to balance the input and loop over its characters. ``` F№( )ιF›ηω«⊞§υ±¹⟦η¹⟧≔ωη» ``` If the current character is one of `( )` then push any current token to the most recent expression. (Note that my nesting levels are one greater than those used by the question, because the nesting level of `()` evaluates to `1`.) ``` ≡ι ω ``` If the current character is a space then do nothing more at this point. ``` (⊞υ⟦⟧ ``` If the current character is a `(` then start a new subexpression. ``` )« ``` If the current character is a `)`: ``` ≔∨⊟υ⟦⟦ω⁰⟧⟧ι ``` Get the latest expression, or an empty token if there wasn't one. (Since this makes `()` contain an empty token with a nesting level of `0`, its nesting level evaluates to `1`.) ``` ≔∧⊖Lι›³§§ι¹±¹δ ``` Calculate whether the second term should be concatenated to the end of the first. ``` ≔⌈Eι⊕⊟κζ ``` Calculate the depth of this term. ``` F›⁴ζ≔⊖Lιδ ``` If this term is shallow enough then concatenate all the terms together. ``` ≔E§ι⁰⁺§ (¬λκε ``` Indent the first term, except for the first line, which is prefixed with a leading `(` instead. ``` Fδ⊞ε⁺⁺⊟ε ⊟§ι⊕κ ``` Concatenate the desired number of terms to the first term. ``` FΦι›λδFκ⊞ε⁺ λ ``` Indent and append any remaining terms. ``` ⊞ε⁺⊟ε) ``` Append a final `)` to the last line. ``` ⊞εζ ``` Append the nesting level to this term. ``` ⊞§υ±¹ε ``` Append this term to its parent expression. ``` »≔⁺ηιη ``` For any other character, append it to the current token. ``` »✂⊟⊟υ⁰±¹ ``` Output the pretty-printed expression, excluding its nesting depth. ]
[Question] [ # Challenge ## Premise Bob lost1 Alice's precious grand piano. Big mistake. Alice has now stolen Bob's low-orbit ion cannon. Alice refuses to just make up with Bob, so let's help her give him a *light tap* on the roof. Suppose that from the top Bob's house looks like a lattice polygon, where all points have integer coordinates... 1. So he says. ## Task **Input:** an \$n\times2\$ matrix of integers (where \$3\leq n\leq16\$) representing the coordinates of the points of an \$n\$-gon, given in the order in which you would join them up. To be absolutely clear, the first and second values in each of the \$n\$ rows are respectively an \$x\$- and a \$y\$-coordinate. * If it would be far more natural to take something other than a 2D matrix in your language or it's impossible to take one, you can use something else. Should this happen, please clearly state what you're doing. * \$x\$-coordinates or \$y\$-coordinates may be negative, zero or positive. * The polygon formed by joining up the points in the given order may be convex or concave. * There's no need to consider [degenerate polygons](https://cs.stackexchange.com/questions/12521/what-are-degenerate-polygons). * No input polygon will be self-intersecting, thank goodness. **Output:** two numbers of any numeric type, respectively representing the \$x\$-coordinate and \$y\$-coordinate of a point within the polygon. * No, your numbers needn't be integers. * Your output needn't be consistent for any single input. You're allowed to generate an output in any valid way that shortens your code. * Corners and edge points are forbidden. Sorry. ### Example 1 Input: ``` 0 0 3 0 3 4 ``` Possible output: `1 1` ### Example 2 Input: ``` -3 -1 0 1 -1 -1 -1 0 ``` Possible output: `-0.31416 0.42` # Remarks * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins. * The [random](/questions/tagged/random "show questions tagged 'random'") tag is here only to be on the safe side. I expect that not every answer will use randomness. * [Standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/), [I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and [loophole rules](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * If possible, link an online demo of your code. * Please explain your code. [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~116~~ 110 bytes ``` lambda p:[x:=min(p)[0]+.1,sum(sorted(b+(d-b)*(x-a)/(c-a)for(a,b),(c,d)in zip(p,p[-1:]+p)if(a<x)^(c<x))[:2])/2] ``` [Try it online!](https://tio.run/##JY/bboMwDIbveQqrvbHbQDnsYkLrXgSYFE5aJEitJNXoqj47M0xy7Pj//VkJP8L3zRbv7NbxWq@TntteA5fVUl5nY5GpSptzkil/n9HfXBh6bM/Yxy2dcIk1XbCTPN4catWSwk71ZCz8GkZWXMVZ2ZyZzIj6Y6Ev7CRTVeYNXfJmNTPLSvAPH0WyAiZjBxBahMSH3tgyAjiCG3QvMt@DtPY@e7jCrBmNDWpnEs@TCUgkPos5GR9we8KpMmFwuDHUnPJ94AjshARt/c/gRHBCjPLTDd4cHA9PfkH8Wdune9X2QGsKKRT7eYviAuJM7tlW/iP9Aw "Python 3.8 – Try It Online") **Input**: A list of points, each is a tuple of 2 integers. **Output**: A point as a list of 2 numbers. ### Approach Draw a vertical line through the polygon. Select the first 2 points where the line intersects with the polygon edges. Any point between those 2 points must be inside the polygon. [![How to pick an inside point](https://i.stack.imgur.com/nTYsgm.png)](https://i.stack.imgur.com/nTYsgm.png) Note that the line should be chosen such that it doesn't intersect any polygon vertex. ### Code explanation The x-coordinate of the line is selected as the minimum `x` of all vertices, plus a small amount (`0.1` is used in this case): ``` x:=min(p)[0]+.1 ``` This ensures that the line intersects the polygon, and that it doesn't pass through any vertex (since vertices all have integer coordinates). For each edge through vertices \$(a,b)\$ and \$(c,d)\$, the line intersects the edge if \$a<x<c\$ or \$a>x>c\$. Golfed using xor trick: ``` if (a<x)^(b<x) ``` The y-coordinate of each intersection is calculated using the following formula: $$\frac{y-b}{x-a}=\frac{d-b}{c-a}$$ or `b+(d-b)*(x-a)/(c-a)` The y-coordinate of the final point is calculated as the average of the smallest 2 y-coordinates. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 11 bytes Mathematica has a built-in for pointing ion cannons. In fact, as far as I know, it should support self-intersecting roofs. Takes input as a polygon. ``` RandomPoint ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE7872Yb8z8oMS8lPzcgPzOv5H9AEZB0cIsOyM@pTM/Pi66uNtRRMKzVUag20VEwgdJgvrGOglFtbWzsfwA "Wolfram Language (Mathematica) – Try It Online") By the way, `RandomPoint@Polygon@#&` is 5 bytes of Sledgehammer: `⡘⠼⡃⡖⣳`. [Answer] # [Perl 5](https://www.perl.org/), 191 bytes ``` sub{sub c{($_[0]+$_[1])/2}map{$x{$_->[0]}=0}@_;$x=c sort keys%x;for(0..$#_){($t,$y)=@{$_[$_]};($d=$_[$_-1][0]-$t)&&($t=($x-$t)/$d,$t*(1-$t)>0&&push@y,$y+$t*($_[$_-1][1]-$y))}@{[$x,c sort@y]}} ``` It's deterministic and O(n). Choose an \$x\$-coordinate \$P\_x\$ (`$x`) halfway between the smallest two unique input \$x\$ coordinates. Test each polygon side to see if that line segment intersects the \$x=P\_x\$ vertical line. If it does, add the \$y\$-coordinate of that intersection point to `@y`. Finally, let \$P\_y\$ be halfway between the two smallest values in `@y`, and the output is \$(P\_x,P\_y)\$: since you cross exactly one edge to get here from the \$y=-\infty\$ end of the \$x=P\_x\$ line, the point must be inside the polygon. [Try it online!](https://tio.run/##PVDLbsMgELzzFSt3a0GDE9y0J4uI/3ARSh23TVs/ZIhky@Lb3XVS5cDAzO6M2O3r4fd1aSbAfug@h2OjF395n@lANXN0pbIbwtyK3XNsjv2M44wuO5AetYrGFTjqCnw3BPZTT/5xLD66gavtFh@coIQgcRLakKlEZ2PB8aSv7yy3FJJhEGlKbZrjuJIdniSGJ56v5KDStL/4LzNRymaV79acrJMQ0cwljrJi6w/MZGNcCkbjmFD74EEDZwBlqaSystz/44u18ipne0lZksorZvmN0a2sZaJgNArwW5SAGfrh3Ab47s4tT2Qi7zvLDtygE0JC8tYmENnyBw "Perl 5 – Try It Online") [Answer] # Java 10, 378 bytes ``` import java.awt.geom.*;X->Y->{var p=new Path2D.Double();p.moveTo(X[0],Y[0]);int l=X.length,f=1,i=1;for(;i<l;)p.lineTo(X[i],Y[i++]);p.closePath();var r=p.getBounds();double x=0,y=0;for(;f>0;)for(x=r.getX()+Math.random()*r.getWidth(),y=r.getY()+Math.random()*r.getHeight(),i=f=0;i<l-1;)f=!p.contains(x,y)|new Line2D.Double(X[i],Y[i++],X[i],Y[i]).contains(x,y)?1:f;return x+","+y;} ``` Having builtins is usually an advantage, right?.. :/ I'll see if a manual approach is shorter later on. Input-coordinates as two loose arrays for `x` and `y` respectively, output as a comma-delimited String of the random `x,y`-coordinate. [Try it online.](https://tio.run/##jZFNi9swEIbv@RXTPVlrWWtveqpWKZSl9NCFwhaaEHzQxnKi1JaMPc7GpP7t6ShJaQs5LBgjjeZ95uPd6p1OtsXPo60b3yJs6S70K4q18bW4lXB3B/H9FNADbgy8DGiSle8dTlaV7jp40tYdJgAdarSrs7xHW4mydyu03onPl8ODdbjM@VtSnrG1bj2bQQkKjvNktkhmh51uoVHOvMI3jZv7R/Ho@5fKREw2ovY7891H82Wa8wX9mCQSVGouKuPWuOFWZbxUmSx9G0n7UEnWiMq6s8gGkY3jPKBWle9MqEDgULJVDe0CP9HMRUex4lQV9irlg0rPwHKWShZOe9WG5HnE4idCiFa7wtcRuz2Ff9giYEl3ui6uZ30xdr1BSrOqpALUbJIRXb2j3rxD2ncX7fnAfoVVfKUZ/q7in1H4n3PO/pd9zD6UsjXYtw728Q2/iQc5HuWEPGwIQh5erNx5W0BNuuhsxzIHzYLVAM9Dh6YWvkfR0BNWLiqFbppqiEJTJxcPKZ/y6ciuxFP@fmRMvh2VTEmTZPRd4VE8vPD0whwn4/E3) **Explanation:** ``` import java.awt.geom.*; // Required import for Path2D and Line2D X->Y->{ // Method with two int-arrays as parameters and String return-type var p=new Path2D.Double(); // Create a Path2D p.moveTo(X[0],Y[0]); // Start at the first input-coordinate int l=X.length, // Store the amount of points in `l` f=1, // Flag integer, starting at 1 i=1;for(;i<l;) // Loop `i` in the range [1, l): p.lineTo(X[i],Y[i++]); // And draw a line to the `i`'th x,y-coordinate of the input p.closePath(); // Close the path, so we now have our polygon var r=s.getBounds(); // Create a Rectangle that encapsulates this polygon double x=0,y=0; // Create the random x,y-coordinate for(;f>0;) // Loop as long as the flag is still 1: for(x=r.getX()+Math.random()*r.getWidth(),y=r.getY()+Math.random()*r.getHeight(), // Get a random x,y-coordinate within the Rectangle i=f=0; // (Re)set both the flag and `i` to 0 i<l-1;) // Inner loop `i` in the range [0, l-1): f=!p.contains(x,y) // If the Path2D-polygon does NOT contain this random x,y-coordinate | // Or: new Line2D.Double( // Create a Line2D X[i],Y[i++], // from the `i`'th x,y-coordinate of the input X[i],Y[i]) // to the `i+1`'th x,y-coordinate of the input .contains(x,y)? // And if this line does contain the random x,y-coordinate: 1 // Change the flag to 1 : // Else: f; // Keep the flag the same return x+","+y;} // And finally return our random x,y-coordinate as String ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 19 bytes ``` `xx,Xr]yy&G4$TF#ZQ~ ``` The input is a vector with *x* coordinates, then a vector with *y* coordinates. The ouput is *x*, then *y*. Running time is random, but finite with probability 1. [Try it online!](https://tio.run/##y00syfn/P6GiQieiKLayUs3dRCXETTkqsO7//2hdYwUDBV1DIIrligbSIJaCQSwA "MATL – Try It Online") ### How it works The program randomly generates points with a bidimensional Gaussian distribution until one of them happens to be inside the polygon. This distribution spans the full plane, so the code eventually finds a solution. ``` ` % Do...while xx % Delete twice. In the first iterarion this takes the two inputs % (implicitly) and deletes them. In subsequent iterations this % deletes the previous x, y candidate coordinates, which turned out % not to be a solution , % Do twice Xr % Generate a random number with a standard Gaussian distribution. % Note that his covers the whole plane, although points close to % the origin have greater a probability density ] % End. The stack contains two numbers representing x, y coordinates % of a potential solution yy % Duplicate top two elements in the stack &G % Push the two inputs 4$ % Specify four inputs for the next function TF# % Specify the first of two possible outputs for the next function ZQ % Inpolygon function: takes four inputs, where the first and second % define x, y coordinates of a point, and the third and fourth define % the x, y coordinates of the polygon vertices. The (first) output is % true if the point is strictly in the polygon, and false if not ~ % Negate % End (implicit). A new iteration starts if the top of the stack is % true, meaning that the tested x, y values were not a solution % Display (implicit) ``` [Answer] # [Erlang (escript)](http://erlang.org/doc/man/escript.html), 174 bytes ``` f(P)->X=hd(lists:min(P))+0.1,[X,lists:sum(lists:sublist(lists:sort([B+(D-B)*(X-A)/(C-A)||{[A,B],[C,D]}<-lists:zip(P,[lists:last(P)|lists:droplast(P)]),(A<X)xor(C<X)]),2))/2]. ``` [Try it online!](https://tio.run/##ZU7LboNADLznKzjaiU0g7SlKIwH5AI5I1h5IQ9qVeGmhapXSb6emBLVSffA8NGO5cGVev3DRPTvb9uNqvEKKfMyeXi9Q2q7v9pWt1cJN4IckGc1m91bBws4TWVTjepB4AyeOcQ0ZR7iFRPcwfEpEsSFJ6GS@Djznb7aFlGQWZa53UhxmdXFNe3cMEkSHDD8aB4mi6h3idmf8scr1PTHo8XHl6dhm/@5sX8AVRALyAkOePPziozGIpKm6BKT/FdYMh1NYyz/I4eJMLPjb98dv "Erlang (escript) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 89 bytes ``` l=input() (B,b),(A,a),(C,c)=min(zip(l[1:]+l,l,l[2:]+l)) print.2+B,b+(a+c-b*2)/(A+C-B*2)/5 ``` [Try it online!](https://tio.run/##VYzNCoMwEITvPkXxtGk2VtP2InhQHyPkoEEwkKahpPTn5dOspYey7PLNsDPhFderl@mxWrfsmnZ5LqYsy@Q668M9AitgwJkh9DjlO6Jh3cV6eNsATjWt5g7zKEnEWBFu1sdK8hziMHEj5r1kB@j5KAaic6J2BXVVY95cefyjUyZdKBAkRLP59PslMn7uxhTUHw "Python 2 – Try It Online") Here's the strategy for picking the point: * Take the vertex \$p\$ with the smallest \$x\$-coordinate. If there's a tie, any is fine. * Consider the two edges leading from \$p\$. To obtain a direction that's in between them, add them as vectors. * Travel from \$p\$ in this direction far enough to go +0.2 units in the \$x\$ direction, and pick the point you arrive at. Because \$p\$ is among the leftmost points of the polygon, any direction that's in between the two edges leading from it points inside the polygon. Because we only travel 0.2 units in the \$x\$ direction and all vertices lie on integer points, we can't have exited the polygon after going less than 0.5. ]
[Question] [ # Overview Given an image in plain PPM (P3) format as input, for each pixel `p` in the image, replace each of the following 4 pixels' red, green, and blue with the floored average value of the respective channels of all 4 pixels: 1. `p` itself 2. The pixel located at `p`'s location when the image is flipped vertically 3. The pixel located at `p`'s location when the image is flipped horizontally 4. The pixel located at `p`'s location when the image is flipped both vertically and horizontally Output the resulting image in plain PPM (P3) format. For further explanation, consider this 8x8 image, magnified to 128x128: ![step 2 example](https://i.stack.imgur.com/gwz9K.png) Let `p` be the red pixel. To calculate the new value for `p` (and the 3 blue pixels), the values of `p` and the 3 blue pixels will be averaged together: ``` p1 = (255, 0, 0) p2 = (0, 0, 255) p3 = (0, 0, 255) p4 = (0, 0, 255) p_result = (63, 0, 191) ``` --- # Examples ![](https://i.stack.imgur.com/0qYRK.png) ![](https://i.stack.imgur.com/LgDsl.png) PPM: [input](https://gist.github.com/Mego/21fa133078bbb7191ed1), [output](https://gist.github.com/Mego/45d5800466ef440a0eb9) --- ![](https://i.stack.imgur.com/ozCKC.png) ![](https://i.stack.imgur.com/ih87X.png) PPM: [input](https://gist.github.com/Mego/3baea41a427fbe45a7bf), [output](https://gist.github.com/Mego/25fde6a769ec161fdfb2) --- ![](https://i.stack.imgur.com/4wRWZ.png) ![](https://i.stack.imgur.com/koOTW.png) PPM: [input](https://gist.github.com/Mego/a7f543645eeb602680ed), [output](https://gist.github.com/Mego/10c59b23887c4093d9ee) --- ![](https://i.stack.imgur.com/1fqIS.png) ![](https://i.stack.imgur.com/7p3Zy.jpg) PPM: [input](https://gist.github.com/Mego/d46010e0b5298d33c249), [output](https://gist.github.com/Mego/56430fdcd62123a22781) --- # Reference Implementation ``` #!/usr/bin/python import sys from itertools import * def grouper(iterable, n, fillvalue=None): args = [iter(iterable)] * n return list(izip_longest(*args, fillvalue=fillvalue)) def flatten(lst): return sum(([x] if not isinstance(x, list) else flatten(x) for x in lst), []) def pnm_to_bin(p): w,h = map(int,p[1].split(' ')) data = map(int, ' '.join(p[3:]).replace('\n', ' ').split()) bin = [] lines = grouper(data, w*3) for line in lines: data = [] for rgb in grouper(line, 3): data.append(list(rgb)) bin.append(data) return bin def bin_to_pnm(b): pnm = 'P3 {} {} 255 '.format(len(b[0]), len(b)) b = flatten(b) pnm += ' '.join(map(str, b)) return pnm def imageblender(img): h = len(img) w = len(img[0]) for y in range(w): for x in range(h): for i in range(3): val = (img[x][y][i] + img[x][~y][i] + img[~x][y][i] + img[~x][~y][i])//4 img[x][y][i],img[x][~y][i],img[~x][y][i],img[~x][~y][i] = (val,)*4 return img def main(fname): bin = pnm_to_bin(open(fname).read().split('\n')) bin = imageblender(bin) return bin_to_pnm(bin) if __name__ == '__main__': print main(sys.argv[1]) ``` This program takes a single filename as input, formatted like the output of `pngtopnm <pngfile> -plain`, and outputs a single line of PPM data separated by spaces. --- # A Brief Description of the P3 Format A PPM plaintext file generated from `pngtopnm <pngfile> -plain` will look like this: ``` P3 <width in pixels> <height in pixels> <maximum value as defined by the bit depth, always 255 for our purposes> <leftmost 24 pixels of row 1, in RGB triples, space-separated; like (0 0 0 1 1 1 ...)> <next 24 pixels of row 1> <...> <rightmost (up to) 24 pixels of row 1> <leftmost 24 pixels of row 2> <next 24 pixels of row 2> <...> <rightmost (up to) 24 pixels of row 2> <...> ``` This is the format that the example input and output files use. However, PNM is very loose about its formatting - *any* whitespace may separate values. You could replace all newlines in the above file with a single space each, and still have a valid file. For example, [this file](https://gist.github.com/Mego/3baea41a427fbe45a7bf) and [this file](https://gist.github.com/Mego/ca6bb2ee6c9bb90568cc) are both valid, and represent the same image. The only other requirements are that the file must end with a trailing newline, and there must be `width*height` RGB triplets following the `255`. --- # Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid solution wins. * You may input and output PPM data formatted in any convenient and consistent manner, so long as it is valid according to the PPM format described above. The only exception is that you must use the plain (P3) format, and not the binary (P6) format. * You must provide verification that your solution outputs the correct images for the above test images. * All images will have a bit-depth of 8 bits. Extra reading: [Netpbm format wikipedia page](https://en.wikipedia.org/wiki/Netpbm_format) --- # Testing Snippet (thanks to Calvin's Hobbies for this) ``` function loadImage(t){if(t.files&&t.files[0]){var i=new FileReader;i.onload=function(t){function i(t){t.attr("width",img.width),t.width=img.width,t.attr("height",img.height),t.height=img.height;var i=t[0].getContext("2d");return i}img=$("<img>").attr("src",t.target.result)[0],ctxIn=i($("#input")),ctxIn.drawImage(img,0,0),ctxOut=i($("#output")),go()},i.readAsDataURL(t.files[0])}}function getPixel(t,i){return ctxIn.getImageData(t,i,1,1).data}function setPixel(t,i,e){ctxOut.fillStyle="rgb("+e[0]+","+e[1]+","+e[2]+")",ctxOut.fillRect(t,i,1,1)}function go(){if(void 0!==ctxOut)for(var t=0;t<img.width;t++)for(var i=0;i<img.height;i++){for(var e=new Array(3),g=getPixel(t,i),a=getPixel(img.width-t-1,i),r=getPixel(t,img.height-i-1),n=getPixel(img.width-t-1,img.height-i-1),h=0;h<e.length;h++)e[h]=Math.floor((g[h]+a[h]+r[h]+n[h])/4);setPixel(t,i,e)}}var img,ctxIn,ctxOut; ``` ``` * { font-size: 100%; font-family: Arial, sans-serif; } ``` ``` <script src="http://code.jquery.com/jquery-2.2.0.min.js"></script> Warning - runs very slowly on large images! 300x300 pixel maximum advised.<br><br> <canvas id='input'>Your browser doesn't support the HTML5 canvas tag.</canvas><br><br> Load an image: <input type='file' onchange='loadImage(this)'><br><br> <canvas id='output'>Your browser doesn't support the HTML5 canvas tag.</canvas> ``` [Answer] ## Bash (+ImageMagick), 64+1 = 65 bytes ``` C=convert;$C a -flip b;$C a -flop c;$C c -flip d;$C * -average e ``` Right tool for the job. Must be run in a directory containing a single file `a` that contains the PPM data to transform. Since this filename is significant, I've added one byte to the byte count. PNG thumbnail outputs (not sure why this is necessary because they're all the same anyway, but the question says so, so...): [![penguin](https://i.stack.imgur.com/C7KqNt.png)](https://i.stack.imgur.com/C7KqNt.png) [![quintopia](https://i.stack.imgur.com/4Ubvjt.png)](https://i.stack.imgur.com/4Ubvjt.png) [![peter](https://i.stack.imgur.com/kI15Dt.png)](https://i.stack.imgur.com/kI15Dt.png) [![minibits](https://i.stack.imgur.com/gQtKzt.png)](https://i.stack.imgur.com/gQtKzt.png) Thanks to [nneonneo](https://codegolf.stackexchange.com/users/6699/nneonneo) for saving 2 bytes! [Answer] # Matlab, ~~106~~ ~~82~~ 80 bytes ``` i=imread(input(''))/4;for k=1:2;i=i+flipdim(i,k);end;imwrite(i,'p3.pnm','e','A') ``` The image is loaded as `n*m*3` matrix. Then we flip the matrix and added to itself for both axis, and write it again to a file. --- I couldn't find a place to upload text files so big, so here are the PNG versions: ![](https://i.stack.imgur.com/fWik2.png) ![](https://i.stack.imgur.com/UYMHf.png) ![](https://i.stack.imgur.com/eDOof.png) ![](https://i.stack.imgur.com/W2i5b.png) [Answer] # Mathematica, 86 84 bytes Thanks to DavidC for the advice. (saves 2 bytes) ``` Export[#2,⌊Mean@Join[#,(r=Reverse)/@#]&@{#,r/@#}&@Import[#,"Data"]⌋~Image~"Byte"]& ``` The first and second parameters are the paths to the input and output images, respectively. --- ### Test cases ``` f=%; (assign the function to symbol f) f["penguin.pnm","penguin2.pnm"] f["quintopia.pnm","quintopia2.pnm"] f["peter.pnm","peter2.pnm"] ``` --- ### Result (PNG versions of the images are uploaded below) ``` Import["penguin2.pnm"] ``` ![](https://i.stack.imgur.com/TEIvR.png) ``` Import["quintopia2.pnm"] ``` ![](https://i.stack.imgur.com/uoBc2.png) ``` Import["peter2.pnm"] ``` ![](https://i.stack.imgur.com/8Mgld.png) [Answer] # Pyth, 30 29 bytes ``` zjms.OdC.nM[JrR7.zKm_cd3J_J_K ``` My program expects all metadata on the first line, and the image data row by row on the lines after on stdin. To help, this is a small Python program to convert any valid PPM file into a PPM file my program can understand: ``` import sys p3, w, h, d, *data = sys.stdin.read().split() print(p3, w, h, d) for i in range(0, int(w) * int(h), int(w)): print(" ".join(data[i:i+int(w)])) ``` Once you have the image data row by row the operations are really simple. First I read the image data into a list of lists of integers (`JrR7.z`), then I create the horizontally mirrored version by grouping every 3 integers and reversing them for every row (`Km_cd3J`). Then the vertically mirrored versions are simply `_J_K`, since we can just reverse rows. I take all those matrices, flatten each of them into an 1d array with `.nM`, transpose with `C` to get a list of lists of each of the pixel components, average and truncate to int each of those lists (`ms.Od`), and finally print joined by newlines `j`. Note that my program generates output in a different format (but still valid PPM). The demo images can be viewed [in this imgur album](https://i.stack.imgur.com/O27xq.jpg). [Answer] # Julia, 157 bytes ``` using FileIO s->(a=load(s);b=deepcopy(a);d=a.data;(n,m)=size(d);for i=1:n,j=1:m b.data[i,j]=mean([d[i,j];d[n-i+1,j];d[i,m-j+1];d[n-i+1,m-j+1]])end;save(s,b)) ``` This is a lambda function that accepts a string containing the full path to a PPM file and overwrites it with the transformed image. To call it, assign it to a variable. Ungolfed: ``` using FileIO function f(s::AbstractString) # Load the input image a = load(s) # Create a copy (overwriting does bad things) b = deepcopy(a) # Extract the matrix of RGB triples from the input d = a.data # Store the size of the matrix n, m = size(d) # Apply the transformation # Note that we don't floor the mean; this is because the RGB values # aren't stored as integers, they're fixed point values in [0,1]. # Simply taking the mean produces the desired output. for i = 1:n, j = 1:m b.data[i,j] = mean([d[i,j]; d[n-i+1,j]; d[i,m-j+1]; d[n-i+1,m-j+1]]) end # Overwrite the input save(s, b) end ``` Example outputs: [![penguin](https://i.stack.imgur.com/97xQM.png)](https://i.stack.imgur.com/97xQM.png) [![quintopia](https://i.stack.imgur.com/5bRYl.png)](https://i.stack.imgur.com/5bRYl.png) [![peter](https://i.stack.imgur.com/IySq2.png)](https://i.stack.imgur.com/IySq2.png) [![minibits](https://i.stack.imgur.com/9hKQd.png)](https://i.stack.imgur.com/9hKQd.png) [Answer] # python 2+PIL, 268 Now I massively use PIL, using image flipping and alpha blending ``` from PIL import Image I=Image B,T=I.blend,I.FLIP_TOP_BOTTOM a=I.open(raw_input()).convert('RGB') exec'[[email protected]](/cdn-cgi/l/email-protection)_LEFT_RIGHT);c=a@T);d=b@T)'.replace('@','.transpose(') x,y=a.size print'P3',x,y,255 for r,g,b in list(B(B(B(a,b,0.5),c,0.25),d,0.25).getdata()):print r,g,b ``` Resulting images are available [here](https://i.stack.imgur.com/uaLBA.jpg) ]
[Question] [ # Task Given input N, generate and output an NxN grid where each row, column and the two diagonals contain the numbers 1 to `N` (or 0 to `N`−1 if that's easier). ## Input The input is a positive integer `N`. It represents the number of columns and rows in the grid. For this problem, you can assume `N` will be a reasonable size, `4 ≤ N ≤ 8` or (`1 ≤ N ≤ 8` if you go for the bonus below). ## Output The output will be the `N`×`N` grid. In the grid, each row only contains the numbers 1 to `N`, each column only contains the numbers 1 to `N`, and the two diagonals of length `N` (the one from `(0,0)` to `(N-1,N-1)` and the one from `(0,N-1)` to `(N-1, 0)`) only contain the numbers 1 to `N`. You can use the numbers 0 to `N−1`. For each `N`, there are many possible solutions, you only need to print the first one you find. You don't need to print spaces between the numbers. ## Constraints Your code should be able to repeatably produce results for `N >= 7`. That is, if you're able to actually run and get a solution for `N = 7` from your code each time, you're good. In terms of an absolute limit, your code should be able to solve for `N = 7` in under 10 minutes each time you run it (i.e., if you depend on random numbers, for the worst case, your code should still finish in under 10 minutes for `N = 7`). ## Examples * **Input:** `4` **One possible output:** ``` 1 2 3 4 3 4 1 2 4 3 2 1 2 1 4 3 ``` * **Input:** `5` **One possible output:** ``` 1 2 3 4 5 5 3 1 2 4 2 5 4 3 1 4 1 2 5 3 3 4 5 1 2 ``` * **Input:** `8` **One possible output:** ``` 1 2 3 4 5 6 7 8 2 3 1 5 4 8 6 7 4 1 2 3 7 5 8 6 6 4 7 8 1 2 3 5 7 5 8 2 6 3 4 1 5 8 4 6 2 7 1 3 8 7 6 1 3 4 5 2 3 6 5 7 8 1 2 4 ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins, with one exception. For inputs `N = 2, 3` there are no valid solutions. If your code can handles this (run to completion without outputting anything for these cases, or outputting an empty string), and still handles `N = 1` (outputs `1` for it), take 20% off your byte count. [Answer] # [Funciton](http://esolangs.org/wiki/Funciton), non-competitive # UPDATE! Massive performance improvement! *n* = 7 now completes in under 10 minutes! See explanation at bottom! This was good fun to write. This is a brute-force solver for this problem written in Funciton. Some factoids: * It accepts an integer on STDIN. Any extraneous whitespace breaks it, including a newline after the integer. * It uses the numbers 0 to *n* − 1 (not 1 to *n*). * It fills the grid “backwards”, so you get a solution where the bottom row reads `3 2 1 0` rather than where the top row reads `0 1 2 3`. * It correctly outputs `0` (the only solution) for *n* = 1. * Empty output for *n* = 2 and *n* = 3. * When compiled to an exe, takes about 8¼ minutes for *n* = 7 (was about one hour before the performance improvement). Without compiling (using the interpreter) it takes about 1.5 times as long, so using the compiler is worth it. * As a personal milestone, this is the first time I wrote a whole Funciton program without first writing the program in a pseudocode language. I did write it in actual C# first though. * (However, this is not the first time I made a change to massively improve the performance of something in Funciton. The first time I did that was in the factorial function. Swapping the order of the operands of the multiplication made a huge difference because of [how the multiplication algorithm works](https://github.com/Timwi/Funciton/blob/master/FncLib/multiply.fnc). Just in case you were curious.) Without further ado: ``` ┌────────────────────────────────────┐ ┌─────────────────┐ │ ┌─┴─╖ ╓───╖ ┌─┴─╖ ┌──────┐ │ │ ┌─────────────┤ · ╟─╢ Ӂ ╟─┤ · ╟───┤ │ │ │ │ ╘═╤═╝ ╙─┬─╜ ╘═╤═╝ ┌─┴─╖ │ │ │ │ └─────┴─────┘ │ ♯ ║ │ │ │ ┌─┴─╖ ╘═╤═╝ │ │ │ ┌────────────┤ · ╟───────────────────────────────┴───┐ │ │ ┌─┴─╖ ┌─┴─╖ ┌────╖ ╘═╤═╝ ┌──────────┐ ┌────────┐ ┌─┴─╖│ │ │ ♭ ║ │ × ╟───┤ >> ╟───┴───┘ ┌─┴─╖ │ ┌────╖ └─┤ · ╟┴┐ │ ╘═╤═╝ ╘═╤═╝ ╘══╤═╝ ┌─────┤ · ╟───────┴─┤ << ╟─┐ ╘═╤═╝ │ │ ┌───────┴─────┘ ┌────╖ │ │ ╘═╤═╝ ╘══╤═╝ │ │ │ │ │ ┌─────────┤ >> ╟─┘ │ └───────┐ │ │ │ │ │ │ │ ╘══╤═╝ ┌─┴─╖ ╔═══╗ ┌─┴─╖ ┌┐ │ │ ┌─┴─╖ │ │ │ │ ┌┴┐ ┌───────┤ ♫ ║ ┌─╢ 0 ║ ┌─┤ · ╟─┤├─┤ ├─┤ Ӝ ║ │ │ │ │ ╔═══╗ └┬┘ │ ╘═╤═╝ │ ╚═╤═╝ │ ╘═╤═╝ └┘ │ │ ╘═╤═╝ │ │ │ │ ║ 1 ╟───┬┘ ┌─┴─╖ └───┘ ┌─┴─╖ │ │ │ │ │ ┌─┴─╖ │ │ │ ╚═══╝ ┌─┴─╖ │ ɓ ╟─────────────┤ ? ╟─┘ │ ┌─┴─╖ │ ├─┤ · ╟─┴─┐ │ ├─────────┤ · ╟─┐ ╘═╤═╝ ╘═╤═╝ ┌─┴────┤ + ╟─┘ │ ╘═╤═╝ │ ┌─┴─╖ ┌─┴─╖ ╘═╤═╝ │ ╔═╧═╕ ╔═══╗ ┌───╖ ┌─┴─╖ ┌─┴─╖ ╘═══╝ │ │ │ ┌─┤ · ╟─┤ · ╟───┐ └┐ └─╢ ├─╢ 0 ╟─┤ ⌑ ╟─┤ ? ╟─┤ · ╟──────────────┘ │ │ │ ╘═╤═╝ ╘═╤═╝ └───┐ ┌┴┐ ╚═╤═╛ ╚═╤═╝ ╘═══╝ ╘═╤═╝ ╘═╤═╝ │ │ │ │ ┌─┴─╖ ┌───╖ │ └┬┘ ┌─┴─╖ ┌─┘ │ │ │ │ │ ┌─┴───┤ · ╟─┤ Җ ╟─┘ └────┤ ? ╟─┴─┐ ┌─────────────┘ │ │ │ │ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ │ │╔════╗╔════╗ │ │ │ │ │ ┌──┴─╖ ┌┐ ┌┐ ┌─┴─╖ ┌─┴─╖ │║ 10 ║║ 32 ║ ┌─────────────────┘ │ │ │ │ │ << ╟─┤├─┬─┤├─┤ · ╟─┤ · ╟─┘╚══╤═╝╚╤═══╝ ┌──┴──┐ │ │ │ │ ╘══╤═╝ └┘ │ └┘ ╘═╤═╝ ╘═╤═╝ │ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ │ │ │ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ╔═╧═╕ └─┤ ? ╟─┤ · ╟─┤ % ║ │ │ └─────┤ · ╟─┤ · ╟──┤ Ӂ ╟──┤ ɱ ╟─╢ ├───┐ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ │ │ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╘═══╝ ╚═╤═╛ ┌─┴─╖ ┌─┴─╖ │ └────────────────────┘ │ └─────┤ │ └───┤ ‼ ╟─┤ ‼ ║ │ ┌──────┐ │ │ │ ╘═══╝ ╘═╤═╝ │ │ ┌────┴────╖ │ │ │ ┌─┴─╖ │ │ │ str→int ║ │ │ └──────────────────────┤ · ╟───┴─┐ │ ╘════╤════╝ │ │ ┌─────────╖ ╘═╤═╝ │ ╔═╧═╗ ┌──┴──┐ │ └──────────┤ int→str ╟──────────┘ │ ║ ║ │ ┌───┴───┐ │ ╘═════════╝ │ ╚═══╝ │ │ ┌───╖ │ └───────────────────────────────────────────────────────┘ │ └─┤ × ╟─┘ ┌──────────────┐ ╔═══╗ │ ╘═╤═╝ ╔════╗ │ ╓───╖ ┌───╖ │ ┌───╢ 0 ║ │ ┌─┴─╖ ╔═══╗ ║ −1 ║ └─╢ Ӝ ╟─┤ × ╟──┴──────┐ │ ╚═╤═╝ └───┤ Ӂ ╟─╢ 0 ║ ╚═╤══╝ ╙───╜ ╘═╤═╝ │ │ ┌─┴─╖ ╘═╤═╝ ╚═══╝ ┌─┴──╖ ┌┐ ┌───╖ ┌┐ ┌─┴──╖ ╔════╗ │ │ ┌─┤ ╟───────┴───────┐ │ << ╟─┤├─┤ ÷ ╟─┤├─┤ << ║ ║ −1 ║ │ │ │ └─┬─╜ ┌─┐ ┌─────┐ │ ╘═╤══╝ └┘ ╘═╤═╝ └┘ ╘═╤══╝ ╚═╤══╝ │ │ │ └───┴─┘ │ ┌─┴─╖ │ │ └─┘ └──────┘ │ │ └───────────┘ ┌─┤ ? ╟─┘ └──────────────────────────────┘ ╓───╖ └───────────────┘ ╘═╤═╝ ┌───────────╢ Җ ╟────────────┐ │ ┌────────────────────────┴───┐ ╙───╜ │ │ ┌─┴────────────────────┐ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ┌─┴─┤ · ╟──────────────────┐ │ ♯ ║ ┌────────────────────┤ · ╟───────┐ │ ╘═╤═╝ │ ╘═╤═╝ │ ╘═╤═╝ │ │ │ ┌───╖ │ ┌─────┴───┘ ┌─────────────────┴─┐ ┌───┴───┐ ┌─┴─╖ ┌─┴─╖ ┌─┤ × ╟─┴─┐ │ │ ┌─┴─╖ │ ┌───┴────┤ · ╟─┤ · ╟──────────┤ ╘═╤═╝ │ │ │ ┌───╖ ┌───╖ ┌──┤ · ╟─┘ ┌─┴─┐ ╘═╤═╝ ╘═╤═╝ ┌─┴─╖ │ │ │ ┌────┴─┤ ♭ ╟─┤ × ╟──┘ ╘═╤═╝ │ ┌─┴─╖ ┌───╖└┐ ┌──┴─╖ ┌─┤ · ╟─┘ │ │ │ ╘═══╝ ╘═╤═╝ ┌───╖ │ │ │ × ╟─┤ Ӝ ╟─┴─┤ ÷% ╟─┐ │ ╘═╤═╝ ┌───╖ │ │ ┌─────┴───┐ ┌────┴───┤ Ӝ ╟─┴─┐ │ ╘═╤═╝ ╘═╤═╝ ╘══╤═╝ │ │ └───┤ Ӝ ╟─┘ │ ┌─┴─╖ ┌───╖ │ │ ┌────╖ ╘═╤═╝ │ └───┘ ┌─┴─╖ │ │ └────┐ ╘═╤═╝ │ │ × ╟─┤ Ӝ ╟─┘ └─┤ << ╟───┘ ┌─┴─╖ ┌───────┤ · ╟───┐ │ ┌─┴─╖ ┌───╖ │ │ │ ╘═╤═╝ ╘═╤═╝ ╘══╤═╝ ┌───┤ + ║ │ ╘═╤═╝ ├──┴─┤ · ╟─┤ × ╟─┘ │ └───┤ └────┐ ╔═══╗ ┌─┴─╖ ┌─┴─╖ ╘═╤═╝ │ ╔═══╗ ┌─┴─╖ ┌─┴─╖ ╘═╤═╝ ╘═╤═╝ │ ┌─┴─╖ ┌────╖ │ ║ 0 ╟─┤ ? ╟─┤ = ║ ┌┴┐ │ ║ 0 ╟─┤ ? ╟─┤ = ║ │ │ ┌────╖ │ │ × ╟─┤ << ╟─┘ ╚═══╝ ╘═╤═╝ ╘═╤═╝ └┬┘ │ ╚═══╝ ╘═╤═╝ ╘═╤═╝ │ └─┤ << ╟─┘ ╘═╤═╝ ╘═╤══╝ ┌┐ ┌┐ │ │ └───┘ ┌─┴─╖ ├──────┘ ╘═╤══╝ │ └────┤├──┬──┤├─┘ ├─────────────────┤ · ╟───┘ │ │ └┘┌─┴─╖└┘ │ ┌┐ ┌┐ ╘═╤═╝ ┌┐ ┌┐ │ └────────────┤ · ╟─────────┘ ┌─┤├─┬─┤├─┐ └───┤├─┬─┤├────────────┘ ╘═╤═╝ │ └┘ │ └┘ │ └┘ │ └┘ └───────────────┘ │ └────────────┘ ``` # Explanation of the first version The first version took about an hour to solve *n* = 7. The following explains mostly how this slow version worked. At the bottom I will explain what change I made to get it to under 10 minutes. ## An excursion into bits This program needs bits. It needs lots of bits, and it needs them in all the right places. Experienced Funciton programmers already know that if you need *n* bits, you can use the formula ![2^n-1](https://i.stack.imgur.com/eVnx5.png) which in Funciton can be expressed as ![(1 << n) - 1](https://i.stack.imgur.com/dZvem.png) When doing my performance optimization, it occurred to me that I can calculate the same value much faster using this formula: ![¬ (−1 << n)](https://i.stack.imgur.com/AKrAJ.png) I hope you’ll forgive me that I didn’t update all the equation graphics in this post accordingly. Now, let’s say you don’t want a contiguous block of bits; in fact, you want *n* bits at regular intervals every *k*-th bit, like so: ``` LSB ↓ 00000010000001000000100000010000001 └──┬──┘ k ``` The formula for this is fairly straight-forward once you know it: ![((1 << nk) - 1) / ((1 << k) - 1)](https://i.stack.imgur.com/uzLFJ.png) In the code, the function `Ӝ` takes values *n* and *k* and calculates this formula. ## Keeping track of used numbers There are *n*² numbers in the final grid, and each number can be any of *n* possible values. In order to keep track of which numbers are permitted in each cell, we maintain a number consisting of *n*³ bits, in which a bit is set to indicate that a particular value is taken. Initially this number is 0, obviously. The algorithm begins in the bottom-right corner. After “guessing” the first number is a 0, we need to keep track of the fact that the 0 is no longer permitted in any cell along the same row, column and diagonal: ``` LSB (example n=5) ↓ 10000 00000 00000 00000 10000 00000 10000 00000 00000 10000 00000 00000 10000 00000 10000 00000 00000 00000 10000 10000 10000 10000 10000 10000 10000 ↑ MSB ``` To this end, we calculate the following four values: * **Current row:** We need *n* bits every *n*-th bit (one per cell), and then shift it to the current row *r*, remembering every row contains *n*² bits: ![((1<<n²)−1)/((1<<n)−1) << n²r](https://i.stack.imgur.com/tVvGz.png) * **Current column:** We need *n* bits every *n*²-th bit (one per row), and then shift it to the current column *c*, remembering every column contains *n* bits: ![((1<<n³)−1)/((1<<n²)−1) << n²r](https://i.stack.imgur.com/1kW4B.png) * **Forward diagonal:** We need *n* bits every... (did you pay attention? Quick, figure it out!)... *n*(*n*+1)-th bit (well done!), but only if we’re actually on the forward diagonal: ![((1 << n²(n+1))−1) / ((1 << n(n+1))−1) if c = r](https://i.stack.imgur.com/LLM3i.png) * **Backward diagonal:** Two things here. First, how do we know if we’re on the backward diagonal? Mathematically, the condition is *c* = (*n* − 1) − *r*, which is the same as *c* = *n* + (−*r* − 1). Hey, does that remind you of something? That’s right, it’s two’s complement, so we can use bitwise negation (very efficient in Funciton) instead of the decrement. Second, the formula above assumes that we want the least significant bit to be set, but in the backward diagonal we don’t, so we have to shift it up by... do you know?... That’s right, *n*(*n* − 1). ![((1 << n²(n-1))−1) / ((1 << n(n-1))−1) << n(n-1) if c = n + ¬r](https://i.stack.imgur.com/ROq1O.png) This is also the only one where we potentially divide by 0 if *n* = 1. However, Funciton doesn’t care. 0 ÷ 0 is just 0, don’t you know? In the code, the function `Җ` (the bottom one) takes *n* and an *index* (from which it calculates *r* and *c* by division and remainder), calculates these four values and `or`s them together. ## The brute-force algorithm The brute-force algorithm is implemented by `Ӂ` (the function at the top). It takes *n* (the grid size), *index* (where in the grid we’re currently placing a number), and *taken* (the number with *n*³ bits telling us which numbers we can still place in each cell). This function returns a sequence of strings. Each string is a full solution to the grid. It’s a complete solver; it would return all solutions if you let it, but it returns them as a lazy-evaluated sequence. * If *index* has reached 0, we’ve successfully filled the whole grid, so we return a sequence containing the empty string (a single solution that covers none of the cells). The empty string is `0`, and we use the library function `⌑` to turn that into a single-element sequence. * The check described under *performance improvement* below happens here. * If *index* has not yet reached 0, we decrement it by 1 to get the index at which we now need to place a number (call that *ix*). We use `♫` to generate a lazy sequence containing the values from 0 to *n* − 1. Then we use `ɓ` (monadic bind) with a lambda that does the following in order: + First look at the relevant bit in *taken* to decide whether the number is valid here or not. We can place a number *i* if and only if *taken* & (1 << (*n* × *ix*) << *i*) isn’t already set. If it is set, return `0` (empty sequence). + Use `Җ` to calculate the bits corresponding to the current row, column and diagonal(s). Shift it by *i* and then `or` it onto *taken*. + Recursively call `Ӂ` to retrieve all solutions for the remaining cells, passing it the new *taken* and the decremented *ix*. This returns a sequence of incomplete strings; each string has *ix* characters (the grid filled in up to index *ix*). + Use `ɱ` (map) to go through the solutions thusly found and use `‼` to concatenate *i* to the end of each. Append a newline if *index* is a multiple of *n*, otherwise a space. ## Generating the result The main program calls `Ӂ` (the brute forcer) with *n*, *index* = *n*² (remember we fill the grid backwards) and *taken* = 0 (initially nothing is taken). If the result of this is an empty sequence (no solution found), output the empty string. Otherwise, output the first string in the sequence. Note that this means it will evaluate only the first element of the sequence, which is why the solver doesn’t continue until it has found all solutions. ## Performance improvement (For those who already read the old version of the explanation: the program no longer generates a sequence of sequences that needs to be separately turned into a string for output; it just generates a sequence of strings directly. I’ve edited the explanation accordingly. But that wasn’t the main improvement. Here it comes.) On my machine, the compiled exe of the first version took pretty much exactly 1 hour to solve *n* = 7. This was not within the given time limit of 10 minutes, so I didn’t rest. (Well, actually, the reason I didn’t rest was because I had this idea on how to massively speed it up.) The algorithm as described above stops its search and backtracks every time that it encounters a cell in which all the bits in the *taken* number are set, indicating that nothing can be put into this cell. However, the algorithm will continue to futilely fill the grid *up to* the cell in which all those bits are set. It would be much faster if it could stop as soon as **any** yet-to-be-filled-in cell already has all the bits set, which already indicates that we can never solve the rest of the grid no matter what numbers we put in it. But how do you efficiently check whether **any** cell has its *n* bits set without going through all of them? The trick starts by adding a single bit per cell to the *taken* number. Instead of what was shown above, it now looks like this: ``` LSB (example n=5) ↓ 10000 0 00000 0 00000 0 00000 0 10000 0 00000 0 10000 0 00000 0 00000 0 10000 0 00000 0 00000 0 10000 0 00000 0 10000 0 00000 0 00000 0 00000 0 10000 0 10000 0 10000 0 10000 0 10000 0 10000 0 10000 0 ↑ MSB ``` Instead of *n*³, there are now *n*²(*n* + 1) bits in this number. The function that populates the current row/column/diagonal has been changed accordingly (actually, completely rewritten to be honest). That function will still populate only *n* bits per cell though, so the extra bit we just added will always be `0`. Now, let’s say we are halfway through the calculation, we just placed a `1` in the middle cell, and the *taken* number looks something like this: ``` current LSB column (example n=5) ↓ ↓ 11111 0 10010 0 01101 0 11100 0 11101 0 00011 0 11110 0 01101 0 11101 0 11100 0 11111 0 11110 0[11101 0]11100 0 11100 0 ← current row 11111 0 11111 0 11111 0 11111 0 11111 0 11111 0 11111 0 11111 0 11111 0 11111 0 ↑ MSB ``` As you can see, the top-left cell (index 0) and the middle-left cell (index 10) are now impossible. How do we most efficiently determine this? Consider a number in which the 0th bit of each cell is set, but only up to the current index. Such a number is easy to calculate using the familiar formula: ![((1 << (n+1)i) - 1) / ((1 << (n+1)) - 1)](https://i.stack.imgur.com/7pNqA.png) What would we get if we added these two numbers together? ``` LSB LSB ↓ ↓ 11111 0 10010 0 01101 0 11100 0 11101 0 10000 0 10000 0 10000 0 10000 0 10000 0 ╓───╖ 00011 0 11110 0 01101 0 11101 0 11100 0 ║ 10000 0 10000 0 10000 0 10000 0 10000 0 ║ 11111 0 11110 0 11101 0 11100 0 11100 0 ═══╬═══ 10000 0 10000 0 00000 0 00000 0 00000 0 ═════ ╓─╜ 11111 0 11111 0 11111 0 11111 0 11111 0 ║ 00000 0 00000 0 00000 0 00000 0 00000 0 ═════ ╨ 11111 0 11111 0 11111 0 11111 0 11111 0 00000 0 00000 0 00000 0 00000 0 00000 0 o ↑ ↑ MSB MSB ``` The result is: ``` OMG ↓ 00000[1]01010 0 11101 0 00010 0 00011 0 10011 0 00001 0 11101 0 00011 0 00010 0 ═════ 00000[1]00001 0 00011 0 11100 0 11100 0 ═════ 11111 0 11111 0 11111 0 11111 0 11111 0 11111 0 11111 0 11111 0 11111 0 11111 0 ``` As you can see, the addition overflows into the extra bit that we added, but only if all the bits for that cell are set! Therefore, all that’s left to do is to mask out those bits (same formula as above, but << *n*) and check if the result is 0: ``` 00000[1]01010 0 11101 0 00010 0 00011 0 ╓╖ 00000 1 00000 1 00000 1 00000 1 00000 1 ╓─╖ ╓───╖ 10011 0 00001 0 11101 0 00011 0 00010 0 ╓╜╙╖ 00000 1 00000 1 00000 1 00000 1 00000 1 ╓╜ ╙╖ ║ 00000[1]00001 0 00011 0 11100 0 11100 0 ╙╥╥╜ 00000 1 00000 1 00000 0 00000 0 00000 0 ═════ ║ ║ ╓─╜ 11111 0 11111 0 11111 0 11111 0 11111 0 ╓╜╙╥╜ 00000 0 00000 0 00000 0 00000 0 00000 0 ═════ ╙╖ ╓╜ ╨ 11111 0 11111 0 11111 0 11111 0 11111 0 ╙──╨─ 00000 0 00000 0 00000 0 00000 0 00000 0 ╙─╜ o ``` If it is not zero, the grid is impossible and we can stop. * **[Screenshot](https://i.stack.imgur.com/iES6l.png)** showing solution and running time for *n* = 4 to 7. [Answer] # Haskell, 790\*0.80=632 bytes ``` import Data.List import Control.Monad import Data.Array s r=let{h as bs=[(a,b)|a<-as,b<-bs];(&)m k=(\(Just x)->x)$lookup k m;j=Just;n=Nothing;c=[1..r];q=delete;u=h[1..r]c;o=[(s,[u |u<-[h[1..r][c]|c<-c]++[h[r]c|r<-[1..r]]++[zip[1..r][1..r],zip[1..r][r,r-1..1]],s`elem`u])|s<-u];k=foldr(>=>)j;a p d g0=k[t p d2|d2<-q d(g0!p)]g0;t p d g0|not(d`elem`(g0!p))=j g0|[]<-v=n|[d2]<-v=k[t s2 d2|s2<-[(s,delete s$nub(concat(o&s)))|s<-u]&p]g1|True=k[l[s|s<-u,not(d`elem`v)]|u<-o&p]g1 where{v=q d(g0!p);g1=g0//[(p,v)];l[]_=n;l[d3]g=a d3 d g;l _ r=j r};w g0|and[case g0!s of{[_]->True;_->False}|s<-u]=j g0|True=msum[a s' d g0>>=w|d<-g0!s']where(_,s')=minimumBy(\(a,_)(b,_)->compare a b)[(l,s)|s<-u,let v=g0!s;l=length v,l>1]}in fmap(fmap(\[x]->x))$w$array((1,1),(r,r))[((i,j),[1..r])|i<-[1..r],j<-[1..r]] ``` I noticed this problem is very similar to sudoku. I remember an old sudoku solver I wrote in Haskell based on [this other one](http://norvig.com/sudoku.html) in Python. This is my first code golf post or attempt. This fulfills the bonus because it returns `Nothing` for `n=2,3` and `Just <result>` for `n>=4`, where `<result>` is a 2D array of integral values. See [here](https://ideone.com/1tCJza) for online interpreter. That code is actually longer than the one in the post because the online interpreter has more strict requirements as to what forms a complete program (rules say a submission can be a function). This submission takes input as a function argument. [Answer] ## Pyth, 41 bytes ``` #Km.SQQI.AmqQl{d+.TK.Tm,@@Kdd@@Kt-QddQB;K ``` ``` # ; # while(True) Km.SQQ # K = random QxQ 2d list I ; # if ... .A # all of... m Q # map(range(Q))... + # concat .TK # transpose K .Tm,@@Kdd@@Kt-Qdd # diagonals of K m d # map(range(d)) , # 2-elem list of... @@Kdd # K[n][n] @@Kt-Qd # and K[len(K)-n-1][n] .T # transpose qQl{d # subarrays have no dups... B; # ... then, break K # output final result ``` Brute force ftw! Since this basically keeps trying random shuffles until it works (well, it keeps trying `n * [shuffle(range(n))]`), it takes a really, really long time. Here are some test runs to give you an idea of how long it takes: ``` llama@llama:~$ time echo 4 | pyth <(echo '#Km.SQQI.AmqQl{d+.TK.Tm,@@Kdd@@Kt-QddQB;K') [[2, 1, 0, 3], [0, 3, 2, 1], [3, 0, 1, 2], [1, 2, 3, 0]] echo 4 0.00s user 0.00s system 0% cpu 0.001 total pyth <(echo '#Km.SQQI.AmqQl{d+.TK.Tm,@@Kdd@@Kt-QddQB;K') 0.38s user 0.00s system 96% cpu 0.397 total ``` That's only 4x4, and it runs in a little under half a second. I'm actually cheating because this is the best out of a few trials—most of them take over a second or two. I've yet to get a timing on 5x5 (it ran to completion once, but that was in a REPL and I wasn't timing it). Note that the rule for the time limit was only edited into the question after this answer was posted. [Answer] # Python 3, ~~275~~ 260 Bytes\*0.8= ~~220~~ 208 Bytes Recursive/backtracking approach. `R` is the recursive function, `l` is the coLumn, `w` is the roW, `K` is the next entry. I chose to put it in a 1d array and pretty-print it at the end to make indices simpler. ``` r=range n=(int)(input()) def R(A,I): l=I%n;w=I//n if I==n*n:[print(A[i*n:i*n+n])for i in r(n)];exit() for K in r(n): if all([all([A[i*n+l]!=K,w!=l or A[i+n*i]!=K,w!=n-1-l or A[n*i+n-i-1]!=K])for i in r(w)]+[A[w*n+i]!=K for i in r(l)]):R(A+[K],I+1) R([],0) ``` Ungolfed version: ``` def Recurse(A,I,n): column=I%n row=I//n if I==n*n: [print(*A[i*n:i*n+n])for i in range(n)] # output exit() #end recursion for K in range(n): # try every possibility. Test if they satisfy the constraints: # if so, move the index on. If none of them do, we'll return None. # if a child returns None, we'll move onto the next potential child: # if all of them fail it will backtrack to the next level. if all([ all([ A[i*n+column]!=K, # column constraint row!=column or A[i+n*i]!=K, # diagonal constraint row!=n-1-column or A[n*i+n-i-1]!=K # antidiagonal constraint ]) for i in range(row) ]+[ A[row*n+i]!=K for i in range(column) # row constraint ]): Recurse(A+[K],I+1,n) Recurse([],0,(int)(input())) ``` [Answer] # SWI-Prolog, 326\*0.80 = 260.8 bytes ``` :-use_module(library(clpfd)). a(N):-l(N,R),m(l(N),R),append(R,V),V ins 1..N,transpose(R,C),d(0,R,D),maplist(reverse,R,S),d(0,S,E),m(m(all_distinct),[R,C,[D,E]]),m(label,R),m(p,R). l(L,M):-length(M,L). d(X,[H|R],[A|Z]):-nth0(X,H,A),Y is X+1,(R=[],Z=R;d(Y,R,Z)). p([H|T]):-write(H),T=[],nl;write(' '),p(T). m(A,B):-maplist(A,B). ``` *Edit: saved 16 bytes thanks to @Mat* ### Usage Call `a(5).` in your interpreter for `N=5`. This returns `false` for `N=2` or `N=3`. Since it uses the CLPFD library this is not pure bruteforce. This program can find a solution for `N=20` in about 15 seconds on my computer. ### Ungolfed + explanations: This basically works like a Sudoku solver, except that the blocks constraints are replaced with the diagonals constraints. ``` :-use_module(library(clpfd)). % Import Constraints library a(N):- l(N,R), % R is a list of length N maplist(l(N),R), % R contains sublists, each of length N append(R,V), V ins 1..N, % Each value in the matrix is between 1 and N maplist(all_distinct,R), % Values must be different on each row transpose(R,C), maplist(all_distinct,C), % Values must be different on each column d(0,R,D), maplist(reverse,R,S), d(0,S,E), all_distinct(D), % Values must be different on the diagonal all_distinct(E), % Values must be different on the "anti"-diagonal maplist(label,R), % Affects actual values to each element maplist(p,R). % Prints each row l(L,M):-length(M,L). % True if L is the length of M d(X,[H|R],[A|Z]):-nth0(X,H,A),Y is X+1,(R=[],Z=R;d(Y,R,Z)). % True if the third argument is the diagonal of the second argument p([H|T]):-write(H),T=[],nl;write(' '),p(T). % Prints a row separated by spaces and followed by a new line ``` [Answer] # CJam, 87 bytes - 20% bonus = 69.6 bytes ``` qi__"@I/l ŤˏūȻ ܀ᅀ൹৽჈͚ 㑢鴑慚菥洠㬝᚜ "N/=:i0+\,m!f=`1LL](4e<= ``` Hardcodes the answers. Contains some unprintables. Works for `N = 1` through `N = 8`. Basically, each line in that mysterious string contains indices into the list of permutations of `range(N)`, encoded as Unicode characters. `=:i0+\,m!f=` indexes into the list of permutations, adding a 0 to the end of the list of indices first, representing the bottom row `0 1 2 ... N-1`. For `N < 4`, the resulting 2D array is nonsense. ``1LL]` creates a list `[N, pretty output, 1, "", ""]`. Then, `(4e<=` pops the first element out of this list, `N`, and retrieves the `min(N, 4) % 4`th element from the rest of it. For `N >= 4`, that's the output, and otherwise it's the special-case outputs for the first three cases. [Try it here](http://cjam.aditsu.net/#code=qi__%22%40I%2Fl%0A%C5%A4%CB%8F%C5%AB%C8%BB%C2%94%0A%DC%80%E1%85%80%E0%B5%B9%E0%A7%BD%E1%83%88%CD%9A%0A%E3%91%A2%E9%B4%91%E6%85%9A%E8%8F%A5%E6%B4%A0%E3%AC%9D%E1%9A%9C%0A%07%17%10%22N%2F%3D%3Ai0%2B%5C%2Cm!f%3D%5B%601LL%5D%5C4e%3C%3D&input=8). [Answer] # C++, 672\*0.80 645\*0.80 = 516 bytes ``` #include <iostream> int **b,**x,**y,*d,*a,n; #define R(i) for(i=0;i<n;i++){ #define E(e) e=new int[n]; int f(int c,int r) {int i=0,p=c-1;if(r>=n)return 1;if(c == n + 1)return f(1,r+1);R(i)int m=r==i,s=r+i==n-1;if(!b[r][i]&&!x[r][p]&&!(m&&d[p])&&!(s&&a[p])&&!y[i][p]){b[r][i]=c;x[r][p]=1;y[i][p]=1;if(m)d[p]=1;if(s)a[p]=1;if(f(c+1,r))return 1;b[r][i]=0;x[r][p]=0;y[i][p]=0;if(m)d[p]=0;if(s)a[p]=0;}}return 0;} int main(){std::cin>>n;int i=0,j=0;b=new int*[n];x=new int*[n];y=new int*[n];E(d);E(a);R(i)E(b[i]);E(x[i]);E(y[i]); d[i]=0;a[i]=0;R(j)b[i][j]=0;x[i][j]=0;y[i][j]=0;}}if(f(1,0)){R(i)R(j)std::cout<<b[i][j];}std::cout<<std::endl;}}} ``` Try it online [here](http://cpp.sh/7dqg) Since a couple answers have already been posted, I thought I would post the golfed version of the code I used to generated the output for the examples. This is my first time answering a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so all feedback is welcomed. :) ## Ungolfed + explanations: Essentially, the code is brute-forcing a solution. It starts in the first row, with 0. It starts in the first spot, if that spots passes all the checks, it moves onto to the next number. If it fills the row, it moves onto the next row. If it's done all of the rows, that means a solution has been found. If the spot doesn't pass all of the checks, it moves onto the next spot. If it's done the row, then it backtracks, as a number in one of the previous rows prevents a solution from being possible. ``` #include <iostream> // global variables to save bytes on passing these are function arguments int **b, // this will store the state of the board **x, // if x[i][j] is true, row i of b contains the number j **y, // if y[i][j] is true, column i of b contains the number j *d, // if d[i] the main diagonal of b contains i *a, // if a[i] the antidiagonal of a contains i n; // preprocessor to save bytes on repeated statements #define R(i) for(i=0;i<n;i++){ #define E(e) e=new int[n]; // Recursively looks for a solution // c - the current number to insert in row r // r - the current row to fill int f (int c, int r) { int i=0,p=c-1; if (r >= n) return 1; // we are done if (c == n + 1) return f(1,r+1); // this row is full, move to the next row R(i) // go through the positions in this row, // trying to fill them with c int m=r==i, s=r+i==n-1; // check if this position (r,i) is on ones // of the diagonals // if this spot isn't filled, and the row (r), column (i) and diagonals // (if it's on the diagonal) doesn't contain the number, fill the spot if (!b[r][i] && !x[r][p] && !(m&&d[p]) && !(s&&a[p]) && !y[i][p]) { // fill the spot, and indicate that this row, column and diagonals // contain this number, c b[r][i]=c; x[r][p]=1; y[i][p]=1; if (m) d[p]=1; if (s)a[p]=1; // move onto to the next number, if you find a solution, stop if (f(c+1,r)) return 1; // with this number in this spot, a solution is impossible, clear // its, and clear the checks b[r][i]=0; x[r][p]=0; y[i][p]=0; if (m) d[p]=0; if (s) a[p]=0; } } return 0; // a solution wasn't found } int main() { std::cin >> n; // get n from STDIN // initialization int i=0,j=0; b=new int*[n]; x=new int*[n]; y=new int*[n]; E(d); E(a); R(i) E(b[i]); E(x[i]); E(y[i]); // initialization the inner arrays of b, x, y d[i]=0; a[i]=0; R(j) b[i][j]=0; x[i][j]=0; y[i][j]=0; // ensure each point is initialized as 0 } } // find a solution starting at the top-left corner and print it if it finds one if (f(1,0)) { R(i) R(j) std::cout<<b[i][j]; } std::cout<<std::endl; } } } ``` [Answer] ## Clojure, ~~(215 + 258) \* 0.8 = 378.4~~ (174 + 255) \* 0.8 = 343.2 Split into two parts: error counting `S` and an anonymous function which does the actual optimization via [Tabu search](https://en.wikipedia.org/wiki/Tabu_search). Update: shorter `S` (counts distinct values within groups), less optimal starting state (no shuffle). ``` (defn S[I n](count(mapcat set(vals(apply merge-with concat(flatten(for[R[(range n)]i R j R v[[(I(+(* n i)j))]]][{[1 i]v}{[2 j]v}(if(= i j){3 v})(if(=(- n 1 i)j){4 v})]))))))) #(if-let[s({1[0]2()3()}%)]s(loop[I(vec(for[R[(range %)]i R j R]i))P #{}](let[[s I](last(sort-by first(for[R[(range(count I))]i R j R I[(assoc(assoc I i(I j))j(I i))]:when(not(P I))][(S I %)I])))](if(=(*(+(* % 2)2)%)s)(partition % I)(recur I(conj P I)))))) ``` Single core benchmarks (in milliseconds) for 4, 5, 6 and 7 run 3 times: ``` [[ 131.855337 132.96267 138.745981] [ 1069.187325 1071.189488 1077.339372] [ 9114.736987 9206.65368 9322.656693] [36546.309408 36836.567267 36928.346312]] ``` Original: ``` (defn S[I n](apply +(flatten(for[p(concat(partition n I)(for[p(apply map vector(partition n(range(count I))))](map I p))[(take-nth(inc n)I)][(rest(butlast(take-nth(dec n)I)))])](remove #{1}(vals(frequencies p))))))) #(if-let[s({1[0]2()3()}%)]s(loop[I(vec(flatten(map shuffle(repeat %(range %)))))P #{}](let[[s I](first(sort-by first(for[R[(range(count I))]i R j R I[(assoc(assoc I i(I j))j(I i))]:when(not(P I))][(S I %)I])))](if(= s 0)(partition % I)(recur I(conj P I)))))) ``` I wish `S` was shorter, but because it only counts occurrences of more than one / partition the stopping criterion is simple `(= s 0)`. Many CPU cycles are wasted for non-useful swaps, for example it doesn't improve the score if you swap `2` with `2`, and you don't need to swap numbers between rows as they all have distinct values to begin with. Benchmarks with Intel 6700K (in milliseconds): ``` (defn S[I n]( ... ) (def F #( ... )) (defmacro mytime[expr] `(let [start# (. System (nanoTime)) ret# ~expr] (/ (double (- (. System (nanoTime)) start#)) 1000000.0))) (pprint(vec(for[n[4 5 6 7]](vec(sort(repeatedly 5 #(mytime (F n))))))) [[ 43.445902 45.895107 47.277399 57.681634 62.594037] [ 222.964582 225.467034 240.532683 330.237721 593.686911] [2285.417473 2531.331068 3002.597908 6361.591714 8331.809410] [3569.62372 4779.062486 5725.905756 7444.941763 14120.796615]] ``` Multithreaded with `pmap`: ``` [[ 8.881905 16.343714 18.87262 18.9717890 22.194430] [ 90.963870 109.719332 163.00299 245.824443 385.365561] [ 355.872233 356.439256 1534.31059 2593.482767 3664.221550] [1307.727115 1554.00260 2068.35932 3626.878526 4029.543011]] ``` ]
[Question] [ As any *amateur* photographer can tell you, extreme post-processing is **always good.** One such technique is called "[miniature-faking](http://en.wikipedia.org/wiki/Miniature_faking)". The object is to make an image look like a photograph of a miniaturized, toy version of itself. This works best for photographs taken from a moderate/high angle to the ground, with a low variance in subject height, but can be applied with varying effectiveness to other images. **The challenge:** Take a photograph and apply a miniature-faking algorithm to it. There are many ways to do this, but for the purposes of this challenge, it boils down to: * **Selective blur** > > Some part of the image should be blurred to simulate a shallow depth-of-field. This is usually done along some gradient, whether linear or shaped. Choose whatever blur/gradient algorithm you like, but between 15-85% of the image must have "noticeable" blur. > > > * **Saturation boost** > > Pump up the color to make things appear they were painted by hand. Output must have an average saturation level of > +5% when compared to input. (using [HSV saturation](http://en.wikipedia.org/wiki/HSL_and_HSV#Saturation)) > > > * **Contrast Boost** > > Increase the contrast to simulate harsher lighting conditions (such as you see with an indoor/studio light rather than the sun). Output must have a contrast of > +5% when compared to input. (using [RMS algorithm](http://en.wikipedia.org/wiki/Contrast_%28vision%29#RMS_contrast)) > > > Those three alterations **must** be implemented, and **no other** enhancements/alterations are allowed. No cropping, sharpening, white balance adjustments, nothing. * Input is an image, and can be read from a file or memory. You may use external libraries to *read and write* the image, but you **cannot** use them to *process* the image. Supplied functions are also disallowed for this purpose (you can't just call `Image.blur()` for example) * There is no other input. The processing strengths, levels, etc, must be determined by the program, not by a human. * Output can be displayed or saved as a file in a standardized image format (PNG, BMP, etc). * Try to generalize. It should not work on only *one* image, but it's understandable that it won't work on *all* images. Some scenes simply do not respond well to this technique, no matter how good the algorithm. Apply common sense here, both when answering and voting on answers. * Behavior is undefined for invalid inputs, and those images which are impossible to satisfy the spec. For example, a grayscale image cannot be saturated (there is no base hue), a pure white imaged cannot have increased contrast, etc. * Include at least two output images in your answer: > > One must be generated from one of the images in [this dropbox folder](https://www.dropbox.com/sh/gc9zz3dg3lxg6ou/RNVpbzNnPW). There are six to choose from, but I tried to make them all viable to varying degrees. You can see sample outputs for each in the `example-outputs` subfolder. Please note that these are full 10MP JPG images straight out of the camera, so you have a lot of pixels to work on. > > > The other can be any image of your choice. Obviously, try to choose images that are freely usable. Also, include either the original image or a link to it for comparison. > > > --- For example, from this image: ![original](https://i.stack.imgur.com/jUZYQ.png) You might output something like: ![processed](https://i.stack.imgur.com/rieky.png) For reference, the example above was processed in GIMP with an angular box-shaped gradient gaussian blur, saturation +80, contrast +20. (I don't know what units GIMP uses for those) For more inspiration, or to get a better idea what you're trying to achieve, check out [this site](http://benthomas.net.au/), or [this one](http://www.uniqlo.com/calendar/). You can also search for `miniature faking` and `tilt shift photography` for examples. --- This is a popularity contest. Voters, vote for the entries you feel look the best while staying true to the objective. --- **Clarification:** Clarifying what functions are disallowed, it was not my intent to ban *math* functions. It was my intent to ban *image manipulation* functions. Yes, there's some overlap there, but things like FFT, convolutions, matrix math, etc, are useful in many other areas. You should *not* be using a function that simply takes an image and blurs. If you find a suitably mathy way to *create* a blur, that fair game. [Answer] ## Java : Reference Implementation Here's a basic reference implementation in Java. It works best on high-angle shots, and it's horribly inefficient. The blur is a very basic box blur, so it loops over the same pixels much more than necessary. The contrast and saturation *could* be combined into a single loop also, but the vast majority of the time spent is on blur, so it wouldn't see much gain from that. That being said, it works fairly quickly on images under 2MP or so. The 10MP image took some time to complete. The blur quality could easily be improved by using *basically anything* but a flat box blur. The contrast/saturation algorithms do their job, so no real complaints there. There is no real intelligence in the program. It uses constant factors for the blur, saturation, and contrast. I played around it with it to find happy medium settings. As a result, there *are* some scenes that it doesn't do very well. For instance, it pumps the contrast/saturation so much that images with large similarly-colored areas(think sky) break up into color bands. It's simple to use; just pass the file name in as the only argument. It outputs in PNG regardless of what the input file was. ### Examples: **From the dropbox selection:** These first images are scaled down for ease of posting. Click the image to see full-size. After: [![enter image description here](https://i.stack.imgur.com/DAz2b.jpg)](https://www.dropbox.com/s/614yodz9js31m18/loop_large_post.png) Before: [![enter image description here](https://i.stack.imgur.com/8mC3M.jpg)](https://www.dropbox.com/s/3mlk6ixs1gs0aec/loop_large.jpg) **Miscellaneous selection:** After: ![enter image description here](https://i.stack.imgur.com/JLLna.png) Before: ![enter image description here](https://i.stack.imgur.com/IJOSR.jpg) ``` import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class MiniFake { int maxBlur; int maxDist; int width; int height; public static void main(String[] args) { if(args.length < 1) return; new MiniFake().run(args[0]); } void run(String filename){ try{ BufferedImage in = readImage(filename); BufferedImage out = blur(in); out = saturate(out, 0.8); out = contrast(out, 0.6); String[] tokens = filename.split("\\."); String outname = tokens[0]; for(int i=1;i<tokens.length-1;i++) outname += "." + tokens[i]; ImageIO.write(out, "png", new File(outname + "_post.png")); System.out.println("done"); } catch (Exception e){ e.printStackTrace(); } } BufferedImage contrast(BufferedImage in, double level){ BufferedImage out = copyImage(in); long lumens=0; for(int x=0;x<width;x++) for(int y=0;y<height;y++){ int color = out.getRGB(x,y); lumens += lumen(getR(color), getG(color), getB(color)); } lumens /= (width * height); for(int x=0;x<width;x++) for(int y=0;y<height;y++){ int color = out.getRGB(x,y); int r = getR(color); int g = getG(color); int b = getB(color); double ratio = ((double)lumen(r, g, b) / (double)lumens) - 1d; ratio *= (1+level) * 0.1; r += (int)(getR(color) * ratio+1); g += (int)(getG(color) * ratio+1); b += (int)(getB(color) * ratio+1); out.setRGB(x,y,getColor(clamp(r),clamp(g),clamp(b))); } return out; } BufferedImage saturate(BufferedImage in, double level){ BufferedImage out = copyImage(in); for(int x=0;x<width;x++) for(int y=0;y<height;y++){ int color = out.getRGB(x,y); int r = getR(color); int g = getG(color); int b = getB(color); int brightness = Math.max(r, Math.max(g, b)); int grey = (int)(Math.min(r, Math.min(g,b)) * level); if(brightness == grey) continue; r -= grey; g -= grey; b -= grey; double ratio = brightness / (double)(brightness - grey); r = (int)(r * ratio); g = (int)(g * ratio); b = (int)(b * ratio); out.setRGB(x, y, getColor(clamp(r),clamp(g),clamp(b))); } return out; } BufferedImage blur(BufferedImage in){ BufferedImage out = copyImage(in); int[] rgb = in.getRGB(0, 0, width, height, null, 0, width); for(int i=0;i<rgb.length;i++){ double dist = Math.abs(getY(i)-(height/2)); dist = dist * dist / maxDist; int r=0,g=0,b=0,p=0; for(int x=-maxBlur;x<=maxBlur;x++) for(int y=-maxBlur;y<=maxBlur;y++){ int xx = getX(i) + x; int yy = getY(i) + y; if(xx<0||xx>=width||yy<0||yy>=height) continue; int color = rgb[getPos(xx,yy)]; r += getR(color); g += getG(color); b += getB(color); p++; } if(p>0){ r /= p; g /= p; b /= p; int color = rgb[i]; r = (int)((r*dist) + (getR(color) * (1 - dist))); g = (int)((g*dist) + (getG(color) * (1 - dist))); b = (int)((b*dist) + (getB(color) * (1 - dist))); } else { r = in.getRGB(getX(i), getY(i)); } out.setRGB(getX(i), getY(i), getColor(r,g,b)); } return out; } BufferedImage readImage(String filename) throws IOException{ BufferedImage image = ImageIO.read(new File(filename)); width = image.getWidth(); height = image.getHeight(); maxBlur = Math.max(width, height) / 100; maxDist = (height/2)*(height/2); return image; } public BufferedImage copyImage(BufferedImage in){ BufferedImage out = new BufferedImage(in.getWidth(), in.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics g = out.getGraphics(); g.drawImage(in, 0, 0, null); g.dispose(); return out; } static int clamp(int c){return c<0?0:c>255?255:c;} static int getColor(int a, int r, int g, int b){return (a << 24) | (r << 16) | (g << 8) | (b);} static int getColor(int r, int g, int b){return getColor(0xFF, r, g, b);} static int getR(int color){return color >> 16 & 0xFF;} static int getG(int color){return color >> 8 & 0xFF;} static int getB(int color){return color & 0xFF;} static int lumen(int r, int g, int b){return (r*299)+(g*587)+(b*114);} int getX(int pos){return pos % width;} int getY(int pos){return pos / width;} int getPos(int x, int y){return y*width+x;} } ``` [Answer] ## C# Instead of doing any iterative box blurs, I decided to go the entire way and write a Gaussian blur. The `GetPixel` calls really slow it down when using large kernels, but it's not really worthwhile to convert the methods to use `LockBits` unless we were processing some larger images. Some examples are below, which use the default tuning parameters I set (I didn't play with the tuning parameters much, because they seemed to work well for the test image). For the test case provided... ![1-Original](https://i.stack.imgur.com/ZwctM.png) ![1-Modified](https://i.stack.imgur.com/CesEv.jpg) Another... ![2-Original](https://i.stack.imgur.com/NoCPJ.jpg) ![2-Modified](https://i.stack.imgur.com/Gk6kx.jpg) Another... ![3-Original](https://i.stack.imgur.com/TQ8x0.jpg) ![3-Modified](https://i.stack.imgur.com/Vkac4.jpg) The saturation and contrast increases should be fairly straightforward from the code. I do this in the HSL space and convert it back to RGB. The [2D Gaussian kernel](http://en.wikipedia.org/wiki/Gaussian_function#Two-dimensional_Gaussian_function) is generated based on the size `n` specified, with: ``` EXP(-((x-x0)^2/2+(y-y0)^2/2)/2) ``` ...and normalized after all kernel values are assigned. Note that `A=sigma_x=sigma_y=1`. In order to figure out where to apply the kernel, I use a blur weight, calculated by: ``` SQRT([COS(PI*x_norm)^2 + COS(PI*y_norm)^2]/2) ``` ...which gives a decent response, essentially creating an ellipse of values that are protected from the blur that gradually fades further out. A band-pass filter combined with other equations (maybe some variant of `y=-x^2`) could potentially work better here for certain images. I went with the cosine because it gave a good response for the base case I tested. ``` using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; namespace FakeMini { static class Program { static void Main() { // Some tuning variables double saturationValue = 1.7; double contrastValue = 1.2; int gaussianSize = 13; // Must be odd and >1 (3, 5, 7...) // NxN Gaussian kernel int padding = gaussianSize / 2; double[,] kernel = GenerateGaussianKernel(gaussianSize); Bitmap src = null; using (var img = new Bitmap(File.OpenRead("in.jpg"))) { src = new Bitmap(img); } // Bordering could be avoided by reflecting or wrapping instead // Also takes advantage of the fact that a new bitmap returns zeros from GetPixel Bitmap border = new Bitmap(src.Width + padding*2, src.Height + padding*2); // Get average intensity of entire image double intensity = 0; for (int x = 0; x < src.Width; x++) { for (int y = 0; y < src.Height; y++) { intensity += src.GetPixel(x, y).GetBrightness(); } } double averageIntensity = intensity / (src.Width * src.Height); // Modify saturation and contrast double brightness; double saturation; for (int x = 0; x < src.Width; x++) { for (int y = 0; y < src.Height; y++) { Color oldPx = src.GetPixel(x, y); brightness = oldPx.GetBrightness(); saturation = oldPx.GetSaturation() * saturationValue; Color newPx = FromHSL( oldPx.GetHue(), Clamp(saturation, 0.0, 1.0), Clamp(averageIntensity - (averageIntensity - brightness) * contrastValue, 0.0, 1.0)); src.SetPixel(x, y, newPx); border.SetPixel(x+padding, y+padding, newPx); } } // Apply gaussian blur, weighted by corresponding sine value based on height double blurWeight; Color oldColor; Color newColor; for (int x = padding; x < src.Width+padding; x++) { for (int y = padding; y < src.Height+padding; y++) { oldColor = border.GetPixel(x, y); newColor = Convolve2D( kernel, GetNeighbours(border, gaussianSize, x, y) ); // sqrt([cos(pi*x_norm)^2 + cos(pi*y_norm)^2]/2) gives a decent response blurWeight = Clamp(Math.Sqrt( Math.Pow(Math.Cos(Math.PI * (y - padding) / src.Height), 2) + Math.Pow(Math.Cos(Math.PI * (x - padding) / src.Width), 2)/2.0), 0.0, 1.0); src.SetPixel( x - padding, y - padding, Color.FromArgb( Convert.ToInt32(Math.Round(oldColor.R * (1 - blurWeight) + newColor.R * blurWeight)), Convert.ToInt32(Math.Round(oldColor.G * (1 - blurWeight) + newColor.G * blurWeight)), Convert.ToInt32(Math.Round(oldColor.B * (1 - blurWeight) + newColor.B * blurWeight)) ) ); } } border.Dispose(); // Configure some save parameters EncoderParameters ep = new EncoderParameters(3); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); ep.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.ScanMethod, (int)EncoderValue.ScanMethodInterlaced); ep.Param[2] = new EncoderParameter(System.Drawing.Imaging.Encoder.RenderMethod, (int)EncoderValue.RenderProgressive); ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo codec in codecs) { if (codec.MimeType == "image/jpeg") ici = codec; } src.Save("out.jpg", ici, ep); src.Dispose(); } // Create RGB from HSL // (C# BCL allows me to go one way but not the other...) private static Color FromHSL(double h, double s, double l) { int h0 = Convert.ToInt32(Math.Floor(h / 60.0)); double c = (1.0 - Math.Abs(2.0 * l - 1.0)) * s; double x = (1.0 - Math.Abs((h / 60.0) % 2.0 - 1.0)) * c; double m = l - c / 2.0; int m0 = Convert.ToInt32(255 * m); int c0 = Convert.ToInt32(255*(c + m)); int x0 = Convert.ToInt32(255*(x + m)); switch (h0) { case 0: return Color.FromArgb(255, c0, x0, m0); case 1: return Color.FromArgb(255, x0, c0, m0); case 2: return Color.FromArgb(255, m0, c0, x0); case 3: return Color.FromArgb(255, m0, x0, c0); case 4: return Color.FromArgb(255, x0, m0, c0); case 5: return Color.FromArgb(255, c0, m0, x0); } return Color.FromArgb(255, m0, m0, m0); } // Just so I don't have to write "bool ? val : val" everywhere private static double Clamp(double val, double min, double max) { if (val >= max) return max; else if (val <= min) return min; else return val; } // Simple convolution as C# BCL doesn't appear to have any private static Color Convolve2D(double[,] k, Color[,] n) { double r = 0; double g = 0; double b = 0; for (int i=0; i<k.GetLength(0); i++) { for (int j=0; j<k.GetLength(1); j++) { r += n[i,j].R * k[i,j]; g += n[i,j].G * k[i,j]; b += n[i,j].B * k[i,j]; } } return Color.FromArgb( Convert.ToInt32(Math.Round(r)), Convert.ToInt32(Math.Round(g)), Convert.ToInt32(Math.Round(b))); } // Generates a simple 2D square (normalized) Gaussian kernel based on a size // No tuning parameters - just using sigma = 1 for each private static double [,] GenerateGaussianKernel(int n) { double[,] kernel = new double[n, n]; double currentValue; double normTotal = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { currentValue = Math.Exp(-(Math.Pow(i - n / 2, 2) + Math.Pow(j - n / 2, 2)) / 2.0); kernel[i, j] = currentValue; normTotal += currentValue; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { kernel[i, j] /= normTotal; } } return kernel; } // Gets the neighbours around the current pixel private static Color[,] GetNeighbours(Bitmap bmp, int n, int x, int y) { Color[,] neighbours = new Color[n, n]; for (int i = -n/2; i < n-n/2; i++) { for (int j = -n/2; j < n-n/2; j++) { neighbours[i+n/2, j+n/2] = bmp.GetPixel(x + i, y + j); } } return neighbours; } } } ``` [Answer] # Java Uses a fast running-average two-way box blur to be speedy enough to run multiple passes, emulating a Gaussian blur. Blur is an elliptical gradient instead of bi-linear as well. Visually, it works best on large images. Has a darker, grungier theme. I'm happy with how the blur turned out on appropriately-sized images, it's quite gradual and hard to discern where it "begins." All computations done on arrays of integers or doubles (for HSV). Expects file path as argument, outputs file to same location with suffix " miniaturized.png" Also displays the input and output in a JFrame for immediate viewing. (click to see large versions, they're way better) ### Before: [![https://i.stack.imgur.com/l16lH.jpg](https://i.stack.imgur.com/ztqCu.jpg)](https://i.stack.imgur.com/ztqCu.jpg) ### After: [![enter image description here](https://i.stack.imgur.com/jqHgC.jpg)](https://i.stack.imgur.com/CVyXg.jpg) I may have to add some smarter tone mapping or luma preservation, as it can get quite dark: ### Before: [![enter image description here](https://i.stack.imgur.com/HPcTM.jpg)](https://i.stack.imgur.com/wm1Ba.jpg) ### After: [![enter image description here](https://i.stack.imgur.com/nEn2G.jpg)](https://i.stack.imgur.com/u5ql8.jpg) Still interesting though, puts it in a whole new atmosphere. ### The Code: ``` import java.awt.*; import java.awt.image.*; import java.io.*; import javax.imageio.*; import javax.swing.*; public class SceneMinifier { static final double CONTRAST_INCREASE = 8; static final double SATURATION_INCREASE = 7; public static void main(String[] args) throws IOException { if (args.length < 1) { System.out.println("Please specify an input image file."); return; } BufferedImage temp = ImageIO.read(new File(args[0])); BufferedImage input = new BufferedImage(temp.getWidth(), temp.getHeight(), BufferedImage.TYPE_INT_ARGB); input.getGraphics().drawImage(temp, 0, 0, null); // just want to guarantee TYPE_ARGB int[] pixels = ((DataBufferInt) input.getData().getDataBuffer()).getData(); // saturation double[][] hsv = toHSV(pixels); for (int i = 0; i < hsv[1].length; i++) hsv[1][i] = Math.min(1, hsv[1][i] * (1 + SATURATION_INCREASE / 10)); // contrast int[][] rgb = toRGB(hsv[0], hsv[1], hsv[2]); double c = (100 + CONTRAST_INCREASE) / 100; c *= c; for (int i = 0; i < pixels.length; i++) for (int q = 0; q < 3; q++) rgb[q][i] = (int) Math.max(0, Math.min(255, ((rgb[q][i] / 255. - .5) * c + .5) * 255)); // blur int w = input.getWidth(); int h = input.getHeight(); int k = 5; int kd = 2 * k + 1; double dd = 1 / Math.hypot(w / 2, h / 2); for (int reps = 0; reps < 5; reps++) { int tmp[][] = new int[3][pixels.length]; int vmin[] = new int[Math.max(w, h)]; int vmax[] = new int[Math.max(w, h)]; for (int y = 0, yw = 0, yi = 0; y < h; y++) { int[] sum = new int[3]; for (int i = -k; i <= k; i++) { int ii = yi + Math.min(w - 1, Math.max(i, 0)); for (int q = 0; q < 3; q++) sum[q] += rgb[q][ii]; } for (int x = 0; x < w; x++) { int dx = x - w / 2; int dy = y - h / 2; double dist = Math.sqrt(dx * dx + dy * dy) * dd; dist *= dist; for (int q = 0; q < 3; q++) tmp[q][yi] = (int) Math.min(255, sum[q] / kd * dist + rgb[q][yi] * (1 - dist)); if (y == 0) { vmin[x] = Math.min(x + k + 1, w - 1); vmax[x] = Math.max(x - k, 0); } int p1 = yw + vmin[x]; int p2 = yw + vmax[x]; for (int q = 0; q < 3; q++) sum[q] += rgb[q][p1] - rgb[q][p2]; yi++; } yw += w; } for (int x = 0, yi = 0; x < w; x++) { int[] sum = new int[3]; int yp = -k * w; for (int i = -k; i <= k; i++) { yi = Math.max(0, yp) + x; for (int q = 0; q < 3; q++) sum[q] += tmp[q][yi]; yp += w; } yi = x; for (int y = 0; y < h; y++) { int dx = x - w / 2; int dy = y - h / 2; double dist = Math.sqrt(dx * dx + dy * dy) * dd; dist *= dist; for (int q = 0; q < 3; q++) rgb[q][yi] = (int) Math.min(255, sum[q] / kd * dist + tmp[q][yi] * (1 - dist)); if (x == 0) { vmin[y] = Math.min(y + k + 1, h - 1) * w; vmax[y] = Math.max(y - k, 0) * w; } int p1 = x + vmin[y]; int p2 = x + vmax[y]; for (int q = 0; q < 3; q++) sum[q] += tmp[q][p1] - tmp[q][p2]; yi += w; } } } // pseudo-lighting pass for (int i = 0; i < pixels.length; i++) { int dx = i % w - w / 2; int dy = i / w - h / 2; double dist = Math.sqrt(dx * dx + dy * dy) * dd; dist *= dist; for (int q = 0; q < 3; q++) { if (dist > 1 - .375) rgb[q][i] *= 1 + (Math.sqrt((1 - dist + .125) / 2) - (1 - dist) - .125) * .7; if (dist < .375 || dist > .375) rgb[q][i] *= 1 + (Math.sqrt((dist + .125) / 2) - dist - .125) * dist > .375 ? 1 : .8; rgb[q][i] = Math.min(255, Math.max(0, rgb[q][i])); } } // reassemble image BufferedImage output = new BufferedImage(input.getWidth(), input.getHeight(), BufferedImage.TYPE_INT_ARGB); pixels = ((DataBufferInt) output.getData().getDataBuffer()).getData(); for (int i = 0; i < pixels.length; i++) pixels[i] = 255 << 24 | rgb[0][i] << 16 | rgb[1][i] << 8 | rgb[2][i]; output.setRGB(0, 0, output.getWidth(), output.getHeight(), pixels, 0, output.getWidth()); // display results display(input, output); // output image ImageIO.write(output, "PNG", new File(args[0].substring(0, args[0].lastIndexOf('.')) + " miniaturized.png")); } private static int[][] toRGB(double[] h, double[] s, double[] v) { int[] r = new int[h.length]; int[] g = new int[h.length]; int[] b = new int[h.length]; for (int i = 0; i < h.length; i++) { double C = v[i] * s[i]; double H = h[i]; double X = C * (1 - Math.abs(H % 2 - 1)); double ri = 0, gi = 0, bi = 0; if (0 <= H && H < 1) { ri = C; gi = X; } else if (1 <= H && H < 2) { ri = X; gi = C; } else if (2 <= H && H < 3) { gi = C; bi = X; } else if (3 <= H && H < 4) { gi = X; bi = C; } else if (4 <= H && H < 5) { ri = X; bi = C; } else if (5 <= H && H < 6) { ri = C; bi = X; } double m = v[i] - C; r[i] = (int) ((ri + m) * 255); g[i] = (int) ((gi + m) * 255); b[i] = (int) ((bi + m) * 255); } return new int[][] { r, g, b }; } private static double[][] toHSV(int[] c) { double[] h = new double[c.length]; double[] s = new double[c.length]; double[] v = new double[c.length]; for (int i = 0; i < c.length; i++) { double r = (c[i] & 0xFF0000) >> 16; double g = (c[i] & 0xFF00) >> 8; double b = c[i] & 0xFF; r /= 255; g /= 255; b /= 255; double M = Math.max(Math.max(r, g), b); double m = Math.min(Math.min(r, g), b); double C = M - m; double H = 0; if (C == 0) H = 0; else if (M == r) H = (g - b) / C % 6; else if (M == g) H = (b - r) / C + 2; else if (M == b) H = (r - g) / C + 4; h[i] = H; s[i] = C / M; v[i] = M; } return new double[][] { h, s, v }; } private static void display(final BufferedImage original, final BufferedImage output) { Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); int wt = original.getWidth(); int ht = original.getHeight(); double ratio = (double) wt / ht; if (ratio > 1 && wt > d.width / 2) { wt = d.width / 2; ht = (int) (wt / ratio); } if (ratio < 1 && ht > d.getHeight() / 2) { ht = d.height / 2; wt = (int) (ht * ratio); } final int w = wt, h = ht; JFrame frame = new JFrame(); JPanel pan = new JPanel() { BufferedImage buffer = new BufferedImage(w * 2, h, BufferedImage.TYPE_INT_RGB); Graphics2D gg = buffer.createGraphics(); { gg.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } @Override public void paint(Graphics g) { gg.drawImage(original, 0, 0, w, h, null); gg.drawImage(output, w, 0, w, h, null); g.drawImage(buffer, 0, 0, null); } }; frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pan.setPreferredSize(new Dimension(w * 2, h)); frame.setLayout(new BorderLayout()); frame.add(pan, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } } ``` [Answer] # [J](http://jsoftware.com) This was a nice challenge. The settings for blur, saturation, and contrast are hard-coded but can be easily changed if desired. However, the area in focus is hard-coded as a horizontal line in the center. It can not be simply modified like the other settings. It was chosen since most of the test images feature views across a city. After performing a Gaussian blur, I split the image horizontally into 5 regions. The top and bottom regions will receive 100% of the blur. The middle region will receive 0% of the blur. The two remaining regions will both scale proportionally to the inverse cube from 0% to 100%. The code is to be used as a script in J and that script will be in the same folder as `input.bmp` which will be the input image. It will create `output.bmp` which will be a *fake miniature* of the input. The performance is good and on my pc using an i7-4770k, it takes about 20 seconds to process an image from the OP's set. Previously, it took about 70 seconds to process an image using standard convolution with the `;._3` subarray operator. The performance was improved by using FFT to perform convolution. [![Loop](https://i.stack.imgur.com/xg5r1.png)](https://i.stack.imgur.com/nGGb6.jpg) [![Loop-Mini](https://i.stack.imgur.com/WDF7V.jpg)](https://i.stack.imgur.com/CwqIV.jpg) [![City](https://i.stack.imgur.com/JZX4v.png)](https://i.stack.imgur.com/8MwQQ.jpg) [![City-Mini](https://i.stack.imgur.com/6QNMU.jpg)](https://i.stack.imgur.com/HVdbG.jpg) This code requires the `bmp` and `math/fftw` addons to be installed. You can install them using `install 'bmp'` and `install 'math/fftw'`. Your system may also need the `fftw` library to be installed. ``` load 'bmp math/fftw' NB. Define 2d FFT fft2d =: 4 : 0 s =. $ y i =. zzero_jfftw_ + , y o =. 0 * i p =. createplan_jfftw_ s;i;o;x;FFTW_ESTIMATE_jfftw_ fftwexecute_jfftw_ p destroyplan_jfftw_ p r =. s $ o if. x = FFTW_BACKWARD_jfftw_ do. r =. r % */ s end. r ) fft2 =: (FFTW_FORWARD_jfftw_ & fft2d) :. (FFTW_BACKWARD_jfftw & fft2d) ifft2 =: (FFTW_BACKWARD_jfftw_ & fft2d) :. (FFTW_FORWARD_jfftw & fft2d) NB. Settings: Blur radius - Saturation - Contrast br =: 15 s =: 3 c =: 1.5 NB. Read image and extract rgb channels i =: 255 %~ 256 | (readbmp 'input.bmp') <.@%"_ 0 ] 2 ^ 16 8 0 'h w' =: }. $ i NB. Pad each channel to fit Gaussian blur kernel 'hp wp' =: (+: br) + }. $ i ip =: (hp {. wp {."1 ])"_1 i NB. Gaussian matrix verb gm =: 3 : '(%+/@,)s%~2p1%~^(s=.*:-:y)%~-:-+&*:/~i:y' NB. Create a Gaussian blur kernel gk =: fft2 hp {. wp {."1 gm br NB. Blur each channel using FFT-based convolution and unpad ib =: (9 o. (-br) }. (-br) }."1 br }. br }."1 [: ifft2 gk * fft2)"_1 ip NB. Create the blur gradient to emulate tilt-shift m =: |: (w , h) $ h ({. >. (({.~ -)~ |.)) , 1 ,: |. (%~i.) 0.2 I.~ (%~i.) h NB. Tilt-shift each channel it =: i ((m * ]) + (-. m) * [)"_1 ib NB. Create the saturation matrix sm =: |: ((+ ] * [: =@i. 3:)~ 3 3 |:@$ 0.299 0.587 0.114 * -.) s NB. Saturate and clamp its =: 0 >. 1 <. sm +/ .*"1 _ it NB. Contrast and clamp itsc =: 0 >. 1 <. 0.5 + c * its - 0.5 NB. Output the image 'output.bmp' writebmp~ (2 <.@^ 16 8 0) +/ .* 255 <.@* itsc exit '' ``` ]
[Question] [ You are to approximate the value of: $$\int^I\_0 \frac {e^x} {x^x} dx$$ Where your input is \$I\$. # Rules * You may not use any built-in integral functions. * You may not use any built-in infinite summation functions. * Your code must execute in a reasonable amount of time ( < 20 seconds on my machine) * You may assume that input is greater than 0 but less than your language's upper limit. * It may be any form of standard return/output. You can verify your results at [Wolfram | Alpha](http://www.wolframalpha.com/input/?i=integrate+e%5Ex%2Fx%5Ex+from+0+to) (you can verify by concatenating your intended input to the linked query). # Examples (let's call the function `f`) ``` f(1) -> 2.18273 f(50) -> 6.39981 f(10000) -> 6.39981 f(2.71828) -> 5.58040 f(3.14159) -> 5.92228 ``` Your answer should be accurate to `±.0001`. [Answer] # Julia, ~~79~~ ~~77~~ 38 bytes ``` I->sum(x->(e/x)^x,0:1e-5:min(I,9))/1e5 ``` This is an anonymous function that accepts a numeric value and returns a float. To call it, assign it to a variable. The approach here is to use a right Riemann sum to approximate the integral, which is given by the following formula: $$\int\_a^b f(x) dx \approx \sum f(x) \Delta x$$ In our case, \$a = 0\$ and \$b = I\$, the input. We divide the region of integration into \$n = 10^5\$ discrete portions, so \$∆x = \frac 1 n = 10^{-5}\$. Since this is a constant relative to the sum, we can pull this outside of the sum and simply sum the function evaluations at each point and divide by \$n\$. The function is surprisingly well-behaved (plot from Mathematica): [![mathematicaplot](https://i.stack.imgur.com/RLKPH.png)](https://i.stack.imgur.com/RLKPH.png) Since the function evaluates nearly to 0 for inputs greater than about 9, we truncate the input to be \$I\$ if \$I\$ is less than 9, or 9 otherwise. This simplifies the calculations we have to do significantly. Ungolfed code: ``` function g(I) # Define the range over which to sum. We truncate the input # at 9 and subdivide the region into 1e5 pieces. range = 0:1e-5:min(I,9) # Evaluate the function at each of the 1e5 points, sum the # results, and divide by the number of points. return sum(x -> (e / x)^x, range) / 1e5 end ``` Saved 39 bytes thanks to Dennis! [Answer] # Jelly, ~~20~~ ~~19~~ 17 bytes ``` ð«9×R÷øȷ5µØe÷*×ḢS ``` This borrows the clever *truncate at 9* trick from [@AlexA.'s answer](https://codegolf.stackexchange.com/a/71314), and uses a [right Riemann sum](https://en.wikipedia.org/wiki/Riemann_sum#Right_Riemann_Sum) to estimate the corresponding integral. Truncated test cases take a while, but are fast enough on [Try it online!](http://jelly.tryitonline.net/#code=w7DCqznDl1LDt8O4yLc1wrXDmGXDtyrDl-G4olM&input=&args=MTA&debug=on) ### How it works ``` ð«9×R÷øȷ5µØe÷*×ḢS Main link. Input: I øȷ5 Niladic chain. Yields 1e5 = 100,000. ð Dyadic chain. Left argument: I. Right argument: 1e5. «9 Compute min(I, 9). × Multiply the minimum with 1e5. R Range; yield [1, 2, ..., min(I, 9) * 1e5] or [0] if I < 1e-5. ÷ Divide the range's items by 1e5. This yields r := [1e-5, 2e-5, ... min(I, 9)] or [0] if I < 1e-5. µ Monadic chain. Argument: r Øe÷ Divide e by each element of r. * Elevate the resulting quotients to the corresponding elements, mapping t -> (e/t) ** t over r. For the special case of r = [0], this yields [1], since (e/0) ** 0 = inf ** 0 = 1 in Jelly. ×Ḣ Multiply each power by the first element of r, i.e., 1e-5 or 0. S Add the resulting products. ``` [Answer] ## ES7, 78 bytes ``` i=>[...Array(n=2e3)].reduce(r=>r+Math.exp(j+=i)/j**j,0,i>9?i=9:0,i/=n,j=-i/2)*i ``` This uses the rectangle rule with 2000 rectangles, which (at least for the examples) seem to produce a sufficiently accurate answer, but the accuracy could easily be increased if necessary. It has to use the 9 trick otherwise the accuracy drops off for large values. 73 byte version that uses rectangles of width ~0.001 so it doesn't work above ~700 because Math.exp hits Infinity: ``` i=>[...Array(n=i*1e3|0)].reduce(r=>r+Math.exp(j+=i)/j**j,0,i/=n,j=-i/2)*i ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 26 bytes ``` 9hX<t1e6XK:K/*ttZebb^/sK/* ``` This approximates the integral as a Riemann sum. As argued by Alex, we can truncate the integration interval at approximately 9 because the function values are very small beyond that. The maximum value of the function is less than 3, so a step of about 1e-5 should be enough to obtain the desired accuracy. So for the maximum input 9 we need about 1e6 points. This takes about 1.5 seconds in the online compiler, for any input value. [**Try it online**!](http://matl.tryitonline.net/#code=OWhYPHQxZTZYSzpLLyp0dFplYmJeL3NLLyo&input=My4xNDE1OQ) ``` 9hX< % input number, and limit to 9 t % duplicate 1e6XK: % generate vector [1,2,...,1e6]. Copy 1e6 to clipboard K K/* % divide by 1e6 and multiply by truncated input. This gives % a vector with 1e6 values of x from 0 to truncated input ttZe % duplicate twice. Compute exp(x) bb^ % rotate top three elements of stack twice. Compute x^x / % divide to compute exp(x)/x^x s % sum function values K/* % multiply by the step, which is the truncated input divided % by 1e6 ``` [Answer] # [golflua](http://mniip.com/misc/conv/golflua/), 83 chars I'll admit it: it took my a while to figure out the `min(I,9)` trick Alex presented allowed computing arbitrarily high numbers because the integral converged by then. ``` \f(x)~M.e(x)/x^x$b=M.mn(I.r(),9)n=1e6t=b/n g=0.5+f(b/2)~@k=1,n-1g=g+f(k*t)$I.w(t*g) ``` An ungolfed Lua equivalent would be ``` function f(x) return math.exp(x)/x^x end b=math.min(io.read("*n"),9) n=1e6 t=b/n g=0.5+f(b/2) for k=1,n-1 do g=g+f(k*t) end io.write(t*g) ``` [Answer] # Python 2, ~~94~~ 76 bytes Thanks to @Dennis for saving me 18 bytes! ``` lambda I,x=1e5:sum((2.71828/i*x)**(i/x)/x for i in range(1,int(min(I,9)*x))) ``` [Try it online with testcases!](https://repl.it/Bk6w/2) Using the rectangle method for the approximation. Using a rectangle width of 0.0001 which gives me the demanded precision. Also truncating inputs greater 9 to prevent memory errors with very big inputs. [Answer] # Perl 6, ~~90~~ 55 bytes ``` {my \x=1e5;sum ((e/$_*x)**($_/x)/x for 1..min($_,9)*x)} ``` **usage** ``` my &f = {my \x=1e5;sum ((e/$_*x)**($_/x)/x for 1..min($_,9)*x)} f(1).say; # 2.1827350239231 f(50).say; # 6.39979602775846 f(10000).say; # 6.39979602775846 f(2.71828).say; # 5.58039854392816 f(3.14159).say; # 5.92227602782184 ``` It's late and I need to sleep, I'll see if I can get this any shorter tomorrow. EDIT: Managed to get it quite a bit shorter after seeing @DenkerAffe 's method. [Answer] # Pyth, ~~34~~ 29 bytes Saved 5 Bytes with some help from @Dennis! ``` J^T5smcc^.n1d^ddJmcdJU*hS,Q9J ``` [Try it online!](http://pyth.herokuapp.com/?code=J%5ET5smcc%5E.n1d%5EddJmcdJU*hS%2CQ9J&input=1&test_suite_input=1%0A50%0A10000%0A2.71828%0A3.14159&debug=0) ### Explanation Same algorithm as in [my Python answer](https://codegolf.stackexchange.com/a/71346/49110). ``` J^T5smcc^.n1d^ddJmcdJU*hS,Q9J # Q=input J^T5 # set J so rectangle width *10^5 hS,Q9 # truncate inputs greater 9 mcdJU/ J # range from zero to Input in J steps mcc^.n1d^ddJ # calculate area for each element in the list s # Sum all areas and output result ``` [Answer] # Vitsy, 39 bytes Thought I might as well give my own contribution. ¯\\_(ツ)\_/¯ This uses the Left-Hand Riemann Sum estimation of integrals. ``` D9/([X9]1a5^D{/V}*0v1{\[EvV+DDv{/}^+]V* D9/([X9] Truncation trick from Alex A.'s answer. D Duplicate input. 9/ Divide it by 9. ([ ] If the result is greater than 0 X9 Remove the top item of the stack, and push 9. 1a5^D{/V}*0v0{ Setting up for the summation. 1 Push 1. a5^ Push 100000. D Duplicate the top item of the stack. { Push the top item of the stack to the back. / Divide the top two items of the stack. (1/100000) V Save it as a global variable. Our global variable is ∆x. } Push the bottom item of the stack to the top. * Multiply the top two items. input*100000 is now on the stack. 0v Save 0 as a temporary variable. 0 Push 1. { Push the bottom item of the stack to the top. input*100000 is now the top of the stack. \[EvV+DDv{/}^+] Summation. \[ ] Loop over this top item of the stack times. input*100000 times, to be exact. E Push Math.E to the stack. v Push the temporary variable to the stack. This is the current value of x. V+ Add ∆x. DD Duplicate twice. v Save the temporary variable again. { Push the top item of the stack to the back. / Divide the top two items. e/x } Push the top item back to the top of the stack. ^ Put the second to top item of the stack to the power of the top item. (e/x)^x + Add that to the current sum. V* Multiply by ∆x ``` This leaves the sum on the top of the stack. The try it online link below has `N` on the end to show you the result. [Try it Online!](http://vitsy.tryitonline.net/#code=RDkvKFtYOV0xYTVeRHsvVn0qMHYwe1xbRXZWK0REdnsvfV4rXVYqTg&input=&args=OQ) ]
[Question] [ Sometimes when writing brainfuck code, you feel the need to make it longer than needed to *encourage* debugging. You could do it by just plopping a `><` in there, but what fun is that? You'll need something longer and less NOPey to confuse anybody reading your code. ## Quick introduction to Brainfuck > > [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck) is an esoteric programming language created in 1993 by Urban Müller, and notable for its extreme minimalism. (Wikipedia) > > > Brainfuck is a language based on eight commands: `+-><,.[]`. The code is run on something like a Turing machine: an infinite tape on which values can be changed. In this challenge, we'll focus on the first four: ``` + increment the value at the pointer - decrement the value at the pointer > move the pointer right < move the pointer left ``` ## Brainfuck NOPs A brainfuck NOP is a sequence of brainfuck characters that, when executed from any state, leads to no change in the state. They consist of the four characters mentioned above. ## The Challenge The challenge is to write a program or function that, when executed, generates a random brainfuck NOP of the given length. ## Input You will receive as input a nonnegative even integer `n`. (NOPs are impossible for odd `n`.) ## Output You will output a random brainfuck NOP of the length `n`. ## Rules * The definition of NOP: when the output of the program is inserted at any point in a brainfuck program, the behavior of said program must not change in any way. In other words, it must not change the state of the interpreter. + Note that for example `+>-<` is incorrect, since it changes the values of the two cells without changing them back. Please test your solution for these before posting. + Also note that `+>-<->+<` is a NOP that can't be reduced to nothing just by removing `><` `<>` `+-` `-+`. Thus, you can't use an algorithm that just inserts these inside each other. * Every valid NOP of the length `n` must have a nonzero chance of appearing in the output. The distribution does not have to be uniform, though. * The brainfuck interpreter in question has a doubly infinite tape of arbitrary precision cells. That is, you can go infinitely to the both directions, and increment/decrement each cell indefinitely. * The program must finish **within 1 minute for `n` = 100** on my machine, so no generating all possible NOPs and picking one. * If given invalid input (non-integer, negative, odd, etc.) you may do anything you'd like, including crash. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. ## Examples Here are all valid outputs for `n` = 4: ``` ++-- +-+- +--+ --++ -+-+ -++- >><< ><>< ><<> <<>> <><> <>>< ><+- ><-+ <>+- <>-+ >+-< >-+< <+-> <-+> +><- -><+ +<>- -<>+ +->< -+>< +-<> -+<> ``` Here are a few possible outputs for `n` = 20: ``` +>>->+<->-<<<->>++<< >+>-<+<->+-<>->+<-<+ +--+-++--++-+--+-++- >>>>>>>>>+-<<<<<<<<< ``` [Answer] ## CJam, ~~118~~ 116 bytes This got slightly out of hand... especially the second half seems like it should be very golfable. ``` ri2/_)mr:R-"<>"R*mr_'=fm0\{1$+}%+__&e`]:\{mr1aa..+}*\@](\z:~\{~\("+-"*mr1$3$e=[{_,)mr_2$<@@>}*+]@@f{`1$`={(}@?\}W<}/ ``` [Test it here.](http://cjam.aditsu.net/#code=ri2%2F_)mr%3AR-%22%3C%3E%22R*mr_'%3Dfm0%5C%7B1%24%2B%7D%25%2B__%26e%60%5D%3A%5C%7Bmr1aa..%2B%7D*%5C%40%5D(%5Cz%3A~%5C%7B~%5C(%22%2B-%22*mr1%243%24e%3D%5B%7B_%2C)mr_2%24%3C%40%40%3E%7D*%2B%5D%40%40f%7B%601%24%60%3D%7B(%7D%40%3F%5C%7DW%3C%7D%2F&input=100) This handles `N = 100` pretty much instantly. I don't have time to write the full breakdown of the code now, so here is the algorithm: * Generate a random balanced string of `<` and `>` with random (even) length between `0` and `N` inclusive. * Riffle the tape head positions into this array. E.g. `"<>><"` becomes `[0 '< -1 '> 0 '> 1 '< 0]`. * Get a list of all positions reached in the process. * For each such position initialise an empty string. Also determine how many pairs of characters are left to reach a string of length `N`. * For each remaining pair append `+-` to the string of a random position. * Shuffle all of those strings. * For each position determine how often that position occurs in the riffled array, and split the corresponding string into that many (random-length) chunks. * In the riffled array, replace the occurrences of the position with its random chunks. Done. This is based on the observation that: * Any NOP must have an equal amount of `<` and `>` to return the tape head to the original position. * The code will be a NOP as long as each tape cell is incremented as often as decremented. By distributing random but balanced amounts of `+`s and `-`s between all the places where the tape head is on a given cell, we ensure that we find every possible NOP. [Answer] ## CJam, ~~62~~ 59 bytes *Thanks to nhahtdh for saving 3 bytes.* Because there is no requirement for any particular distribution as long as each no-op appears with finite probability, we can simplify this a lot by simply generating string containing a balanced number of `-+` and `<>`, respectively, testing if it's a NOP and sorting it if it isn't. Of course, for longer inputs, this will almost always result in sorted output, but you can test the code with some input like `8` to see that it can in principle produce any NOP of the given length. ``` ri_0a*\2/{;"-+<>":L2/mR}%smr:SL["Xa.Xm"3/2e*L]z:sers~0-S$S? ``` [Try it online.](http://cjam.tryitonline.net/#code=cmlfMGEqXDIvezsiLSs8PiI6TDIvbVJ9JXNtcjpTTFsiWGEuWG0iMy8yZSpMXXo6c2Vyc34wLVMkUz8&input=MTAw) [Answer] ## Mathematica, 350 bytes ``` Quiet@(For[a="+",If[{##4}=={},#3!=0||Union@#!={0},Switch[#4,"+",#0[ReplacePart[#,#2->#[[#2]]+1],#2,#3,##5],"-",#0[ReplacePart[#,#2->#[[#2]]-1],#2,#3,##5],">",#0[#~Append~0,#2+1,#3+1,##5],"<",If[#2<2,#0[#~Prepend~0,1,#3-1,##5],#0[#,#2-1,#3-1,##5]]]]&@@{{0},1,0}~Join~Characters@a,a=""<>RandomSample@Flatten@RandomChoice[{{"+","-"},{">","<"}},#/2]];a)& ``` Way too long? Yes. Do I even care? Not until someone else posts a valid answer. [Answer] # [Python 3](https://docs.python.org/3/), 177 bytes ``` from random import* n=int(input()) r=[0]*n*3 p=0 a=[43,45] s=choices(a+[60,62],k=n) for c in s:p+=~c%2*(c-61);r[p]+=c%2*(44-c) if any(r+[p]):s=a*(n//2) print(*map(chr,s),sep='') ``` [Try it online!](https://tio.run/##HY67DoMwDAD3fEWWqnEIKoWUoZW/BDFEaRFRhWM5dGDpr9PHdNLdcrytc6Zu3yfJi5ZA9y/SwllWqwgTrSYRv1YDoASHZrRkO8XYqICD75y/jKpgnHOKj2JCNfSN69vRPZFATVl01Il0uXKF73horYl1f4abDDxW@Bfe1xFUmnSgzUj1DXAtGKyh06kFxfJ7sEtgE2dxBVx5MB6PsO/@Aw "Python 3 – Try It Online") I used code from Bubbler's answer for the BF simulation. [Answer] # [Python 3](https://docs.python.org/3/), 163 bytes ``` from random import* n=int(input()) p=0;d=[0]*n;a=choices(b'+-<>',k=n) for c in a:d[p]+=c%2*(44-c);p+=~c%2*(c-61) if p|any(d):a=n//2*b'+-' print(*map(chr,a),sep='') ``` [Try it online!](https://tio.run/##HY7BbsIwEETv/oq9VGs7iQgUVSjp9kcQh8VOFItmvTJBKlLVX0@B02gOb97ofZmyvK9J9LYAwTfP58gdHtAMP0OwiLiOJc9QWOIj0qy5LN4IJVnsi7LOGaW2j3RsT156pjDlFIarPWPVfH5hfSFxZswFAiQB7uJRTxWFt523@30TXK8V/b1qaD62zqQR9JflbqPrmGSz2fnnFBotT6ufWW2YSs2uvg5KiG59/AQP29at/w "Python 3 – Try It Online") Full program that prints results to STDOUT. The line that runs BF code might be golfable. Adopted Tyilo's approach; if the generated BF code is not a NOP, discard it altogether and fall back to `'+-'` repeated. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 160 bytes ``` n=>[...s=c(i=n,t=c(n/2,r=[],f=_=>'+-'),f=_=>'+-<>'[Math.random()*4|0])].map(_=>_<'<'?(r[i]=_+1-~r[i]-1):(i+=_<'>'||-1))|r.some(eval)|i-n?t:s;c=n=>n?c(n-1)+f():r ``` [Try it online!](https://tio.run/##rU5BasMwELz3I5IqW7FDTrbXvuXWFwhhhGI3KrZkJDWXqP26u4HSayl0D7MzzDDMm77paILdUun8ZdrPsDvopRAigqEWXJHwu8OxCCBVMcMIPeElYT@064l80ekqgnYXv1L2fMqVYkqseqMYGTvSkYEGaRWMvC4/H6ysWUMtBzR7kjNKloOIfp3odNMLy7Z0Q2piawDnuAEnYIbPlDVhb5/i@wr3j3b2gRqXoGoRu7rCezDOGQbklgKcacUUfCvF65zr1ngX/TKJxb9SdNif6o7/W3f6vW7/Ag "JavaScript (Node.js) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 224 bytes ``` (s=RandomSample[##&@@@Table["<"">",(r=RandomInteger)[#/2]]];While[(g=Length@s)<#,s=Insert[s=Insert[s,"+",i=r@g+1],"-",RandomChoice@@Select[GatherBy[0~Range~++g,Count[#,"<"]-Count[#,">"]&@Take[s,#]&],!FreeQ[#,i]&]+1]];""<>s)& ``` [Try it online!](https://tio.run/##RY/BasMwEER/xV2BsfGGOLnGNiKBhkAPbVPoQeigOIssGstBUg@95NfdLSntbYYZZt@OJg00muR6Mz8H55Oai9i@Gn@exqMZrxdSQuRSyjdzYg0NQAdYhN/KwSeyFEollmut9eZ9cNwqbPtE3qZBxrIRGNuDjxSS@hcIFaBrg7TVSiMsAO97u2FyPUl5pAv1Se1/6ML2S9U3zi3dqsribvpkTIHMohd/pgOdM@QH8bjQucaHx0D0wpFjx1f0BqDpYpnP2VJm93dWNWbrmqP5Gw "Wolfram Language (Mathematica) – Try It Online") Here is the un-golfed (or rather, pre-golfed) version: ``` Function[{n}, k = RandomInteger[n/2]; s = RandomSample[## & @@@ Table["<" ">", k]]; While[Length[s] < n, s = Insert[s, "+", i = RandomInteger[Length[s]] + 1]; p = GatherBy[Range[0, Length[s]], Count[#, "<"] - Count[#, ">"]& @ Take[s, #]&]; j = RandomChoice @@ Select[p, ! FreeQ[#, i] &]]; s = Insert[s, "-", j + 1]; ]; ""<>s] ``` We first pick a random number of `<`'s and `>`'s to use, and generate a random list with an equal number of each. To fill in the rest of the characters, we pick a position in which to add a `+`, then find a position where the pointer points to the same location and add a `-` there. Repeat until the list has length `n`, and stringify the result. ]
[Question] [ Your company is just getting started on a project, and for the first time you decided to go use a functional programming code-style. However your boss is really diffident and doesn't want to use built-in functions, and requires you to implement yourself the main functions. In particular you need to write the functions: `Map`, `Nest`, `Apply`, `Range`, `Fold` and `Table` in a language on your choice. The boss is a really busy man, and he wants to have the programs as short as possible, so he doesn't waste time reading. He also would like not for you to use loops, therefore you will have a 10% reduction on the byte count for not using loops. The detailed requirements of the functions are below: ## Map The `Map` function takes two parameters: `f` and `list` where `f` is a function and `list` is a list of values. It should return the `f` applied to each element of `list`. Therefore it will work as such: ``` Map(f,{a,b,c}) ``` returns ``` { f(a), f(b), f(c) } ``` and ``` Map(f, {{a,b},{b,c}}) ``` returns ``` { f({a,b}), f({b,c})} ``` ## Nest The `Nest` function takes three parameters as well: `f`, `arg`, `times` where `f` is a function, `arg` is its starting argument, and `times` is how many times the function is applied. It should return an expression with `f` applied `times` times to `arg`. Therefore it will work as such: ``` Nest(f, x, 3) ``` returns ``` f(f(f(x))) ``` and ``` Nest(f, {a,b}, 3) ``` returns ``` f(f(f({a,b}))) ``` ## Apply The `Apply` function takes two parameters: `f` and `args` where `f` is a function and `args` a list. It should apply `f` to the `args`. Therefore: ``` Apply(f, {a,b,c}) ``` returns ``` f(a,b,c) ``` ## Range The `Range` function takes one integer`r` and outputs the integers up to that number. Therefore: ``` Range(5) ``` returns ``` { 1, 2, 3, 4, 5} ``` ## Fold The `Fold` function takes three parameters `f`, `arg`, `others` where `f` is a function, `arg` is simple parameter, and `others` a list. It will work as such: ``` Fold(f, x, {a, b, c, d}) ``` returns ``` f(f(f(f(x,a),b),c),d) ``` ## Table The table functions should take a function `f`, and a parameter called `iterator` in the form: `{iMin, iMax}` where `iMin` and `iMax` are integers. You should apply `f` over the range specified. Therefore: ``` Table(f, {0, 5}) ``` returns ``` {f(0), f(1), f(2), f(3), f(4), f(5)} ``` --- I've used the definition of these functions from the [Mathematica functional programming page](https://reference.wolfram.com/language/guide/FunctionalProgramming.html), so head there if you need any more guidance. Note that you will not need to implement all the version of the functions shown in that page, but only those written in this post. [Standard Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed as usual. In case your language does not allow functions to be passed as arguments, you need to implement this capability, and add it into your answer. However the byte-count of this operation will not be added to the total. This is code golf so the shortest code wins. Good luck!!! [Answer] # Haskell, ~~many previous byte counts~~ 127 \* 0.9 = 114.3 bytes ``` f#(a:b)=f a:f#b;f#x=x (f&x)0=x;(f&x)i=f$f&x$i-1 i=id r x=i%(1,x) (g?x)(a:b)=g(g?x$b)a;(g?x)y=x f%(a,b)|a>b=[]|1<2=f a:f%(a+1,b) ``` No loops, just recursion. `#` is map: `(*2) # [1,2,3]` -> `[2,4,6]` `&` is nest: `((*2) & 3) 4` -> `48` `i` is apply: `i (*2) 7` -> `14` `r` is range: `r 4` -> `[1,2,3,4]` `?` is fold: `((+) ? 0) [1,2,3,4]` -> `10` `%` is table: `(*2) % (2,4)` -> `[4,6,8]` As requested an ungolfed version with comments. Note, `&` and `?` are ternary infix operators, which require additional parentheses when called or pattern matched. ``` f # (a:b) = f a : f#b -- map on a list (a->head, b->tail) is f a in front of mapping f to b f # x = x -- map on the empty list is the empty list -- (non empty lists are caught in the line before) (f & x) 0 = x -- nesting zero times is x (f & x) i = f $ f&x $ i-1 -- nesting i times is f (nesting one time less) i=id -- apply in Haskell is just the identity function r x = i % (1,x) -- defined via the "table" of the identity function from 1 to x (g ? x) (a:b) = g (g?x$b) a -- folding g into a list (a->head, b->tail) is g applied to (folding g into b) and a (g ? x) y = x -- folding the empty list is x -- again, y must be the empty list, else it would have been handled by the previous line f % (a,b) |a>b = [] -- if iMin is greater than iMax, the table is empty |otherwise = f a : f%(a+1,b) -- otherwise f a in front of the table with iMin increased by one ``` Thanks to @dfeuer and @Zgarb for some useful hints [Answer] # Python 2, 305.1 bytes (-10% ~~376~~ ~~369~~ ~~366~~ ~~349~~ 339 bytes) ``` exec'e=eval;q=len;m=@,l:e("["+"f(l.pop()),"*q(l)+"][::-1]");n=@,x,l:e("f("*l+"*x"+")"*l);r=@:e("r(f-1)+"*(f>1)+"[f]");a=@,a:e("f(a["+`r(q(a))`[1:-1]$",","-1],a[")+"-1])");f=@,x,l:e("f("*q(l)+"x,["+`r(q(l))`[1:-1]$",","-1]),l[")+"-1])");t=@,n,x:e("[f("+`r(x)[n-1:]`$",","),f(")[1:-1]+")]")'.replace("@","lambda f").replace("$",".replace(") ``` When expanded, equivalent to: ``` e=eval;q=len m=lambda f,l:e("["+"f(l.pop()),"*q(l)+"][::-1]") n=lambda f,x,l:e("f("*l+"*x"+")"*l) r=lambda i:e("r(i-1)+"*(i>1)+"[i]") a=lambda f,a:e("f(a["+`r(q(a))`[1:-1].replace(",","-1],a[")+"-1])") f=lambda f,x,l:e("f("*q(l)+"x,["+`r(q(l))`[1:-1].replace(",","-1]),l[")+"-1])") t=lambda f,n,x:e("[f("+`r(x)[n-1:]`.replace(",","),f(")[1:-1]+")]") ``` No loops! Well, it does a lot of `eval`ing and if your boss can't stand loops, then they'll HATE eval. But, they're going to have to put up with it A way to do `range` in a lambda is appreciated so I don't have to do any functions (Shudder.). Explanations: * `m=lambda f,l:eval("["+"f(l.pop()),"*len(l)+"][::-1]")` + Create a string that pops elements from the list, wrap it into a list, reverse it and finally eval it! * `n=lambda f,x,l:eval("f("*l+"*x"+")"*l)` + Manually create the string with the nesting, and eval it! * `r=lambda i:e("r(i-1)+"*(i>1)+"[i]")` + Create a string that when `eval`ed, either returns `[0]` or uses recursion to get the previous results and adds the current index to the list. Evals it. * `a=lambda f,a:eval("f(a["+`r(len(a))`[1:-1].replace(",","-1],a[")+"-1])")` + Uses the range function to get the indexes 1-len(list). Replaces the commas in the list stringified with a way to get the correct index of the list `a`. Evals it! * `f=lambda f,x,l:eval("f("*len(l)+"x,["+`r(len(l))`[1:-1].replace(",","-1]),l[")+"-1])")` + Same as apply except replaces the commas with closing brackets, commas and starting the list index. * `t=lambda f,n,x:eval("[f("+`r(x)[n-1:]`.replace(",","),f(")[1:-1]+")]")` + Same as apply and fold except replaces with ending the function and calling the new one. Evals it! Map, nest, range, apply, fold, table. Thanks @Zgarb for a lambda for range! [Answer] # Javascript ES6, 197 \* 0.9 = 177.3 bytes ``` M=(f,l)=>F((a,b)=>[...a,f(b)],[],l) N=(f,x,n)=>f(--n?N(f,x,n):x) A=(f,l)=>f(...l) R=n=>n--?[...R(n),n+1]:[] F=(f,x,l,n=l.length)=>n--?f(F(f,x,l,n),l[n]):x T=(f,i)=>([n,x]=i,M(q=>f(q+n-1),R(x-n+1))) ``` ### **Map** (`M=(f,l)=>F((a,b)=>[...a,f(b)],[],l)`): Uses **Fold** to concat the results of `f` applied to every member of `l` onto an empty list. Using built-in functions reduces the this to `M=(f,l)=>l.map(f)` (didn't use it because it seems cheap...?). ### **Nest** (`N=(f,x,n)=>f(--n?N(f,x,n):x)`): Apply `f` recursively until `n` is decremented to 0. ### **Apply** (`A=(f,l)=>f(...l)`): Uses the spread (`...`) operator to apply `l` onto `f`. ### **Range** (`R=n=>n--?[...R(n),n+1]:[]`): Concat `n` to recursive call of **Range** until `n` is decremented to 0. ### **Fold** (`F=(f,x,l,n=l.length)=>n--?f(F(f,x,l,n),l[n]):x`): Applies the recursive call of **Fold** and the `n`'th element of `l` to `f` until `n` is decremented to 0. Using built-in functions reduces this to `F=(f,x,l)=>l.reduce(f,x)` (again, seemed cheap...). ### **Table** (`T=(f,i)=>([n,x]=i,M(q=>f(q+n-1),R(x-n+1)))`): First initializes `n` and `x` to iMin and iMax using destructuring (`[n,x]=i`), then uses **Range** to construct the table of values from iMin to iMax. `f` is then applied over the table using **Map** and the result is returned. [Answer] # Python 3, 218 bytes The unreadable version: ``` exec("P!:[f(_)for _ in x];Y!,z:Y(f,f(x),z-1)if z else x;T!:f(*x);H!=0:(H(f-1)if~-f else[])+[f];O!,z:O(f,f(x,z[0]),z[1:])if z else x;N!:(N(f,[x[0],x[1]-1])if x[1]-x[0]else[])+[f(x[1])]".replace("!","=lambda f,x")) ``` The (more) readable version: ``` P=lambda f,x:[f(_)for _ in x] Y=lambda f,x,z:Y(f,f(x),z-1)if z else x T=lambda f,x:f(*x) H=lambda f,x=0:(H(f-1)if~-f else[])+[f] O=lambda f,x,z:O(f,f(x,z[0]),z[1:])if z else x N=lambda f,x:(N(f,[x[0],x[1]-1])if x[1]-x[0]else[])+[f(x[1])] ``` Going though it one lambda at a time: ### Map function `P` `P=lambda f,x:[f(_)for _ in x]` Just a simple iterator. Not much to say here. ### Nest function `Y` `Y=lambda f,x,z:Y(f,f(x),z-1)if z else x` Recursing until `z` hits zero, applying `f` every time. The if clause at the end feels clunky; perhaps there is a better way to end the recursion. ### Apply function `T` `T=lambda f,x:f(*x)` Python has a nice expansion operator to do all of the heavy lifting for me. ### Range function `H` `H=lambda f,x=0:(H(f-1)if~-f else[])+[f]` This one was harder than I was expecting. Ended up taking a recursive approach. Again, the if-else construction takes up a lot of bytes, and I feel it can be improved. Why does it have a dummy `x=0`, you ask? It's so that when I compress it with the `exec`, I can replace `=lambda f,x` instead of just `=lambda f`. ### Fold function `O` `O=lambda f,x,z:O(f,f(x,z[0]),z[1:])if z else x` Pretty happy with this one. Just lops off the first element of the array every time it recurses, until there's nothing left. ### Table function `N` `N=lambda f,x:(N(f,[x[0],x[1]-1])if x[1]-x[0]else[])+[f(x[1])]` This one is horrible and I'm sure there's room for improvement. Tried to use the range and map functions previously defined for a `map(f,range(x,y))` sort of construction, but without much success. Ended up doing a *terrible* recursive approach which shares some similarity to the range function. All the lambdas are wrapped up in an `exec` with a `replace` to shorten the byte count significantly. [Answer] # Julia, 181 bytes No bonus for me; I used loops liberally. Sorry boss, but loops in Julia are efficient! ``` M(f,x)=[f(i...)for i=x] N(f,x,n)=(for i=1:n x=f(x...)end;x) A(f,x)=f(x...) R(n)=(i=0;x={};while i<n push!(x,i+=1)end;x) F(f,x,a)=(for b=a x=f(x,b)end;x) T(f,i)=[f(j)for j=i[1]:i[2]] ``` Adding the ellipses after an argument to a function breaks an array, tuple, or what have you into regular function arguments. Otherwise the function will think you're trying to pass an array (or tuple, etc.). It has no effect for single arguments. Function names: * Map: `M` * Nest: `N` * Apply: `A` * Range: `R` * Fold: `F` * Table: `T` [Answer] ## [tinylisp](https://codegolf.stackexchange.com/q/62886/16766), 325 \* 0.9 = 292.5 The language is newer than the question, but it's not going to win anyway. ``` (d @(q(a a)))(d Q(q((l)(i l(c(@(q q)(h l))(Q(t l)))l))))(d A(q((f a)(v(c(q f)(Q a))))))(d M(q((f l)(i l(c(A f(@(h l)))(M f(t l)))l))))(d N(q((f a x)(i x(A f(@(N f a(s x 1))))a))))(d ,(q((m a b)(i(l b a)m(,(c b m)a(s b 1))))))(d R(q((a)(,()1 a))))(d T(q((f r)(M f(A ,(c()r))))))(d F(q((f a l)(i l(F f(A f(@ a(h l)))(t l))a)))) ``` Defines the functions `A` (apply), `M` (map), `N` (nest), `R` (range), `T` (table), and `F` (fold), along with a couple helper functions. `T` expects a list of two integers for its second argument. Tinylisp doesn't even have any loop constructs; everything is accomplished using recursion. Several of these functions are not [tail-recursive](https://en.wikipedia.org/wiki/Tail_call), so if you call them on large lists they will probably blow the call stack. They could all be implemented with tail recursion... but it would take more bytes, and this is code golf. Here's an expanded version with whitespace and real words for names, which should be pretty readable if you're familiar with Lisp. (I've aliased most of the tinylisp builtins except for `q` (quote) and `i` (if).) ``` (d define d) (define cons c) (define car h) (define cdr t) (define subtract s) (define less l) (define eval v) (define lambda (q (() (arglist expr) (list arglist expr)))) (define list (lambda args args)) (define quote-all (lambda (lyst) (i lyst (cons (list (q q) (car lyst)) (quote-all (cdr lyst))) lyst))) (define Apply (lambda (func arglist) (eval (cons (q func) (quote-all arglist))))) (define Map (lambda (func lyst) (i lyst (cons (Apply func (list (car lyst))) (Map func (cdr lyst))) lyst))) (define Nest (lambda (func arg times) (i times (Apply func (list (Nest func arg (subtract times 1)))) arg))) (define range* (lambda (accumulator a b) (i (less b a) accumulator (range* (cons b accumulator) a (subtract b 1))))) (define Range (lambda (x) (range* 1 x))) (define Table (lambda (func iterator) (Map func (Apply range* (cons () iterator))))) (define Fold (lambda (func arg lyst) (i lyst (Fold func (Apply func (list arg (car lyst))) (cdr lyst)) arg))) ``` Further explanation available upon request. ### Sample output Uses the REPL environment from my reference implementation. I used `q` (quote) for the unary function and `s` (subtract) as the binary function for these examples, as well as the function `@` (defined in this code) which returns a list of its arguments. ``` tl> [line of definitions goes here] @ Q A M N , R T F tl> (A s (@ 10 7)) 3 tl> (M q (@ 1 2 3 4)) ((q 1) (q 2) (q 3) (q 4)) tl> (N q 123 4) (q (q (q (q 123)))) tl> (R 5) (1 2 3 4 5) tl> (T q (@ 3 7)) ((q 3) (q 4) (q 5) (q 6) (q 7)) tl> (F s 10 (@ 4 3 2)) 1 ``` [Answer] # Python 2.x: 450.6 bytes (493 bytes before 10% discount) Golfed answer: ``` y=len z=lambda a,b:a.append(b) _=lambda a:a if a is not None else[] def M(a,b,c=None): c=_(c);d=y(b) if d:z(c,A(a,b[0])) return M(a,b[1:],c)if d else c def N(a,b,c):d=A(a,b);return N(a,d,c-1)if c>1 else d A=lambda a,b:a(*b)if type(b)is list else a(b) def R(a,b=None):b=_(b);b.insert(0,a);return b if a<=1 else R(a-1,b) def F(a,b,c):d=a(b,c[0]);return F(a,d,c[1:])if y(c)>1 else d def T(a,b,c=None,d=None): if c is None:c=b[0];d=[] z(d,a(c));return T(a,b,c+1,d)if c<b[1]else d ``` This question was fun. I decided to write my functions without using the Python equivalents (though that may have been a valid loophole) and to write the functions as though Python supports tail recursion. To make this work, I used a lot of optional parameters that allow the required calls to still work. Below I have ungolfed listings for each function. `Apply`: ``` A = lambda function, arguments: function(*arguments) if type(arguments) is list else function(arguments) ``` `Map`: ``` def M(function, arguments, result=None): result = result if result is not None else [] length = len(arguments) if length != 0: result.append(A(function, arguments[0])) return M(function, arguments[1:], result) if length != 0 else result ``` `Nest`: ``` def N(function, arguments, times): result = A(function, arguments) return N(function, result, times - 1) if times > 1 else result ``` Note that this function requires that the passed `function` be able to represent multiple arguments variably. Another approach would have been to enforce that the function always received a single list, but that would have required that the passed functions be able to interpret argument lists. There were assumptions either way, so I chose the one that fit the rest of the system better. `Range`: ``` def R(ceiling, result=None): result = result if result is not None else [] result.insert(0, ceiling) return result if ceiling <= 1 else R(ceiling - 1, result) ``` `Fold`: ``` def F(function, initial, rest): result = function(initial, rest[0]) return F(function, result, rest[1:] if len(rest) > 1 else result ``` `Table`: ``` def T(function, iterator, current=None, result=None): if current is None: current = iterator[0] result = [] result.append(function(current)) return T(function, iterator, current + 1, result) if current < iterator[1] else result ``` Here is sample output using the following helper functions: ``` square = lambda x: x * x def add(*args): addTwo = lambda a, b: a + b if len(args) == 1 and type(args[0]) is list: return F(addTwo, 0, args[0]) else: return F(addTwo, 0, args) >>> M(square, R(10)) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] >>> M(add, [R(i) for i in R(10)]) [1, 3, 6, 10, 15, 21, 28, 36, 45, 55] >>> T(square, [0, 10]) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100] >>> N(square, 2, 4) 65536 >>> N(lambda *args: F(lambda a, b: a * b, 1, args) if len(args) > 1 else str(args[0]) + 'a', R(5), 10) '120aaaaaaaaa' ``` [Answer] ## Ceylon, ~~370 \* 0.9 = 333~~ 364 \* 0.9 = 327.4 Most of those functions are already available in Ceylon's language package (though sometimes with a bit different signature), but we are defining them here like requested in the question. ``` alias I=>Integer;R[]m<A,R>(R(A)g,A[]l)=>f((R[]x,A y)=>x.append([g(y)]),[],l);A n<A>(A(A)g,A a,I t)=>f((A x,I y)=>g(x),a,r(t));R y<A,R>(Callable<R,A>g,A v)given A satisfies Anything[]=>g(*v);I[]r(I i)=>t((j)=>j,[1,i]);A f<A,O>(A(A,O)g,A a,O[]o)=>if(nonempty o)then f(g,g(a,o[0]),o.rest)else a;R[]t<R>(R(I)g,[I,I]i)=>i[1]<i[0]then[]else[g(i[0]),*t(g,[i[0]+1,i[1]])]; ``` Actually only two of the functions (`t` and `f`) are actually using recursion (over lists and integers, respectively), the other ones are based on these. (Apply is a bit of an outlier, it doesn't really relate to the others.) I interpret "List" as Ceylon's Sequential type, which is an immutable ordered (possibly empty) sequence of elements. `[R*]` stands for `Sequential<R>` – for some reason we can also write it `R[]`, which is one byte shorter. A function type is `Callable<R, A>`, where `A` is a tuple type for the arguments, like `[X, Y, Z]` (i.e. some subtype of `Anything[]`). As a shortcut we can write `R(X,Y,Z)` instead of `Callable<R,[X,Y,Z]>`. I aliased `Integer` as `I` to save some bytes. Here is a formatted (and slightly commented) version: ``` // implement functional paradigms // // Question: http://codegolf.stackexchange.com/q/58588/2338 // My Answer: http://codegolf.stackexchange.com/a/64515/2338 alias I => Integer; // map – based on fold. R[] m<A, R>(R(A) g, A[] l) => f((R[]x,A y) => x.append([g(y)]), [], l); // nest – based on fold + range, throwing away the second // argument in a proxy function. A n<A>(A(A) g, A a, I t) => f((A x, I y) => g(x), a, r(t)); // apply – this looks quite heavy due to type safety. // This uses the "spread operator" *. R y<A, R>(Callable<R,A> g, A v) given A satisfies Anything[] => g(*v); // range – based on table (using the identity function) I[] r(I i) => t((j) => j, [1, i]); // fold – a plain list recursion. A f<A, O>(A(A, O) g, A a, O[] o) => if (nonempty o) then f(g, g(a, o[0]), o.rest) else a; // table – an integer recursion. // (Not sure why the min/max parameters need // to be passed in one argument.) R[] t<R>(R(I) g, [I, I] i) => i[1] < i[0] then [] else [g(i[0]), *t(g, [i[0] + 1, i[1]])]; ``` --- ## Using "loops" Table and Map can be implemented shorter using loops (actually, an sequence comprehension): ``` // map – using a sequence comprehension: R[] m<A, R>(R(A) g, A[] l) => [for(a in l) g(a)]; // table – map with an integer range. // (Not sure why the min/max parameters need // to be passed in one argument.) R[] t<R>(R(I) g, [I, I] i) => m(g, i[0]..i[1]); ``` Though I'm not sure if the use of the [`..` operator](http://ceylon-lang.org/documentation/1.2/reference/operator/spanned-range/) for the integer range counts as using a built-in function. If this is allowed, the resulting code is this here, length 312: ``` alias I=>Integer;R[]m<A,R>(R(A)g,A[]l)=>[for(a in l)g(a)];A n<A>(A(A)g,A a,I t)=>f((A x,I y)=>g(x),a,r(t));R y<A,R>(Callable<R,A>g,A v)given A satisfies Anything[]=>g(*v);I[]r(I i)=>t((j)=>j,[1,i]);A f<A,O>(A(A,O)g,A a,O[]o)=>if(nonempty o)then f(g,g(a,o[0]),o.rest)else a;R[]t<R>(R(I)g,[I,I]i)=>m(g,i[0]..i[1]); ``` (It could be made even shorter by defining `r(I i) => 1..i`, resulting in score 301. Though that looks even more like cheating.) If `..` is not allowed, we'll have to implement it again. We can use these implementations for `r` and `t` (with the `m` above): ``` // range – based two-limit range I[] r(I i) => q(1, i); // two-limit range implemented recursively I[] q(I i, I j) => j < i then [] else [i, *q(i + 1, j)]; // table – map with an integer range. // (Not sure why the min/max parameters need // to be passed in one argument.) R[] t<R>(R(I) g, [I, I] i) => m(g, q(i[0], i[1])); ``` This results in 348 bytes, better than the completely recursive version, but not after applying the bonus. [Answer] # [Scala 3 (compile-time)](https://dotty.epfl.ch/), 403 \* 0.9 = 362.7 bytes This works using compiletime black magic. ``` import compiletime.S type T=Tuple type E=EmptyTuple type^[F[_],X<:T]<:T=X match{case h*:t=>F[h]*:(F^t)case _=>X} type N[F[_],X,T]=T match{case 0=>X case S[t]=>N[F,F[X],t]} type%[F[_],X]=F[X] type>[A<:T,X]=X match{case 0=>A case S[e]=>X*:A>e} type R[X]=E>X type F[G[_,_],X,L]=L match{case h*:t=>F[G,G[X,h],t]case _=>X} type-[F[_],I]<:T=I match{case(b,e)=>S[e]match{case`b`=>E case _=>F[b]*:(F-(S[b],e))}} ``` [Try it in Scastie](https://scastie.scala-lang.org/JAWzU5TISqijL8hRdyTuJg) * `^` is Map. * `N` is Nest. * `%` is Apply. * `R` is Range. * `F` is Fold. * `-` is Table. NB there is a compiler bug so most functions (type constructors) don't work with my implementation of Table, and only the identity function seems to work. The first 3 lines are just so long names aren't repeated. `T` and `E` are typealiases we'll need later, and `S` is a type that gives the successor of a singleton type, e.g. `S[1]` becomes `2`. `S` is extremely useful here, as it can not only add 1, but also subtract 1 using match types. ``` import compiletime.S type T=Tuple type E=EmptyTuple ``` ### Map ``` type ^[F[_], X <: T] <: T = X match { case h *: t => F[h] *: (F ^ t) case _ => E } ``` Here, we declare a type `^` that takes 2 parameters, `F` and `X`. The `[_]` after `F` means that `F` is a type constructor of 1 argument, which we'll treat as a function taking a single parameter. `X <: T` means that `X` is a subtype of `T`, which is an alias for `Tuple`. The second `<: T` means that `^` returns a tuple (this is necessary because `^` is recursive). The body of `^` is a match type. The first case if `X` has at least one element (tuples can be uncons-ed in Scala 3). If so, `X` is destructured into a head `h` and a tail `t`. `F[h]` applies `F` to `h`, and we join that using `*:` to the result of mapping the result of the tuple (`F ^ t` is equivalent to `^[F, t]`). The second case will be reached if `X` is empty, in which case we return `E`, the empty tuple (or rather, the type of an empty tuple). ### Nest ``` type N[F[_], X, T] = T match { case 0 => X case S[t] => N[F, F[X], t] } ``` This is more interesting. Here, `F` is the function to repeatedly apply, `X` is the starting argument, and `T` is how many times to apply `F`. If `T` is 0, we simply return `X`. Otherwise, we see if it is the successor of some type `t`. If `T` is a literal type extending `Int`, `t` will be `T - 1`, so the second case is basically calling `N(F, F(X), T - 1)`. ### Apply ``` type %[F[_], X] = F[X] ``` This is boring. It just takes a function `F` and another argument `X` and applies `F` to `X`. ### Range ``` type >[A <: T, X] = X match { case 0 => A case S[e] => X *: A > e } type R[X] = E > X ``` `R` is the Range function, but `>`, a tail-recursive type, does all the heavy-lifting. `>` takes an accumulator tuple `A` and an integer `X`. When `X` reaches 0, it's time to return the accumulator. Otherwise, we use `S` to find an `e` that is `X - 1`. `X` is prepended to the accumulator and `>` is called again with `e`. `R` just calls `>` with an empty tuple as the accumulator to start it off. ### Fold ``` type F[G[_, _], X, L] = L match{ case h *: t => F[G, G[X, h], t] case _ => X } ``` Here, `G` is a function/type constructor that takes two parameters (like `F[_]` above). `X` is the starting argument, and `L` is the tuple to fold over. If `L` is not empty, the first case will be matched, so we call `F` again with the same function `G`, but with `X` as the result of applying `G` on `X` and the first element of `L`, and with `L` as `L`'s tail. ### Table ``` type -[F[_], I] <: T = I match{ case (b, e) => S[e] match{ case `b` => E case _ => F[b] *: ( F - (S[b],e) ) } } ``` This got a little hairy because of how the second parameter is taken, and it's also affected by a compiler bug (mentioned above). First, we destructure the iterator `I` to get the start and end (here, `b` and `e`). If `b` is greater than `e`, we return an empty tuple (`E`). To test that, we find `e + 1` (`S[e]`) and check if that matches `b`. Otherwise (`case _`), we apply `F` to Imin/`b` and prepend that to the result of calling Table with `b + 1` (`S[b]`) as the new beginning. [Answer] # [Go](https://go.dev), 489 bytes, `int` only ``` func M(f func(int)int,L[]int)(Q[]int){for _,e:=range L{Q=append(Q,f(e))};return} func N(f func(int)int,s,t int)int{if t<1{return s};return f(N(f,s,t-1))} func A(f func(...int)int,L[]int)int{return f(L...)} func R(r int)(O[]int){for i:=1;i<=r;i++{O=append(O,i)};return} func F(f func(int,int)int,x int,o[]int)int{l:=len(o)-1;if len(o)<2{return f(x,o[l])}else{return f(F(f,x,o[:l]),o[l])}} func T(f func(int)int,k...int)(O[]int){if len(k)>1{for i:=k[0];i<=k[1];i++{O=append(O,f(i))}};return} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fVLNasIwHGfXPMUfT8mMYnXCqHbgxZMfU7yJjE4TCa1taSt0lD7FjrvIYG-xJ9kb7C2WpB9KcR5KfiT5ff3Tj8-9f_oO7K1j7xkcbOEhJA6BH8bQhgY_xI2vY8xbjz93v_zobWGKOSiAhRcT-dHJeqMgXuRryv0QXigzrdD2pOIkXVh2EDBvhxeUY0ZINghZfAy9DGnBWV0wojEUOBUc4qGR5gSISipwLGnqZsuQgrnQqBRqt9u1cEqqYk7keclZ4lB74flFemFaxkAMrXAgms10XsafU1HPPr7ITkvPRClS_-zsmpbLPOyTlpTlkONh95wokbfdDcmYG7HzrhSn6sSUR8WFwnZVH5lTVK5qFDYOeTLKSs66s1GtnLWxqRfjWMgxVuXKF3_XbuqfwARSNLUDMC2YohmLYoVmaBQE7puCI7TUzy3hEo19d6fQGK3sV1dvrhB6DmU018NSBuv0CdTeJoF7SDIKukRq0C7t0QfazwipyMr6X3YTDMnuUOhdMHTEnDIpxxTB9V81gqYFrJrDzSS6L-5f7KjaRTbqX0vn5-kq5pmq53R7Kh2qvIq3OZ3y9Q8) Golang is really not designed for concise functional programming. This solution works on `int`s only. # [Go](https://go.dev), 492 bytes, generic ``` func M[I,O any](f func(I)O,L[]I)(Q[]O){for _,e:=range L{Q=append(Q,f(e))};return} func N[I any](f func(I)I,s I,t int)I{if t<1{return s};return f(N(f,s,t-1))} func A[I,O any](f func(...I)O,L[]I)O{return f(L...)} func R(r int)(O[]int){for i:=1;i<=r;i++{O=append(O,i)};return} func F[I any](f func(I,I)I,x I,o[]I)I{l:=len(o)-1;if len(o)<2{return f(x,o[l])}else{return f(F(f,x,o[:l]),o[l])}} func T[K any](f func(int)K,k...int)(O[]K){if len(k)>1{for i:=k[0];i<=k[1];i++{O=append(O,f(i))}};return} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fVLNitswEKZXP8WwJ6mZhHi3C8WJC7kETLJxE3ITpri70mLs2MZ2wIvwk_QSCvsGPfZJ-gx9iEryT3bTdg9C0kjffN83M9--P2ann3l4H4ePHA5hlFpWdMizooIJXIlDdfV8rMT44693v8UxvYc75qEPYfoUEAE6Qjzq45oFHiVbFvhUiqyAL8gdtwhTlXItt26Y5zx9IFsUhFPazApeHYu0sUzGDfMu8nlYgocVRGlFPRkJqOa2bDFQ9mgQZEMElliNbZWzzbX4S91kMhkE-nKArlW8B-1IYaiIzwK9GweR49qzaO4Ws2g0kn5vwcfoUv_yUj9qB7VykGlSTyaOm_CUZHSsMgpoz_Prs5ha_UwC2vCk5OfoUrnTL4566j50jHu2esWoRa8wVpZ6GysqO6aYfrJ7QzGbBtpTzOzg0pYgkariYK1v-g9DqMeCUJDWXZiD46ohUESoVmBteFnp0IaZ6yLPkyd9X5y_7MwcqNjOWmbJgz4t29_78GtiXvbt3fpcqD1JieIhxlptOqNWX5ca3kPdIJhWSRuv8QY_4G1D6QDWkv6LHoGt0FOEmxcIo7qFrPsqljDMwqtpLmHkAh8K9aYS45zcvojoAnTaMPuXuqxVNyDPUFOst6syRc3VNe90avc_) [Answer] # Groovy (146 Bytes) (146\*90%=131.4) *P.S. I don't know what you're considering as a 'loop' in this context, I only applied the bonus after I was told to in the comments by OP and will remove if 2-3 additional users say these collection functions and iterators are loops and that I don't deserve the bonus. Also, if you want to call me out on my use of 1..it, please do so and I will rework it / update my bytecount.* ``` m={f,l->l.collect{f(it)}} // Map n={f,x,n->n.times{x=f(x)};x} // Nest a={f,l->f(l)} // Apply r={1..it} // Range (Is this cheating?) f={f,x,l->l.each{x=f(x,it)};x} // Fold t={f,l->(l[0]..l[1]).collect{f(it)}} // Table ``` ## Example Input/Output ``` f1={2*it} f2={a,b,c,d,e->a*b*c*d*e} f3={a,b->a*b} l=[1,2,3,4,5] l2=[1,9] y=5 x=1 println m(f1,l) println n(f1,x,y) println a(f2,l) println r(y) println f(f3,x,l) println t(f1,l2) ``` ## Output ``` MAP: [2, 4, 6, 8, 10] NEST: 32 APPLY: 120 RANGE: [1, 2, 3, 4, 5] FOLD: 120 TABLE: [2, 4, 6, 8, 10, 12, 14, 16, 18] ``` Try it yourself: <https://groovyconsole.appspot.com/edit/5203951758606336> ]
[Question] [ Inspired by [one of Vi Hart's videos](https://www.youtube.com/watch?v=Gx5D09s5X6U) (which are a treasure trove full of potential challenge ideas) A snake is made up of segments of same length and the connection between each segment can be straight or make a 90° turn. We can encode such a snake (up to a rotation, which depends on the initial direction) by writing down a *slither*, the direction of turns (Straight/Left/Right) it takes. This one, starting in the top left and pointing to the right ``` -+ +--+ SR RSSR | +-+ | S RSL S +--+ --+ LSSL SSR ``` Would be represented by the slither `SRSLSSLRLRSSRSRSS` And of course a planar snake cannot intersect itself (like in `SSSSLLLSS`), that would result in a horrible pixelated Game Over. Your task is to determine whether a slither is valid or not (results in at least one self-intersection) **Input** A string made from letters `SLR` with `2 < length < 10000` **Output** Something Truthy if it is a valid slither and something Falsey if its not. **Test cases** ``` __Valid__ SSLSLSRSRSSRSSSLLSSSRRLRSLRLLSSS SRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR (A hilbert curve) RLLRSRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRR SRRSRSRSSRSSRSSSRSSSRSSSSRSSSSRSSSSSRSSSSSRSSSSSSRSSSSSSRSSSSSS (Spiral) SSSSSSSSSSLSSSSSSSLSSSSSSSSLSSSSSLSSSSSSLSSSLLRRLLRRLLSLSSSRRSSSSRSSSRSSSSSSRSSSSSRSSSSSSSSRSSSSSSSRSSSSSSSSS (bigger, squigglier spiral) LRSLLRLSRSLLSRLSLRSLSSSLRRSSLSRRLRSRLRLSLRLLRLRSSLSLRLRSRSSSSSLSRRLSLSSSRRLRLRLRLRRLLSSLSSSRRLRLRLRLRLSLSSSSSSSSSSSSSRLRLLRLRLRLRLRLRLRLSLSSSLSLSLL __Invalid__ SRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR SRRLSLLRRLLSLRRSRLLRSRRLLSRSSSRSSSSSSSRSRSSSSSSSRRLLRRSRLLRSRRLSLLRRLLSLRR SRRSRSRSSRSSRSSSRSSSRSSSSSSSSSSRSSSSRSSSSSRSSSSSRSSSSSSRSSSSSSRSSSSSS SSSSSSSSSSLSSSSSSSLSSSSSSSSLSSSSSLSSSSSSLSSSLLRRLRLRRLLSLSSSRRSSSSRSSSRSSSSSSRSSSSSRSSSSSSSSRSSSSSSSRSSSSSSSSS LRSLLRLSRSLLSRLSLRSLSSSLRRSSLSRRLRSRLRLSLRLLRLRSSLSLRLRSRSSSSSLSRRLSLSSSRRLRLRLRLRRLLSSLSSSRRLRLRLRLRLSLSSSSSSSSSSSSSRLRLLRLRLRLRLRLRLRLSLSSSLSLSLLSLRLSLRSLRSLRSLSLSLRSRLSLRSLRLSRSLLLRLRLRRRRSLSLSSLLSLSLSLSSLLSLSLLRLRSLLRSRLSLSSLLLLSSSSSSSSSSSSSSSSSSSSRLRLLRRLRLRLLRLRLRLRLRLSSSSLSLRLLRLSLSSLSLSLSLSLRLLRLSLLLSRSSSSSSSSSSSSSSSRLRLRLLRLRLSLSRSRSSSLSRLRLRLRSLSLSLSRLLSRLSLSLSLSLSSLSLSLLSLSRLLRLRLRLRLRLRLRLRLRLRLSLSRLRLSLLRRLSLLSLSLSLSLSLLSLSLSLRLRLRLRLRLRLRLRLRLRRLRSLSLSLSLSLSLSLSSLSSSSSLSLSSSLSLSLSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS ``` You can [draw the slithers here](https://www.khanacademy.org/computer-programming/slither/822941639) (R and L are flipped, but it doesnt affect validity) [Answer] # Pyth, 22 20 bytes ``` ql{m+=Z*=T^.j)hCdzlz ``` [Try it yourself](https://pyth.herokuapp.com/?code=ql%7Bm%2B%3DZ*%3DT%5E.j)hCdzlz&input=SSLSLSRSRSSRSSSLLSSSRRLRSLRLLSSS&debug=0) or run the [testsuite](https://pyth.herokuapp.com/?code=Lql%7Bm%2B%3DZ*%3DT%5E.j)hCdblb%0Ay%22SSLSLSRSRSSRSSSLLSSSRRLRSLRLLSSS%22%0Ay%22SRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR%22%0Ay%22RLLRSRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRR%22%0Ay%22SRRSRSRSSRSSRSSSRSSSRSSSSRSSSSRSSSSSRSSSSSRSSSSSSRSSSSSSRSSSSSS%22%0Ay%22SSSSSSSSSSLSSSSSSSLSSSSSSSSLSSSSSLSSSSSSLSSSLLRRLLRRLLSLSSSRRSSSSRSSSRSSSSSSRSSSSSRSSSSSSSSRSSSSSSSRSSSSSSSSS%22%0Ay%22LRSLLRLSRSLLSRLSLRSLSSSLRRSSLSRRLRSRLRLSLRLLRLRSSLSLRLRSRSSSSSLSRRLSLSSSRRLRLRLRLRRLLSSLSSSRRLRLRLRLRLSLSSSSSSSSSSSSSRLRLLRLRLRLRLRLRLRLSLSSSLSLSLL%22%0Ay%22SRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR%22%0Ay%22SRRLSLLRRLLSLRRSRLLRSRRLLSRSSSRSSSSSSSRSRSSSSSSSRRLLRRSRLLRSRRLSLLRRLLSLRR%22%0Ay%22SRRSRSRSSRSSRSSSRSSSRSSSSSSSSSSRSSSSRSSSSSRSSSSSRSSSSSSRSSSSSSRSSSSSS%22%0Ay%22SSSSSSSSSSLSSSSSSSLSSSSSSSSLSSSSSLSSSSSSLSSSLLRRLRLRRLLSLSSSRRSSSSRSSSRSSSSSSRSSSSSRSSSSSSSSRSSSSSSSRSSSSSSSSS%22%0Ay%22LRSLLRLSRSLLSRLSLRSLSSSLRRSSLSRRLRSRLRLSLRLLRLRSSLSLRLRSRSSSSSLSRRLSLSSSRRLRLRLRLRRLLSSLSSSRRLRLRLRLRLSLSSSSSSSSSSSSSRLRLLRLRLRLRLRLRLRLSLSSSLSLSLLSLRLSLRSLRSLRSLSLSLRSRLSLRSLRLSRSLLLRLRLRRRRSLSLSSLLSLSLSLSSLLSLSLLRLRSLLRSRLSLSSLLLLSSSSSSSSSSSSSSSSSSSSRLRLLRRLRLRLLRLRLRLRLRLSSSSLSLRLLRLSLSSLSLSLSLSLRLLRLSLLLSRSSSSSSSSSSSSSSSRLRLRLLRLRLSLSRSRSSSLSRLRLRLRSLSLSLSRLLSRLSLSLSLSLSSLSLSLLSLSRLLRLRLRLRLRLRLRLRLRLRLSLSRLRLSLLRRLSLLSLSLSLSLSLLSLSLSLRLRLRLRLRLRLRLRLRLRRLRSLSLSLSLSLSLSLSSLSSSSSLSLSSSLSLSLSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS%22&debug=0). Note the ASCII values of SRL, respectively 83, 76, 82. I abuse the fact that: > > *i 83 + 1* = 1 > > *i 76 + 1* = *i* > > *i 82 + 1* = *-i* > > > From here I just keep a variable for the current position and current direction. For every character I multiply the current direction with the above complex number, then add it to the current position. At the end I check if all the visited positions are unique. [Answer] # CJam, 30 bytes ``` q{iF%U+:U[XWe4W1e4]=T+:T}%__&= ``` Explanation to follow soon. [Try it online here](http://cjam.aditsu.net/#code=q%7BiF%25U%2B%3AU%5BXWe4W1e4%5D%3DT%2B%3AT%7D%25__%26%3D&input=SRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR) or [run the whole suite](http://cjam.aditsu.net/#code=11%7B0%3AU%3AT%3Bl_%7BiF%25U%2B%3AU%5BXWe4W1e4%5D%3DT%2B%3AT%7D%25__%26%3D%22%20-%3E%20%22%5CN%7D*&input=SSLSLSRSRSSRSSSLLSSSRRLRSLRLLSSS%0ASRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR%0ARLLRSRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRR%0ASRRSRSRSSRSSRSSSRSSSRSSSSRSSSSRSSSSSRSSSSSRSSSSSSRSSSSSSRSSSSSS%0ASSSSSSSSSSLSSSSSSSLSSSSSSSSLSSSSSLSSSSSSLSSSLLRRLLRRLLSLSSSRRSSSSRSSSRSSSSSSRSSSSSRSSSSSSSSRSSSSSSSRSSSSSSSSS%0ALRSLLRLSRSLLSRLSLRSLSSSLRRSSLSRRLRSRLRLSLRLLRLRSSLSLRLRSRSSSSSLSRRLSLSSSRRLRLRLRLRRLLSSLSSSRRLRLRLRLRLSLSSSSSSSSSSSSSRLRLLRLRLRLRLRLRLRLSLSSSLSLSLL%0ASRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR%0ASRRLSLLRRLLSLRRSRLLRSRRLLSRSSSRSSSSSSSRSRSSSSSSSRRLLRRSRLLRSRRLSLLRRLLSLRR%0ASRRSRSRSSRSSRSSSRSSSRSSSSSSSSSSRSSSSRSSSSSRSSSSSRSSSSSSRSSSSSSRSSSSSS%0ASSSSSSSSSSLSSSSSSSLSSSSSSSSLSSSSSLSSSSSSLSSSLLRRLRLRRLLSLSSSRRSSSSRSSSRSSSSSSRSSSSSRSSSSSSSSRSSSSSSSRSSSSSSSSS%0ALRSLLRLSRSLLSRLSLRSLSSSLRRSSLSRRLRSRLRLSLRLLRLRSSLSLRLRSRSSSSSLSRRLSLSSSRRLRLRLRLRRLLSSLSSSRRLRLRLRLRLSLSSSSSSSSSSSSSRLRLLRLRLRLRLRLRLRLSLSSSLSLSLLSLRLSLRSLRSLRSLSLSLRSRLSLRSLRLSRSLLLRLRLRRRRSLSLSSLLSLSLSLSSLLSLSLLRLRSLLRSRLSLSSLLLLSSSSSSSSSSSSSSSSSSSSRLRLLRRLRLRLLRLRLRLRLRLSSSSLSLRLLRLSLSSLSLSLSLSLRLLRLSLLLSRSSSSSSSSSSSSSSSRLRLRLLRLRLSLSRSRSSSLSRLRLRLRSLSLSLSRLLSRLSLSLSLSLSSLSLSLLSLSRLLRLRLRLRLRLRLRLRLRLRLSLSRLRLSLLRRLSLLSLSLSLSLSLLSLSLSLRLRLRLRLRLRLRLRLRLRRLRSLSLSLSLSLSLSLSSLSSSSSLSLSSSLSLSLSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS). [Answer] # JavaScript (ES6), 84 ~~89~~ Run snippet in Firefox to test. Some notes: * the snake moves inside the f array. Unvisited cells have value `undefined`. On first visit, the tilde operator change it to -1 that is a truthy. Eventually, on a second visit the value change to 0 that is falsy and the `every` loop terminates returning false. * in JS, array elements with non canonic indices (not numeric or negative) are somehow 'hidden', but they do exist. Here I use negative indices with no problem. ``` F=s=>[...s].every(c=>f[p+=[1,1e5,-1,-1e5][d=d+{R:1,L:3,S:0}[c]&3]]=~f[p],d=p=0,f=[]) //TEST $('#S').on('keyup mouseup change', Draw); function Draw(){ var s = S.value.toUpperCase(); if (!s) { C.width = C.height = 0; return } C.width = 600; C.height = 400; var ctx = C.getContext("2d"); var px, py, int=0; ctx.strokeStyle = '#008'; ctx.lineWidth = 2; ctx.translate(300,200); ctx.beginPath(); ctx.moveTo(0,0); [...s].forEach(c=>{ (f[p+=[1,1e4,-1,-1e4][d=d+{R:1,L:3,S:0}[c]&3]]=~f[p]) ? 1 : (++int) if (int==1) ctx.stroke(), ctx.strokeStyle = '#800', ctx.beginPath(), ctx.moveTo(10*px,10*py); py = (p / 1e4 | 0) - 5e3; px = (p % 1e4) -5e3 ctx.lineTo(10*px, 10*py); }, d=0,p=50005000,f=[]); ctx.stroke(); } valid=["SSLSLSRSRSSRSSSLLSSSRRLRSLRLLSSS", "SRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR", "RLLRSRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRR", "SRRSRSRSSRSSRSSSRSSSRSSSSRSSSSRSSSSSRSSSSSRSSSSSSRSSSSSSRSSSSSS", "SSSSSSSSSSLSSSSSSSLSSSSSSSSLSSSSSLSSSSSSLSSSLLRRLLRRLLSLSSSRRSSSSRSSSRSSSSSSRSSSSSRSSSSSSSSRSSSSSSSRSSSSSSSSS", "LRSLLRLSRSLLSRLSLRSLSSSLRRSSLSRRLRSRLRLSLRLLRLRSSLSLRLRSRSSSSSLSRRLSLSSSRRLRLRLRLRRLLSSLSSSRRLRLRLRLRLSLSSSSSSSSSSSSSRLRLLRLRLRLRLRLRLRLSLSSSLSLSLL"]; invalid=["SRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR", "SRRLSLLRRLLSLRRSRLLRSRRLLSRSSSRSSSSSSSRSRSSSSSSSRRLLRRSRLLRSRRLSLLRRLLSLRR", "SRRSRSRSSRSSRSSSRSSSRSSSSSSSSSSRSSSSRSSSSSRSSSSSRSSSSSSRSSSSSSRSSSSSS", "SSSSSSSSSSLSSSSSSSLSSSSSSSSLSSSSSLSSSSSSLSSSLLRRLRLRRLLSLSSSRRSSSSRSSSRSSSSSSRSSSSSRSSSSSSSSRSSSSSSSRSSSSSSSSS", "LRSLLRLSRSLLSRLSLRSLSSSLRRSSLSRRLRSRLRLSLRLLRLRSSLSLRLRSRSSSSSLSRRLSLSSSRRLRLRLRLRRLLSSLSSSRRLRLRLRLRLSLSSSSSSSSSSSSSRLRLLRLRLRLRLRLRLRLSLSSSLSLSLLSLRLSLRSLRSLRSLSLSLRSRLSLRSLRLSRSLLLRLRLRRRRSLSLSSLLSLSLSLSSLLSLSLLRLRSLLRSRLSLSSLLLLSSSSSSSSSSSSSSSSSSSSRLRLLRRLRLRLLRLRLRLRLRLSSSSLSLRLLRLSLSSLSLSLSLSLRLLRLSLLLSRSSSSSSSSSSSSSSSRLRLRLLRLRLSLSRSRSSSLSRLRLRLRSLSLSLSRLLSRLSLSLSLSLSSLSLSLLSLSRLLRLRLRLRLRLRLRLRLRLRLSLSRLRLSLLRRLSLLSLSLSLSLSLLSLSLSLRLRLRLRLRLRLRLRLRLRRLRSLSLSLSLSLSLSLSSLSSSSSLSLSSSLSLSLSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"]; V.innerHTML=valid.map(s=>F(s)+' '+s).join('\n') I.innerHTML=invalid.map(s=>F(s)+' '+s).join('\n') ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Type to check and draw <input id=S> (better full page)<br> <canvas id=C width=1 height=1 ></canvas><br> Valid<pre id=V></pre> Invalid<pre id=I></pre> ``` [Answer] # TI-BASIC, 49 56 53 51 bytes ``` abs(e^(i)-cumSum(i^cumSum(seq(inString("SL",sub(Ans,X,1))-1,X,1,length(Ans→X SortA(∟X min(ΔList(∟X ``` Similar to orlp's method, this creates a list of all points in the complex plane visited by the snake, starting at the origin. If the list has no duplicate elements, the code returns some positive value. Note that on a string of more than 999 elements, the calculator will be unable to generate a sufficiently long list, and will error. EDIT: Saved two bytes at the cost of ugliness as no two lattice points on the complex plane can be the same distance away from e^i. [Answer] # Ruby 87 ~~89~~ ``` F=->s{d=[1,w=1e4,-1,-w] v=[w]+s.chars.map{|c|w+=d.rotate!(c<?R?-1:c>?R?0:1)[0]} v==v&v} ``` Online test: <http://ideone.com/pepeW2> Ungolfed version: ``` F = -> input { # Coordinates are expressed using one number, # that is computed using the formula `y + x*max_x`. # Assume max horizontal field width (max_x) to be 10000, # since that's the max length of the input. position = max_x = 1e4 # These are possible directions to move to (coordinate deltas). # The current direction is always the first in the array. directions = [1,max_x,-1,-max_x] visited = [position] visited += input.chars.map{|c| # adjust current direction... directions.rotate! case c when ?L -1 when ?R 1 when ?S 0 end # ...and move there position += directions[0] } # Return `true` if `visited` only contains distinct elements, `false` otherwise visited == visited & visited } ``` [Answer] # Golfscript 48 ~~49 50~~ ``` [10.4?:z-10z~)]z*z@{'R L S'?@>(@+.`n}%n/@;\;..&= ``` Expects the string to exist on the stack and returns either `0` or `1`. You can try it online with tests for [valid](http://golfscript.apphb.com/?c=ewoKWzEwLjQ%2FOnotMTB6fildeip6QHsnUiBMIFMnP0A%2BKEArLmBufSVuL0A7XDsuLiY9Cgp9OnByb2dyYW07CgoKIyBUZXN0cwojIyMjIyMjCnsgLkAuQD17OzsnT0suJ317J0ZBSUwhIFsnXCsnXSBkb2VzIG5vdCBlcXVhbCBbJytcJ10hJysrfWlmIHB1dHN9OmFzc2VydF9lcXVhbHM7CgojIFZhbGlkIHNuYWtlcwojIyMjIyMjIyMjIyMjIwoKJ1NTTFNMU1JTUlNTUlNTU0xMU1NTUlJMUlNMUkxMU1NTJwpwcm9ncmFtIDEgYXNzZXJ0X2VxdWFscwoKJ1NSUkxTTExSUkxMU0xSUlNSTExSU1JSTExSUlNSTExTU0xMUlNSUkxMUlJTUkxMUlNSUkxTTExSUkxMU0xSUicgIyhBIGhpbGJlcnQgY3VydmUpCnByb2dyYW0gMSBhc3NlcnRfZXF1YWxzCgonUkxMUlNSUkxTTExSUkxMU0xSUlNSTExSU1JSTExSUlNSTExTU0xMUlNSUkxMUlJTUkxMUlNSUkxTTExSUkxMU0xSUlNSTExSU1JSTExSUlNSTExTU0xMUlNSUkxMUlInCnByb2dyYW0gMSBhc3NlcnRfZXF1YWxzCgonU1JSU1JTUlNTUlNTUlNTU1JTU1NSU1NTU1JTU1NTUlNTU1NTUlNTU1NTUlNTU1NTU1JTU1NTU1NSU1NTU1NTJyAjKFNwaXJhbCkKcHJvZ3JhbSAxIGFzc2VydF9lcXVhbHMKCidTU1NTU1NTU1NTTFNTU1NTU1NMU1NTU1NTU1NMU1NTU1NMU1NTU1NTTFNTU0xMUlJMTFJSTExTTFNTU1JSU1NTU1JTU1NSU1NTU1NTUlNTU1NTUlNTU1NTU1NTUlNTU1NTU1NSU1NTU1NTU1NTJyAjKGJpZ2dlciwgc3F1aWdnbGllciBzcGlyYWwpCnByb2dyYW0gMSBhc3NlcnRfZXF1YWxzCgonTFJTTExSTFNSU0xMU1JMU0xSU0xTU1NMUlJTU0xTUlJMUlNSTFJMU0xSTExSTFJTU0xTTFJMUlNSU1NTU1NMU1JSTFNMU1NTUlJMUkxSTFJMUlJMTFNTTFNTU1JSTFJMUkxSTFJMU0xTU1NTU1NTU1NTU1NTUkxSTExSTFJMUkxSTFJMUkxSTFNMU1NTTFNMU0xMJwpwcm9ncmFtIDEgYXNzZXJ0X2VxdWFscwo%3D) and [invalid](http://golfscript.apphb.com/?c=ewoKWzEwLjQ%2FOnotMTB6fildeip6QHsnUiBMIFMnP0A%2BKEArLmBufSVuL0A7XDsuLiY9Cgp9OnByb2dyYW07CgojIFRlc3RzCiMjIyMjIyMKeyAuQC5APXs7OydPSy4nfXsnRkFJTCEgWydcKyddIGRvZXMgbm90IGVxdWFsIFsnK1wnXSEnKyt9aWYgcHV0c306YXNzZXJ0X2VxdWFsczsKCiMgSW52YWxpZCBzbmFrZXMKIyMjIyMjIyMjIyMjIyMjIwoKJ1NSUkxTTExSUkxMU0xSUlNSTExSU1JSTExSUlNSTExMTFJTUlJMTFJSU1JMTFJTUlJMU0xMUlJMTFNMUlInCnByb2dyYW0gMCBhc3NlcnRfZXF1YWxzCgonU1JSTFNMTFJSTExTTFJSU1JMTFJTUlJMTFNSU1NTUlNTU1NTU1NSU1JTU1NTU1NTUlJMTFJSU1JMTFJTUlJMU0xMUlJMTFNMUlInCnByb2dyYW0gMCBhc3NlcnRfZXF1YWxzCgonU1JSU1JTUlNTUlNTUlNTU1JTU1NSU1NTU1NTU1NTU1JTU1NTUlNTU1NTUlNTU1NTUlNTU1NTU1JTU1NTU1NSU1NTU1NTJwpwcm9ncmFtIDAgYXNzZXJ0X2VxdWFscwoKJ1NTU1NTU1NTU1NMU1NTU1NTU0xTU1NTU1NTU0xTU1NTU0xTU1NTU1NMU1NTTExSUkxSTFJSTExTTFNTU1JSU1NTU1JTU1NSU1NTU1NTUlNTU1NTUlNTU1NTU1NTUlNTU1NTU1NSU1NTU1NTU1NTJwpwcm9ncmFtIDAgYXNzZXJ0X2VxdWFscw%3D%3D) snakes. This is basically the same idea as in [my Ruby answer](https://codegolf.stackexchange.com/a/49729/3527). Just the direction array is dealt with differently, because AFAIK Golfscript does not have an arary rotate function. In this case, I build a sufficiently large directions array, by multiplying it 10000 times and then trimming from its start 0, 1, or 3 elements, depending on the current command (S, R, or L). The current "direction" to move to is always the first item in the array. Here it is with comments: ``` # Build the direction array and set current position [1 10000:z-1z~)]z*z @{ # For each character in the input: # set current direction by cutting 0, 1 or 3 elements # from the beginning of the directions array 'SR L'? @> # move to current direction .0=@+. # format as number and addd newline `n }% # split by newlines n/ # cleanup @;\; # return 1 if array contains distinct elements, 0 otherwise ..&= ``` ### Edit: Saved 1 char by modifying how the "directions" array is consumed. ### Edit: saved 1 char by moving increments of 10 instead of 1 to make use of the `?` (power) syntax. ]
[Question] [ Let's define a **grouping** as a flat list, which is either: * just `0` * 2 groupings followed by the literal integer `2` * 3 groupings followed by `3` * 4 groupings followed by `4` * etc. (for all integers \$ \ge 2 \$) Note that `1` is not included in this definition, because otherwise groupings could be infinite. For example, these are valid groupings: * `0` * `0 0 2` * `0 0 0 3` * `0 0 0 2 2` * `0 0 0 0 0 2 3 0 0 0 4 2 0 2` If it helps, here is a more visual representation of the last two groupings above, using parentheses to show how they're constructed: ``` (0 ((0 0) 2) 2) ((0 ((0 0 (0 0 2) 3) 0 0 0 4) 2) 0 2) ``` ## Task Given a positive integer `n`, output all possible **groupings** which contain exactly `n` `0`s. For example, for `n = 3`, there are 3 possible groupings: * `0 0 0 3` * `0 0 0 2 2` * `0 0 2 0 2` ## Rules * Outputs may be in any order, but duplicate outputs are not allowed. * You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447) * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins ## Test cases ``` input -> outputs 1 -> [0] 2 -> [0 0 2] 3 -> [0 0 0 2 2], [0 0 0 3], [0 0 2 0 2] 4 -> [0 0 0 0 2 2 2], [0 0 0 0 2 3], [0 0 0 0 3 2], [0 0 0 0 4], [0 0 0 2 0 2 2], [0 0 0 2 0 3], [0 0 0 2 2 0 2], [0 0 0 3 0 2], [0 0 2 0 0 2 2], [0 0 2 0 0 3], [0 0 2 0 2 0 2] 5 -> [0 0 0 0 0 2 2 2 2], [0 0 0 0 0 2 2 3], [0 0 0 0 0 2 3 2], [0 0 0 0 0 2 4], [0 0 0 0 0 3 2 2], [0 0 0 0 0 3 3], [0 0 0 0 0 4 2], [0 0 0 0 0 5], [0 0 0 0 2 0 2 2 2], [0 0 0 0 2 0 2 3], [0 0 0 0 2 0 3 2], [0 0 0 0 2 0 4], [0 0 0 0 2 2 0 2 2], [0 0 0 0 2 2 0 3], [0 0 0 0 2 2 2 0 2], [0 0 0 0 2 3 0 2], [0 0 0 0 3 0 2 2], [0 0 0 0 3 0 3], [0 0 0 0 3 2 0 2], [0 0 0 0 4 0 2], [0 0 0 2 0 0 2 2 2], [0 0 0 2 0 0 2 3], [0 0 0 2 0 0 3 2], [0 0 0 2 0 0 4], [0 0 0 2 0 2 0 2 2], [0 0 0 2 0 2 0 3], [0 0 0 2 0 2 2 0 2], [0 0 0 2 0 3 0 2], [0 0 0 2 2 0 0 2 2], [0 0 0 2 2 0 0 3], [0 0 0 2 2 0 2 0 2], [0 0 0 3 0 0 2 2], [0 0 0 3 0 0 3], [0 0 0 3 0 2 0 2], [0 0 2 0 0 0 2 2 2], [0 0 2 0 0 0 2 3], [0 0 2 0 0 0 3 2], [0 0 2 0 0 0 4], [0 0 2 0 0 2 0 2 2], [0 0 2 0 0 2 0 3], [0 0 2 0 0 2 2 0 2], [0 0 2 0 0 3 0 2], [0 0 2 0 2 0 0 2 2], [0 0 2 0 2 0 0 3], [0 0 2 0 2 0 2 0 2] 6 -> [0 0 0 0 0 0 2 2 2 2 2], [0 0 0 0 0 0 2 2 2 3], [0 0 0 0 0 0 2 2 3 2], [0 0 0 0 0 0 2 2 4], [0 0 0 0 0 0 2 3 2 2], [0 0 0 0 0 0 2 3 3], [0 0 0 0 0 0 2 4 2], [0 0 0 0 0 0 2 5], [0 0 0 0 0 0 3 2 2 2], [0 0 0 0 0 0 3 2 3], [0 0 0 0 0 0 3 3 2], [0 0 0 0 0 0 3 4], [0 0 0 0 0 0 4 2 2], [0 0 0 0 0 0 4 3], [0 0 0 0 0 0 5 2], [0 0 0 0 0 0 6], [0 0 0 0 0 2 0 2 2 2 2], [0 0 0 0 0 2 0 2 2 3], [0 0 0 0 0 2 0 2 3 2], [0 0 0 0 0 2 0 2 4], [0 0 0 0 0 2 0 3 2 2], [0 0 0 0 0 2 0 3 3], [0 0 0 0 0 2 0 4 2], [0 0 0 0 0 2 0 5], [0 0 0 0 0 2 2 0 2 2 2], [0 0 0 0 0 2 2 0 2 3], [0 0 0 0 0 2 2 0 3 2], [0 0 0 0 0 2 2 0 4], [0 0 0 0 0 2 2 2 0 2 2], [0 0 0 0 0 2 2 2 0 3], [0 0 0 0 0 2 2 2 2 0 2], [0 0 0 0 0 2 2 3 0 2], [0 0 0 0 0 2 3 0 2 2], [0 0 0 0 0 2 3 0 3], [0 0 0 0 0 2 3 2 0 2], [0 0 0 0 0 2 4 0 2], [0 0 0 0 0 3 0 2 2 2], [0 0 0 0 0 3 0 2 3], [0 0 0 0 0 3 0 3 2], [0 0 0 0 0 3 0 4], [0 0 0 0 0 3 2 0 2 2], [0 0 0 0 0 3 2 0 3], [0 0 0 0 0 3 2 2 0 2], [0 0 0 0 0 3 3 0 2], [0 0 0 0 0 4 0 2 2], [0 0 0 0 0 4 0 3], [0 0 0 0 0 4 2 0 2], [0 0 0 0 0 5 0 2], [0 0 0 0 2 0 0 2 2 2 2], [0 0 0 0 2 0 0 2 2 3], [0 0 0 0 2 0 0 2 3 2], [0 0 0 0 2 0 0 2 4], [0 0 0 0 2 0 0 3 2 2], [0 0 0 0 2 0 0 3 3], [0 0 0 0 2 0 0 4 2], [0 0 0 0 2 0 0 5], [0 0 0 0 2 0 2 0 2 2 2], [0 0 0 0 2 0 2 0 2 3], [0 0 0 0 2 0 2 0 3 2], [0 0 0 0 2 0 2 0 4], [0 0 0 0 2 0 2 2 0 2 2], [0 0 0 0 2 0 2 2 0 3], [0 0 0 0 2 0 2 2 2 0 2], [0 0 0 0 2 0 2 3 0 2], [0 0 0 0 2 0 3 0 2 2], [0 0 0 0 2 0 3 0 3], [0 0 0 0 2 0 3 2 0 2], [0 0 0 0 2 0 4 0 2], [0 0 0 0 2 2 0 0 2 2 2], [0 0 0 0 2 2 0 0 2 3], [0 0 0 0 2 2 0 0 3 2], [0 0 0 0 2 2 0 0 4], [0 0 0 0 2 2 0 2 0 2 2], [0 0 0 0 2 2 0 2 0 3], [0 0 0 0 2 2 0 2 2 0 2], [0 0 0 0 2 2 0 3 0 2], [0 0 0 0 2 2 2 0 0 2 2], [0 0 0 0 2 2 2 0 0 3], [0 0 0 0 2 2 2 0 2 0 2], [0 0 0 0 2 3 0 0 2 2], [0 0 0 0 2 3 0 0 3], [0 0 0 0 2 3 0 2 0 2], [0 0 0 0 3 0 0 2 2 2], [0 0 0 0 3 0 0 2 3], [0 0 0 0 3 0 0 3 2], [0 0 0 0 3 0 0 4], [0 0 0 0 3 0 2 0 2 2], [0 0 0 0 3 0 2 0 3], [0 0 0 0 3 0 2 2 0 2], [0 0 0 0 3 0 3 0 2], [0 0 0 0 3 2 0 0 2 2], [0 0 0 0 3 2 0 0 3], [0 0 0 0 3 2 0 2 0 2], [0 0 0 0 4 0 0 2 2], [0 0 0 0 4 0 0 3], [0 0 0 0 4 0 2 0 2], [0 0 0 2 0 0 0 2 2 2 2], [0 0 0 2 0 0 0 2 2 3], [0 0 0 2 0 0 0 2 3 2], [0 0 0 2 0 0 0 2 4], [0 0 0 2 0 0 0 3 2 2], [0 0 0 2 0 0 0 3 3], [0 0 0 2 0 0 0 4 2], [0 0 0 2 0 0 0 5], [0 0 0 2 0 0 2 0 2 2 2], [0 0 0 2 0 0 2 0 2 3], [0 0 0 2 0 0 2 0 3 2], [0 0 0 2 0 0 2 0 4], [0 0 0 2 0 0 2 2 0 2 2], [0 0 0 2 0 0 2 2 0 3], [0 0 0 2 0 0 2 2 2 0 2], [0 0 0 2 0 0 2 3 0 2], [0 0 0 2 0 0 3 0 2 2], [0 0 0 2 0 0 3 0 3], [0 0 0 2 0 0 3 2 0 2], [0 0 0 2 0 0 4 0 2], [0 0 0 2 0 2 0 0 2 2 2], [0 0 0 2 0 2 0 0 2 3], [0 0 0 2 0 2 0 0 3 2], [0 0 0 2 0 2 0 0 4], [0 0 0 2 0 2 0 2 0 2 2], [0 0 0 2 0 2 0 2 0 3], [0 0 0 2 0 2 0 2 2 0 2], [0 0 0 2 0 2 0 3 0 2], [0 0 0 2 0 2 2 0 0 2 2], [0 0 0 2 0 2 2 0 0 3], [0 0 0 2 0 2 2 0 2 0 2], [0 0 0 2 0 3 0 0 2 2], [0 0 0 2 0 3 0 0 3], [0 0 0 2 0 3 0 2 0 2], [0 0 0 2 2 0 0 0 2 2 2], [0 0 0 2 2 0 0 0 2 3], [0 0 0 2 2 0 0 0 3 2], [0 0 0 2 2 0 0 0 4], [0 0 0 2 2 0 0 2 0 2 2], [0 0 0 2 2 0 0 2 0 3], [0 0 0 2 2 0 0 2 2 0 2], [0 0 0 2 2 0 0 3 0 2], [0 0 0 2 2 0 2 0 0 2 2], [0 0 0 2 2 0 2 0 0 3], [0 0 0 2 2 0 2 0 2 0 2], [0 0 0 3 0 0 0 2 2 2], [0 0 0 3 0 0 0 2 3], [0 0 0 3 0 0 0 3 2], [0 0 0 3 0 0 0 4], [0 0 0 3 0 0 2 0 2 2], [0 0 0 3 0 0 2 0 3], [0 0 0 3 0 0 2 2 0 2], [0 0 0 3 0 0 3 0 2], [0 0 0 3 0 2 0 0 2 2], [0 0 0 3 0 2 0 0 3], [0 0 0 3 0 2 0 2 0 2], [0 0 2 0 0 0 0 2 2 2 2], [0 0 2 0 0 0 0 2 2 3], [0 0 2 0 0 0 0 2 3 2], [0 0 2 0 0 0 0 2 4], [0 0 2 0 0 0 0 3 2 2], [0 0 2 0 0 0 0 3 3], [0 0 2 0 0 0 0 4 2], [0 0 2 0 0 0 0 5], [0 0 2 0 0 0 2 0 2 2 2], [0 0 2 0 0 0 2 0 2 3], [0 0 2 0 0 0 2 0 3 2], [0 0 2 0 0 0 2 0 4], [0 0 2 0 0 0 2 2 0 2 2], [0 0 2 0 0 0 2 2 0 3], [0 0 2 0 0 0 2 2 2 0 2], [0 0 2 0 0 0 2 3 0 2], [0 0 2 0 0 0 3 0 2 2], [0 0 2 0 0 0 3 0 3], [0 0 2 0 0 0 3 2 0 2], [0 0 2 0 0 0 4 0 2], [0 0 2 0 0 2 0 0 2 2 2], [0 0 2 0 0 2 0 0 2 3], [0 0 2 0 0 2 0 0 3 2], [0 0 2 0 0 2 0 0 4], [0 0 2 0 0 2 0 2 0 2 2], [0 0 2 0 0 2 0 2 0 3], [0 0 2 0 0 2 0 2 2 0 2], [0 0 2 0 0 2 0 3 0 2], [0 0 2 0 0 2 2 0 0 2 2], [0 0 2 0 0 2 2 0 0 3], [0 0 2 0 0 2 2 0 2 0 2], [0 0 2 0 0 3 0 0 2 2], [0 0 2 0 0 3 0 0 3], [0 0 2 0 0 3 0 2 0 2], [0 0 2 0 2 0 0 0 2 2 2], [0 0 2 0 2 0 0 0 2 3], [0 0 2 0 2 0 0 0 3 2], [0 0 2 0 2 0 0 0 4], [0 0 2 0 2 0 0 2 0 2 2], [0 0 2 0 2 0 0 2 0 3], [0 0 2 0 2 0 0 2 2 0 2], [0 0 2 0 2 0 0 3 0 2], [0 0 2 0 2 0 2 0 0 2 2], [0 0 2 0 2 0 2 0 0 3], [0 0 2 0 2 0 2 0 2 0 2] ``` [Answer] # [Haskell](https://www.haskell.org/), 59 bytes Returns a list of groupings in lexicographic order. ``` (!0) 0!1=[[]] n!s=[k:g|k<-[0^n..s],k/=1,g<-(n-0^k)!(s+1-k)] ``` [Try it online!](https://tio.run/##BcFBDsIgEADAe18BN4hdhIsHU57gC3BrSKNrs5SQrse@vTjzzcLvUjrFZzfa28HrEFNCHKqWmPhOB0@Q/FydExz5GsNIE5gKfmarjVwCsMW@5bWqqLbcHi9l2r7WnyOrUnDuhv1cPiWTdFha@wM "Haskell – Try It Online") The possible groupings can be constructed from left to right if you keep track of two values: the remaining number of `0`s to place, and the number of currently open groupings. When all `0`s are placed and there is a single open grouping, we have constructed a valid output. This is implemented by the function `(!)` which takes the number of `0`s as a left argument `n` and the open groupings as `s`. At each step we can insert a `0` if `n>0` and any integer in `[2..s]` to close multiple open groupings. ``` -- main function: (!) with 0 open groupings (!0) -- base case: no more 0s to place, a single grouping left 0!1=[[]] -- k is the number to insert -- 0^n == if n==0 then 1 else 0 n!s=[k:g|k<-[0^n..s],k/=1,g<-(n-0^k)!(s+1-k)] ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), version 12.3.1, 44 bytes ``` Groupings[#,2~Range~#,Length/@#~Level~All&]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@9@9KL@0IDMvvThaWceoLigxLz21TlnHJzUvvSRD30G5zie1LDWnzjEnRy1W7b9LfnRAUWZeSXSmgq6dQlp0ZmysjkJ1po6CkY6CaW3sfwA "Wolfram Language (Mathematica) – Try It Online") Yes, Mathematica has a built-in for groupings. But the version on TIO (Mathematica 12.0.1) gives the wrong result for input `1`. The version I'm using (Mathematica 12.3.1) works correctly. [Answer] # [JavaScript (V8)](https://v8.dev/), ~~ 77 ~~ 76 bytes Prints all groupings as comma-separated strings. ``` f=(n,s=0,g=0,h=k=>k|n>1?f(k?h(k-1)|n:n+--k,s+[,k+1],g-k):!g&&print(s))=>h(g) ``` [Try it online!](https://tio.run/##JYpBCoMwEEX3PcV0YxImgWZTijZ6EHEhhUQ7MJVE3NSePU3r4vM@vPcctzE94rysZrvl7J1kndxFh7LJkWtp59Z2XlI3STJW7VwzGkM6Ya8J7aCDIVWfQ1UtceZVJqVcO8mgsn9FyeDANsBwd3AtRFTwPgEcreh/XgCWAEEMQjXFecl/Hk25n/wF "JavaScript (V8) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input s = 0, // s = output 'string' (initially the number 0) g = 0, // g = number of groupings - 1 h = k => // h = helper recursive function taking a counter k k | n > 1 ? // if k is not equal to 0 or n is greater than 1: f( // recursive call to f: k ? // if k is not equal to 0: h(k - 1) // do a recursive call to h with k - 1 | n // and pass n unchanged (*) : // else: n + --k, // set k = -1 and decrement n s + [, k + 1], // append a comma followed by k + 1 to s g - k // subtract k from g // (this actually increments g if k = -1) ) // end of recursive call : // else: !g && print(s) // print s if g = 0 ) => h(g) // initial call to h with k = g ``` *(\*) This relies on the fact that `h()` will always eventually return a zero'ish value. And that's why we use `!g && print(s)` rather than `g || print(s)`.* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes ``` Nθ⊞υ⟦⁰⟧FυF⁺…⁰‹№ι⁰θ…·²⁻LιΣι⊞υ⁺ι⟦κ⟧IΦυ⁼⁼№ι⁰θ⁻LιΣι ``` [Try it online!](https://tio.run/##fY4xC8IwEIV3f8WNF4hQBCfHolCoUnQsHWKJbTBNbZLr349n1cXBG@5x8N17r@2Vb0dlUyrcg@KJhqv2OIndqqLQI0mos4av2@gBScCilaWAZ@U6jZmEUoeA@UguopGQCQmT4FW4ljEz6ze4kXA0jv9K7brYo2HkQgMrD3zDFmd2qe@NeHXwhl1zFSIejI3cjJn9RMoG/MhP8L8Udkxpm9azfQI "Charcoal – Try It Online") Link is to verbose version of code. Explanation: A simplification of @ovs's method, where the number of `0`s to place is simply the desired number of `0`s minus the current number of `0`s, and the number of open groupings is the length minus the sum. ``` Nθ ``` Input the desired number of `0`s. ``` ⊞υ⟦⁰⟧Fυ ``` Start a breadth first search with a single `0`. (I can't use an empty list because `Sum([])` isn't `0` in Charcoal.) ``` F⁺…⁰‹№ι⁰θ…·²⁻LιΣι ``` Loop over the concatenation of two ranges, one from `0` to whether more `0`s are needed (so either an empty range or a range containing just `0`), one from `2` to the difference between the length and the sum inclusive. ``` ⊞υ⁺ι⟦κ⟧ ``` Append the value to the grouping and push it to the search list. ``` IΦυ⁼⁼№ι⁰θ⁻LιΣι ``` Output those groupings with one grouping and the correct number of `0`s. [Answer] # [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), 209 + 15 = 224 bytes ``` mod G is inc LIST{Nat}*(op size to{_]). ops({_})([_]): Nat ~> Nat . var A B N :[Nat]. eq{N}=[N]N . eq 0 1 = 0 . eq[0]= nil . eq[s N]= 0[N]. crl A B N => A{A]B s sd(N,{A])if{A]> 1 /\{A]< N /\ A B =[{A B]]. endm ``` To get the list of groupings for \$n\$, run the following Maude command with the \$G\$ module loaded. ``` search{𝑛}=>* A . ``` The groupings will be the listed assignments to \$A\$. So, for example, for \$n = 3\$ run ``` search{3}=>* A . ``` (The bytes of this command — minus the bytes to specify \$n\$ — have been included in the total.) ### Example Session ``` Maude> search{1}=>* A . search in G : {1} =>* A . Solution 1 (state 0) states: 1 rewrites: 4 in 0ms cpu (0ms real) (~ rewrites/second) A --> 0 No more solutions. states: 1 rewrites: 15 in 0ms cpu (0ms real) (~ rewrites/second) Maude> search{2}=>* A . search in G : {2} =>* A . Solution 1 (state 0) states: 1 rewrites: 4 in 0ms cpu (0ms real) (~ rewrites/second) A --> 0 0 2 No more solutions. states: 1 rewrites: 128 in 0ms cpu (0ms real) (~ rewrites/second) Maude> search{3}=>* A . search in G : {3} =>* A . Solution 1 (state 0) states: 1 rewrites: 5 in 0ms cpu (0ms real) (~ rewrites/second) A --> 0 0 0 3 Solution 2 (state 1) states: 2 rewrites: 181 in 0ms cpu (0ms real) (~ rewrites/second) A --> 0 0 2 0 2 Solution 3 (state 2) states: 3 rewrites: 218 in 0ms cpu (0ms real) (~ rewrites/second) A --> 0 0 0 2 2 No more solutions. states: 3 rewrites: 1467 in 1ms cpu (1ms real) (1467000 rewrites/second) Maude> search{4}=>* A . search in G : {4} =>* A . Solution 1 (state 0) states: 1 rewrites: 6 in 0ms cpu (0ms real) (~ rewrites/second) A --> 0 0 0 0 4 -- SNIP -- Solution 11 (state 10) states: 11 rewrites: 4520 in 3ms cpu (3ms real) (1506666 rewrites/second) A --> 0 0 0 0 2 2 2 No more solutions. states: 11 rewrites: 15508 in 12ms cpu (12ms real) (1292333 rewrites/second) Maude> search{5}=>* A . search in G : {5} =>* A . Solution 1 (state 0) states: 1 rewrites: 7 in 0ms cpu (0ms real) (~ rewrites/second) A --> 0 0 0 0 0 5 -- SNIP -- Solution 45 (state 44) states: 45 rewrites: 72386 in 42ms cpu (41ms real) (1723476 rewrites/second) A --> 0 0 0 0 0 2 2 2 2 No more solutions. states: 45 rewrites: 149258 in 59ms cpu (58ms real) (2529796 rewrites/second) Maude> search{6}=>* A . search in G : {6} =>* A . Solution 1 (state 0) states: 1 rewrites: 8 in 0ms cpu (0ms real) (~ rewrites/second) A --> 0 0 0 0 0 0 6 -- SNIP -- Solution 197 (state 196) states: 197 rewrites: 853311 in 216ms cpu (215ms real) (3950513 rewrites/second) A --> 0 0 0 0 0 0 2 2 2 2 2 No more solutions. states: 197 rewrites: 1340298 in 329ms cpu (328ms real) (4073854 rewrites/second) ``` ### Ungolfed ``` mod G is inc LIST{Nat} * (op size to {_]) . ops ({_}) ([_]) : Nat ~> Nat . var A B N : [Nat] . eq {N} = [N] N . eq 0 1 = 0 . eq [0] = nil . eq [s N] = 0 [N] . crl A B N => A {A] B s sd(N, {A]) if {A] > 1 /\ {A] < N /\ A B = [{A B]] . endm ``` This solution uses Maude's rewriting feature, where Maude will search using a rewrite system to find all solutions to an problem of the form \$t\_1 \to\_R^\* t\_2\$, or in this case, \$\{n\} \to\_G^\* A\$, where \$\to\_G^\*\$ means zero or more applications of rules in \$G\$, and \$A\$ is a variable (so essentially *any* term). The single rule picks a run of zeros and groups them, so Maude will explore every way of grouping starting from \$\{n\} \approx\_G 0 \; 0 \, \cdots \, 0 \; n\$. We use odd function names (`{_}`, `[_]`, and `{_]`) to take advantage of Maude's odd tokenization rules. `{_}` creates the initial grouping; `[_]` produces a list of zeroes; `{_]` is the renamed `size` function for lists. [Answer] # [Python](https://www.python.org), 100 bytes ``` f=lambda n:[k+j+R for i in range(1,n)for*j,J in f(i)for k in f(n-i)for R in[[J,2],[J+1]][:i]]or[[0]] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dZjBbtNAEIbvvnNf-RQTt0p31gUFhQfokavxIZAE3KZOlASkCvEkXHqBG0_CE8DT4MRxdnf-30Kl3W_Wv8fj2Zld__i1fTp83jTPzz-_HFZXr_8uVrP1_PHDYm6aafkwvh-_M6vNztSmbsxu3nxajm7yJmvRy_v87ghXo_o4NA_doLnqhu_aYVne5bbKy7vxTVWV07qqNruynFTV-V5_6sftZncw-6d9sjUzs_w6X4_Sb-m4Bdf7w6JurnfL-WKUtb-26_nH5Sg1V29NmqfTMg1g3v4Lx-ZEAvC-acdVi8Zp9T3NkgQe6VU2TYwx213dHEZ1vl42o-ODZfm-dXC56Aaz2Xm0Lesqy0_sTXdJ1j3S878Xv2-OPrZPmdjuDzMxtkrkMmiHLcj7gfR_2m6iCyaepoaTj0DCocRW5wdW38iGN-uUJ5Ej4dBqRy1xtnO4iBw-uxy71UHRSHCWi4Ggkmgdp2cUcbxoECGQFoNp44BeQqZnqcD2EZjAi9NIUE20lqCSi4H190QoGgnOgqQhiQPJQxLI6iTq54CeSiYfWUhIvVj0haIvs-E7QCgaCc5yMVDx8FA0Io7AoqILa2hxnS5ObtUCuywxnfi9QRiGxdZhh5Asug4TXVh8R1hoJNxbYb4K81TQT8cUHeoVOOtWV53BojVQuAaKFylg1tAi1mGiC_E8wkIjWtS8AXRJcesx-EuLnDcQbVLs-pQjmBS9HrMGwSQcQuERERYPYdEQjIXwSAiLg_AoCIuBY6oONR1TLDQKyv-QARodyd8eO4SQvz0muo7NJA15sCnTxjzQnEmDDlYHNxBt2qwvqYqbBKoO-duvfCIB-Ru0ySEDbDAmLCbQ0KPWymbTzQs0M28gMaFNPjTwzREKkYbvsSAECfF3YFgQCpvpNCLR6zFoksgJi5vwqAmLmfCIOSbg8HKHF0fbpCEDbB6hbnjsEApXFqbr2MxCI1I3QgPoQt3wGPwldSM0EG26ASZ1I9gJcsw26UyCbPxp3QgNsGmHrPeYHgSI16RuhFWdOkliMnA4CMobw0Sf1A2PBSFIRKuBG-CwQuJ4SWaEJI5BijI84CQ9YNE4Bq-bYaUvPAQeC0JhM51G8OgegyY8tlz-118q8JE9ZgfEUKJ_UVD_YgMcFlX9C7FDKFxZmK5jMwuNoP7FBtBV9S_E4C_Uv9hAtNXLClsEwcLVhWkLV3YISf2LDXBIV4kbYnrwJ15D_Yu7E3WSf13rf3MD_8CAQlD_QiwIQYLWv9gAHydIHKH-hbUJHCT1L-5o1En6QYXGkdQ_q3_OX6L_Aw) ### How? One big recursive list comprehension. Conceptually: Cut off the tree's lefttmost branch (from the root node) and do recursion on both bits. Technicality: The right bit is the original tree with the left bit removed, while the left bit discards the root branch so as not to violate the no nonbranching nodes requirement. IOW, the left bit hangs one level lower than the right bit. Except when the original tree had only two root branches. Then both hang low. [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 63 bytes ``` (!0) 0!1=[] n!s=anyOf[k:n!(s+1-k)|k<-[2..s]]?n>0&>0:(n-1)!(s+1) ``` [Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z/NVkPRQJPLQNHQNjqWK0@x2DYxr9I/LTrbKk9Ro1jbUDdbsybbRjfaSE@vODbWPs/OQM3OwEojT9dQEyyv@T83MTNPwVYhTcHkPwA "Curry (PAKCS) – Try It Online") Based on [ovs's Haskell answer](https://codegolf.stackexchange.com/a/242785/9288). There are two differences: * The `^` operator is not supported by the Curry version on TIO. * An expression in Curry can be **non-deterministic**, i.e. having multiple values at the same time. Here I define a non-deterministic function `f`, whose return values are all the possible groupings. --- # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 68 bytes ``` (([]:iterate g[0])!!) g a=a++[0,2] g(a++[b])|b>1=g a++[b]?a++[0,b+1] ``` [Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z/NVkMjOtYqsyS1KLEkVSE92iBWU1FRkytdIdE2UVs72kDHKJYrXQPETIrVrEmyM7QFSoF59hD5JG3D2P@5iZl5CrYKaQom/wE "Curry (PAKCS) – Try It Online") Another non-deterministic function that returns all the possible groupings at the same time. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~86~~ 84 bytes ``` f=(n,x=[0],i=0)=>n?x.flatMap((_,j)=>j>i?[]:f(n-!j,[...u=x,j+=!!j],i-j+1)):i-1?[]:[u] ``` [Try it online!](https://tio.run/##ZctBDsIgEIXhvbdgN6RAWnVVM@0JPAEhhtRimBBobGu4PeLWbr//PbIfu05vv2wypudcikOIIqNujfDYchzimJULdrvbBeAhqBINftSmdxAlI6GVUjtmQQ0yRvUmqek4773sfiu9m3I7TSmuKcwqpBc4qPlPzge5HOTKefkC "JavaScript (Node.js) – Try It Online") [Answer] # Python3, 205 bytes: ``` f=lambda x:''.join(f(i)if list==type(i)else'0'for i in x)+str(l:=len(x))*(l>1) def s(n,c=[]): if n: for i in[c+[0],*[[],[[0,c]]][j:=len(c)>1],*[[],[[c,0]]][j]]: yield from s(n-1,i) else:yield f(c) ``` [Try it online!](https://tio.run/##PY9BboQwDEXX5RTeETNpBeqiFVJ6EcsLGpLWKBNQkgWcnga1nZVlff3n5@0o32t8fd/SeXoTpvvnPME@tu3LskpUXgmKhyC5GFOOzdXdhezavvVrAgGJsOMtl6TCaIKLakfsVPgYsJmdh6yitoYYxwYqJ9YB/0WyN@pZd0SsiXptmZnU8ouxWBGP0Or@ChfmCwCHuDCDT@v9OvA8aMEGLq3xL6n18@GXpvjl1KDfqsTTliQWRV2ujzCePw) ]
[Question] [ ## **Concept** In what ways can you scramble the English alphabet so that it can still be sung to the tune Twinkle Twinkle Little Star without ruining the tune? ## **Rules** **Swapping** Let's just assume the letters contained in each of the following sets can be swapped freely by default without ruining the tune: * { A, J, K } * { B, C, D, E, G, P, T, V, Z } * { I, Y } * { Q, U } * { S, X, F } * { M, N } * Therefore H, L, O, R, and W are locked in place **Output** The program needs to output a single RANDOM string (or list of characters) containing the complete English alphabet in any order provided that order satisfies the conditions above. There should be no way for you to predict which string your program will output(if we ignore seeding), meaning you can't just hardcode it. Your program must have some positive probability (not necessarily uniform) of generating each of the \$ 9! \cdot 3! \cdot 3! \cdot 2! \cdot 2! \cdot 2! = 104509440 \$ outputs. There are no particular formatting restrictions regarding spacing, delimiters or case, just be consistent. **Goal** Fewest bytes wins! ## **Examples:** * KCDBPSVHIAJLMNOZQRXGUEWFYT * A,G,Z,V,P,X,C,H,Y,K,J,L,N,M,O,T,U,R,S,D,Q,B,W,F,I,E * KVTDCFBHIJALNMOPURSZQGWXYE * j c d e b x t h i k a l n m o g u r s v q p w f y z * ABCDEFGHIJKLMNOPQRSTUVWXYZ ## **Nonexample:** * HLWROABCDEFZXYGIJKMNPQTSVU ## **Proof of Concept: (Python3, 529 bytes)** ``` import random g1 = ['A', 'J', 'K'] g2 = ['B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z'] g3 = ['I', 'Y'] g4 = ['Q', 'U'] g5 = ['S', 'X', 'F'] g6 = ['M', 'N'] random.shuffle(g1) random.shuffle(g2) random.shuffle(g3) random.shuffle(g4) random.shuffle(g5) random.shuffle(g6) print(g1[0] + g2[0] + g2[1] + g2[2] + g2[3] + g5[0] + g2[4] + 'H' + g3[0] + g1[1] + g1[2] + 'L' + g6[0] + g6[1] + 'O' + g2[5] + g4[0] + 'R' + g5[1] + g2[6] + g4[1] + g2[7] + 'W' + g5[2] + g3[1] + g2[8]) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~140~~ ~~133~~ ~~124~~ 123 bytes ``` d=*map(set,'AJK BCDEGPTVZ IY QU SXF MN H L O R W'.split()), print([d[int(c,16)].pop()for c in'0111141620075581394131a421']) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P8VWKzexQKM4tURH3dHLW8HJ2cXVPSAkLErBM1IhMFQhOMJNwddPwUPBR8FfIUghXF2vuCAns0RDU1OHq6AoM69EIzolGkQl6xiaacbqFeQXaGim5RcpJCtk5qkbGAKBiaGZkYGBuamphaGxpYmhsWGiiZGheqzm//8A "Python 3 – Try It Online") -1 byte, thanks to Jo King --- # [Python 2](https://docs.python.org/2/), ~~174~~ ~~170~~ 158 bytes ``` from random import* s='' for c in'abbbbebHcaaLffObdRebdbWecb':s+=choice(list(set(('AJK BCDEGPTVZ IY QU SXF MN '+c).split()['abcdef'.find(c)])-set(s))) print s ``` [Try it online!](https://tio.run/##Fcy7DsIgFIDhvU9xNkBjB0eTDt7v97vGAQ6QkrTQAItPj/Vf/u1rvrF0tp@S9q4Gz61sZ@rG@djJQkFIpp0HBGMJF21KLJDzjdZ7IU9KSHFXKMggdAssnUFFKxMiDSpSSoarNYzGk@n8cLm9YPmE4xXOjxlsd0C6yPLQVCZS9m5llEqTXBsrKbIP6/2BwBjLGm9shJDSDw "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` A.•¬=©ƶÓÄûkTVã”ØζÞ•Dás#€.rJ‡ ``` Outputs as a single lowercase string. [Try it online](https://tio.run/##ATsAxP9vc2FiaWX//0Eu4oCiwqw9wqnGtsOTw4TDu2tUVsOj4oCdw5jOtsOe4oCiRMOhcyPigqwuckrigKH//w) or [verify \$n\$ random outputs at once](https://tio.run/##AT8AwP9vc2FiaWX/Rv9BLuKAosKsPcKpxrbDk8OEw7trVFbDo@KAncOYzrbDnuKAokTDoXMj4oKsLnJK4oCh/yz/MTA). **Explanation:** ``` A # (a) Push the lowercase alphabet .•¬=©ƶÓÄûkTVã”ØζÞ• # Push compressed string "ajk bcdegptvz iy qu sxf mn" Dá # (b) Duplicate it, and only keep the letters (removing the spaces) s# # Swap to get the string again, and split it by spaces €.r # Shuffle each substring randomly J # (c) Join it back together to a single string ‡ # Transliterate all characters from (b) to (c) in string (a) # (and output the result implicitly) ``` [See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•¬=©ƶÓÄûkTVã”ØζÞ•` is `"ajk bcdegptvz iy qu sxf mn"`. [Answer] # [Ruby](https://www.ruby-lang.org/), 102 bytes ``` s=[*?A..?Z]*'' %w(AJK BCDEGPTVZ IY QU SXF MN).map{|e|a=e.chars.shuffle;s.gsub!(/[#{e}]/){a.pop}} $><<s ``` [Try it online!](https://tio.run/##KypNqvz/v9g2WsveUU/PPipWS12dS7Vcw9HLW8HJ2cXVPSAkLErBM1IhMFQhOMJNwddPUy83saC6JrUm0TZVLzkjsahYrzijNC0tJ9W6WC@9uDRJUUM/Wrk6tTZWX7M6Ua8gv6C2lkvFzsam@P9/AA "Ruby – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~59~~ ~~57~~ 56 bytes ``` hMeD,Vs.SMJc"ajk bcdegptvz iy qu fsx mn h l o r w"dxLGsJ ``` [Try it online!](https://tio.run/##K6gsyfj/vzjDN9VFJ6w4Vy84xStZKTErWyEpOSU1vaCkrEohs1KhsFQhrbhCITdPIUMhRyFfoUihXCklt8I9pdjr/38A "Pyth – Try It Online") Output is an array of lower case letters. ``` hMeD,Vs.SMJc"ajk bcdegptvz iy qu fsx mn h l o r w"dxLGsJ Implicit: d=" ", G=<lowercase alphabet> Jc"ajk bcdegptvz iy qu fsx mn h l o r w"d Chop the grouping string on spaces, store in J sJ Concatenate J into single string xLG Find the index of each letter in grouping string in the unaltered alphabet .SMJ Shuffle each group in J s Concatenate into a single string ,V Pair the shuffled string with their 'correct' positions in the alphabet eD Order the pairs by the derived positions (last element of each pair) hM Keep the letter from each pair (the first element) Implicit print ``` [Answer] # [R](https://www.r-project.org/), ~~93~~ 91 bytes ``` `^`=strsplit L=LETTERS for(s in el('AJK7BCDEGPTVZ7IY7QU7FSX7MN'^7)^'')L[L%in%s]=sample(s) L ``` [Try it online!](https://tio.run/##XVBda8IwFH2/v@LC0CTgnvuyMqZWUetnU1GHosQUwzqVJmODsd/e5daOjeXhJCf33JuTU5TlfrcPrSvsNTcO4jCOpIwWCWSXgls0Z9Q5Z0/DUdDudKP@TC43wWAdzNOgl6yC8YTtArFjTMTPccOcG3Yb2sPrNdfcCojLO1QnrV7QZBijsaguRaGVA7DaWXy4x9xYx0H5F1gL2ZBgxESLbtpEOgRdgoigTzAjkARLgk2tHxBZ12ROJK1Jj0hCsKpvxkQmTICAzHzoI1nxlo4my3gdQOvtXJkjp0IAGDsdkUwu0ugWjnYUT1X/BMRKEN62ZhMPec7tpXD8/WTU6WcqUkjUIzAM8W/9t@IXfMG/cT7fm6Lyu6Xu6gSgDs5/PsFpKmepRC9/RP89ahRQfgM "R – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 76 bytes ``` {my@a='A'..'Z';<AJK BCDEGPTVZ IY QU SXF MN>>>.&{@a[.ords X-65].=pick(*)};@a} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzq30iHRVt1RXU9PPUrd2sbRy1vBydnF1T0gJCxKwTNSITBUITjCTcHXz87OTk@t2iExWi@/KKVYIULXzDRWz7YgMzlbQ0uz1tohsfZ/cWKlQpqGpvV/AA "Perl 6 – Try It Online") Anonymous code block taking no arguments and returning a list of characters. ### Explanation: ``` { } # Anonymous code block my@a='A'..'Z'; # Initialise @a as a list of the alphabet <AJK BCDEGPTVZ IY QU SXF MN> # For each of the sets of letters >>.&{@a[.ords X-65].= } # Set those indexes pick(*) # To a random order ;@a # And return ``` [Answer] # JavaScript - ~~421~~ ~~344~~ ~~328~~ ~~320~~ ~~306~~ ~~280~~ ~~277~~ ~~276~~ ... 176 Bytes -77 Bytes - on my own -18 Byte - thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh) and [@Geza Kerecsenyi](https://codegolf.stackexchange.com/users/85546/geza-kerecsenyi) who made me see what [@tsh](https://codegolf.stackexchange.com/users/44718/tsh) initially pointed out too -8 Bytes - thanks to [@Geza Kerecsenyi](https://codegolf.stackexchange.com/users/85546/geza-kerecsenyi) -14 Bytes - with help of [@Geza Kerecsenyi](https://codegolf.stackexchange.com/users/85546/geza-kerecsenyi) -28 Bytes - on my own -3 Bytes - again with with help of [@Geza Kerecsenyi](https://codegolf.stackexchange.com/users/85546/geza-kerecsenyi) -1 Bytes - how could this happen... **...** -100 Bytes - [@Kaiido](https://codegolf.stackexchange.com/users/64489/kaiido) killed it and via some steps before this whole thing got down to [176 Bytes](https://codegolf.stackexchange.com/questions/188106/do-you-know-your-kvzs/188119#comment450793_188119) ### Golfed: ``` c=[,'AJK','BCDEGPTVZ','IY','QU','SXF','MN'].map(s=>[...s]);alert([...'1222252H311L66O24R5242W532'].reduce((o,v)=>o+(+v?(p=>p.splice((Math.random()*p.length)|0,1))(c[v]):v),"")) ``` or [try it online](https://tio.run/##FYvZDoIwFET/hZf2Sm1CEWM0YNxX3HfCQ1OJYhSagv19rPNwMieTeXHNC6FSWdZ1q6qEHxHUmy8QQf3BcDTZHE4302dXg@3RYH8ZG4YrFNMPl7jwg4hSWsTQkSrNSvw35DATj01dx1k2m2vW2Hmswc6ey8xNJfevSDDOiQY/yG1s6y6WfiBpId/pfwl5@aSKZ/f8g6Em6TvJHuUTiAOARaRjaGsglgVQVT8)! [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 210 bytes ``` >yy `AJK`06B$̤$@ >`BCDEGPTVZ`06B$$$$ $̤$y $ $y @ >̤`IY`06Byyy$yyy̤ @ > ̤`QU`06Byy̤ $y @ > ̤`FSX`06B $yy̤$yy@ >y̤ `MN`06Byyy $@ }}f}l3-[r\ 3-[2'RA?rR1Kl'RAs]{1-:0)?\}l > ̤`HLORW`06Bo$y $y$y$yy@ \~{{B͍ ``` [Try it online!](https://tio.run/##KyrNy0z@/9@uslIhwdHLO8HAzEnlzBIVBy67BCdnF1f3gJCwKLAgECiAZCoVgHSlAlDBmSUJnpEgucrKShUgPrMEJKoAFA4MhQgDRSBKQYJuwREgUaBIJciYSqAwSEGCrx/UDAWgrbW1abU5xrrRRTFcQNJIPcjRvijI0DsHyCiOrTbUtTLQtI@pzYGY6OHjHxQO0pwPclUlCFY6KMTUVVc7ne39/x8A "Runic Enchantments – Try It Online") The randomization is *not uniform* as there isn't a good way to do that in Runic. Instead it randomly rotates each collection of letters (e.g. `[BCDEGPTVZ]` is one grouping) by some amount (e.g. rotating the above set by 4, where the top of the stack is at the right, the result would be `[BCDEGZPTV]`) and then randomly decides whether or not to reverse the stack. It performs these operations 15 times. As a result, all possible orderings are *possible* but not *equally likely.* (In the event that this is not enough, increasing it further [costs zero bytes](https://tio.run/##KyrNy0z@/9@uslIhwdHLO8HAzEnlzBIVBy67BCdnF1f3gJCwKLAgECiAZCoVgHSlAlDBmSUJnpEgucrKShUgPrMEJKoAFA4MhQgDRSBKQYJuwREgUaBIJciYSqAwSEGCrx/UDAWgrbW1aRG1Oca60UUxXLrRRupBjvZFht5BOUBGcWy1oa6VgaZ9DFABxEgPH/@gcJDufJCzKkGw0iGmrrra6Wzv//8A), up to 15000 shuffle loops). This is the section of the code that handles the shuffling: ``` v vvvv Loop counter }}f}l3-[r\ < Loop entry [2'RA?r1KRl'RAs]{1-:0)?\}l3- \~{{B͍ < loop exit ^^^^^^ Randomly reverse ^^^^^ Rotate by a random an amount ``` The rest of the code unrolls into this: ``` ABCDEFGHIJKLMNOPQRSTUVWXYZ > `AJK`08B $ $$; > `BCDEGPTVZ`08B $$$$ $ $ $ $ $; > `IY`08B $ $; > `QU`08B $ $; > `FSX`08B $ $ $; > `MN`08B $$; > `HLORW`08Bo $ $ $ $ $; ^ Create IPs ^^^^^^^^^^^^^^^^ Set letter groupings ^^^ Call shuffle function ^^^^^^^^^^^^^^^^^^^^^^^^^^ Print letters ^ Last letter group needs to be sorted ``` If the letters are left unshuffled (but once-reversed) by changing two bytes the alphabet [is printed normally](https://tio.run/##KyrNy0z@/18BF3B0cnZxdXP38PTy9vH18w8IDAoOCQ0Lj4iM4gJJ20FUJTh6eScYWDhBeCowzSoq1lBVCSBj3ANCwqKQlAEBklowBpPWyEaDTPeMROhCswLGR9ejkBAYiq4J2SZM9W7BEUgaVDBsw9QC1OTrh2GJChazPXz8g8JBKvORPQtFYKNra81qc4x1o4tiUAzTr6uudjrbyxVtpB7kaK9g6B2UA2TUxVYb6loZaNrrg/T8/w8A), which can be used to verify that all letter groupings print in the correct places. The whitespace shifting the `B` commands out of phase is so that all the IPs can use the function loop at the same time without colliding, and then getting them back into phase again. To golf, first any space that could be removed on all lines was trimmed, then each two spaces were converted to a `y`, and every sequence of `yyyy` was converted to `̤` because `̤` and `yyyy` are the same amount of delay, but 2 bytes cheaper. The loop exit was also combined with the `HLORW` main program segment in order to save on the spacing bytes (12 bytes). [Answer] # [Perl 5](https://www.perl.org/), ~~103 91~~ 85 bytes ``` map{my%l;@l{/./g}++;@k{/./g}=keys%l}AJK,BCDEGPTVZ,SXF,IY,QU,MN;say map$k{$_}||$_,A..Z ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saA6t1I1x9ohp1pfTz@9Vlvb2iEbwrTNTq0sVs2pdfTy1nFydnF1DwgJi9IJjnDT8YzUCQzV8fWzLk6sVAAaoZJdrRJfW1OjEq/jqKcX9f//v/yCksz8vOL/ur6megaGBgA "Perl 5 – Try It Online") This code (ab)uses the fact that Perl's output of hash keys (`%l`) is random to create a mapping (`%k`) of all the modifiable letters to one of their possible counterparts. At output time, any key that doesn't exist is assumed to be unchanged. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 34 bytes ``` ØA“wẸXWỵḲ⁻ȦƙṄṇ’œ?µ“ĠQ’ḃ3ÄœṖ⁸Ẋ€Ẏị@Ụ ``` [Try it online!](https://tio.run/##AVcAqP9qZWxsef//w5hB4oCcd@G6uFhX4bu14biy4oG7yKbGmeG5hOG5h@KAmcWTP8K14oCcxKBR4oCZ4biDM8OExZPhuZbigbjhuorigqzhuo7hu4tA4buk//8 "Jelly – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 149 bytes ``` a,b,i,q,s,m,h,l,o,r,w=(set(s)for s in["AJK","BCDEGPTVZ","IY","QU","SXF","MN",*"HLORW"]) print([eval(c).pop()for c in[*"abbbbsbhiaalmmobqrsbqbwsib"]]) ``` [Try it online!](https://tio.run/##Hcy5DoMwEEXRPl@BprLRKE3qFNn3fQ@i8CAiLBlsbBSUr3ecvOLoVdd8mkJXPe8FEkqs0WGJBSrUaLHtM5c3zPGXtpGLZJXAYLkChOFoPJntz9dn@ItH4HAJnO7T4GYLGMN8vTveIOUdY2XVsCR/C8Uy3jXasH8u@@ViEBTmqJBCqLLUVFtHNbVOEqQp9/4L "Python 3 – Try It Online") Randomization by using pop() for letter set [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 55 bytes Full program. Prints uppercase with a leading and trailing space, but no intermediary spaces. ``` {(?⍨∘≢⊇⊢)@(∊∘⍺)⊢⍵}/⌈'AjkBcdegptvzIyQuSxfMn'(⊂⍤⊢,⍨∊⊂⊣)⎕A ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94H@1hv2j3hWPOmY86lz0qKv9UdciTQeNRx1dIJHeXZpA/qPerbX6j3o61B2zsp2SU1LTC0rKqjwrA0uDK9J889Q1HnU1PepdAlSoAzaoC8TvWqz5qG@qI8iK/wUA "APL (Dyalog Extended) – Try It Online") `⎕A` the uppercase alphabet `'AjkBcdegptvzIyQuSxfMn'(`…`)` apply the following anonymous tacit function with that as right argument and the indicated string as left argument: `⊣` for the left argument, `⊂` partition it, beginning a new segment where `∊` the left arguments characters are members of the right argument (i.e. on uppercase letters) `,⍨` append `⊂` enclose (to treat it as a single element) `⍤` the `⊢` right argument `⌈` uppercase everything `{`…`}/` reduce by the following anonymous lambda, giving …`"QU"λ("SXF"λ("MN"λ"A-Z"))`:  `⊢⍵` on the right argument (the scrambling-in-progress alphabet)  `(`…`)@(∊∘⍺)` apply the following anonymous tacit function to the subset that is a member of the left argument (a rhyme group)   `⊢` on that subset   `⊇` reorder it to be   `?⍨` a random permutation   `∘` of length   `≢` tally of letters in the subset [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 43 bytes ``` FαF⪪”&↖(vJf#S»↖ιηa↷N↖⪪νP´↑x‖υ” F№κι‽Φκ¬№KAμ ``` [Try it online!](https://tio.run/##LYtLDoIwGISvMumqTeoJXCGKb6zgC3cN1tjwQ01TvX4Fw2wm881M/dK@dppifDoPrgX@Xr7JBs6SzRazdL5YqtPljnWF4xnlLcM@xwo7HFDgyiQYmBiPqft0gTcStifK2z4Uunu4lmeWgvFDlbsw7pQxTULEhUQrBk1jjJMv/QA "Charcoal – Try It Online") Link is to verbose version of code. Charcoal has no shuffling operators, but I came up with a method of sampling without replacement. Explanation: ``` Fα ``` Loop over each letter of the alphabet. ``` F⪪”&↖(vJf#S»↖ιηa↷N↖⪪νP´↑x‖υ” ``` Split the string `AJK BCDEGPTVZ IY QU SXF MN H L O R W` on spaces and loop over the substrings. ``` F№κι ``` Loop over the number of times the current letter appears in the substring. (I use a loop because a conditional would need an `else` caluse. Alternatively I could have filtered on the substring containing the current letter for the same byte count.) ``` ‽Φκ¬№KAμ ``` Print a random character but exclude ones that have already been printed. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 80 bytes ``` K`1A2B2C2D2E5F2GH3I1J1KL6M6NO2P4QR5S2T4U2VW5X3Y2Z ~(K`123456 . ?O`$&.¶ )`¶$ [blank line] \d [blank line] ``` [Try it online!](https://tio.run/##K0otycxLNPz/3zvB0NHIycjZyMXI1dTNyN3D2NPQy9Dbx8zXzM/fKMAkMMg02CjEJNQoLNw0wjjSKIqrTgOox8jYxNSMS4/L3j9BRU3v0DYuzYRD21S4uGJSNPQ0uVSABgMA "Retina – Try It Online") Probably not the most golfed method, but I'll submit it anyway. **Explanation:** ``` K`1A2B2C2D2E5F2GH3I1J1KL6M6NO2P4QR5S2T4U2VW5X3Y2Z ``` Set the working string to `1A2B2C2D2E5F2GH3I1J1KL6M6NO2P4QR5S2T4U2VW5X3Y2Z`. There is a number before each letter in a group, for example `A`, `J` and `K` all have `1` before them. ``` ~( ``` Mark a section of code that will produce some retina code, then run it afterwards. ``` K`123456 ``` Set the working string to `123456` ``` . ?O`$&.¶ ``` Replace each character with `?O`{character}.¶` ``` )`¶$ [blank line] ``` Remove the trailing newline and finish the group to generate the code. The group will generate the code: ``` ?O`1. ?O`2. ?O`3. ?O`4. ?O`5. ?O`6. ``` `{n}.` matches all instances of number *n* followed by a character. `?O` sorts each instance randomly, and this is done for all character sets. ``` \d [blank line] ``` Finally, remove all numbers and implicitly output the generated string. ]
[Question] [ If you've ever tried adding labels to a really dense plot, then you'll realise that sometimes labels will overlap one another, making them hard to read. We're going to do something similar but in 1D. Input will be a sequence of `(label, x-coordinate)` pairs, and output will be the result of drawing each point and label, in the given order. An asterisk `*` representing the point should be placed at the given x-coordinate and the label should follow. Any existing characters will be overwritten. For instance, if the input was ``` Hello 0 World 8 Fizz 3 Buzz 5 PPCG 16 X 9 ``` Then the following would happen: ``` *Hello *Hello *World *He*Fizz*World *He*F*Buzzorld *He*F*Buzzorld *PPCG *He*F*Buz*Xrld *PPCG ``` The final line should then be outputted. ## I/O rules * Input may consist of any number of pairs. Each label will only consist of uppercase and lowercase letters, and label lengths will be at most 127 chars. Each x-coordinate will be between 0 and 127 inclusive. * Input may be in any convenient list or string format such that the pairs are unambiguous and labels/x-coordinates alternate in the input. For example, a format like `[("Hello", 0), ("World", 8) ...]` or `[0 "Hello" 8 "World" ...]` is fine. However, you may not assume two separate lists of labels and x-coordinates. * Functions and full programs are both okay. * Any spots not covered by a label should be represented with a space. However, there may not be any extraneous leading or trailing whitespace aside from a single optional trailing newline. ## Examples **Input:** ``` OneLabel 10 ``` **Output:** ``` *OneLabel ``` **Input:** ``` Heathrow 0 Edinburgh 2 London 4 Liverpool 6 Oxford 8 ``` **Output:** ``` *H*E*L*L*Oxfordl ``` **Input:** ``` alpha 20 beta 4 gamma 57 delta 3 epsilon 22 zeta 32 eta 53 theta 27 ``` **Output:** ``` *delta *a*epsi*thetazeta *eta*gamma ``` **Input:** ``` abc 5 d 5 abc 10 ABCDEFGHIJKLMNOPQRSTUVWXYZ 127 ``` **Output:** ``` *dbc *abc *ABCDEFGHIJKLMNOPQRSTUVWXYZ ``` Note that labels and/or x-coordinates may be repeated. [Answer] # CJam, ~~24~~ ~~23~~ 19 bytes ``` l~Sf.*'*f*:.{S^+1=} ``` This reads the input as a CJam array of coordinate-label pairs. Try [this fiddle](http://cjam.aditsu.net/#code=l~Sf.*'*f*%3A.%7BS%5E%2B1%3D%7D&input=%5B%5B20%20%22alpha%22%5D%20%5B4%20%22beta%22%5D%20%5B57%20%22gamma%22%5D%20%5B3%20%22delta%22%5D%20%5B22%20%22epsilon%22%5D%20%5B32%20%22zeta%22%5D%20%5B53%20%22eta%22%5D%20%5B27%20%22theta%22%5D%5D) in the CJam interpreter or [verify all test cases at once.](http://cjam.aditsu.net/#code=qN%2F%7B%0A%20%20L~Sf.*'*f*%3A.%7BS%5E%2B1%3D%7D%0AN%7DfL&input=%5B%5B10%20%22OneLabel%22%5D%5D%0A%5B%5B0%20%22Heathrow%22%5D%20%5B2%20%22Edinburgh%22%5D%20%5B4%20%22London%22%5D%20%5B6%20%22Liverpool%22%5D%20%5B8%20%22Oxford%22%5D%5D%0A%5B%5B20%20%22alpha%22%5D%20%5B4%20%22beta%22%5D%20%5B57%20%22gamma%22%5D%20%5B3%20%22delta%22%5D%20%5B22%20%22epsilon%22%5D%20%5B32%20%22zeta%22%5D%20%5B53%20%22eta%22%5D%20%5B27%20%22theta%22%5D%5D%0A%5B%5B5%20%22abc%22%5D%20%5B5%20%22d%22%5D%20%5B10%20%22abc%22%5D%20%5B127%20%22ABCDEFGHIJKLMNOPQRSTUVWXYZ%22%5D%5D) *Thanks to @MartinBüttner for helping me save 4 bytes!* ### How it works ``` l~ Read a line from STDIN and evaluate it. Sf For each pair, push the pair and " "; then: .* Perform vectorized repetition. [X "label"] " " .* -> [(X spaces) "label"] '*f* Join each resulting pair, using '*' as separator. :.{ } Reduce by the following vectorized operator: Push two characters (A and B). S^ Compute the symmetric difference of B and " ". This pushes "B " for a non-space B and "" otherwise. +1= Append and select the second character (with wrap). This selects B for "AB " and A for "A". ``` [Answer] ## Python 2, 67 bytes ``` z='' for a,b in input():z=(z+' '*b)[:b]+'*'+a+z[len(a)-~b:] print z ``` Takes input like `[('Heathrow', 0), ('Edinburgh', 2), ('London', 4), ('Liverpool', 6), ('Oxford', 8)]` and prints the result. Python doesn't allow strings to be modified, and converting to and from a list is expensive. So, this recreates the string `z` to add in a new word. We take the `b` characters before the word, padding with spaces if needed, then the new text with an asterisk, then the part of `z` after the new word. Note that trailing spaces are never added. The `reduce` version is 3 chars longer (70): ``` lambda I:reduce(lambda z,(a,b):(z+' '*b)[:b]+'*'+a+z[len(a)-~b:],I,"") ``` [Answer] # Pyth, 20 bytes ``` V.Tmrj" *"d9Qpe+d-Nd ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?input=%5B0%2C%20%22Hello%22%5D%2C%20%5B8%2C%20%22World%22%5D%2C%20%5B3%2C%20%22Fizz%22%5D%2C%20%5B5%2C%20%22Buzz%22%5D%2C%20%5B16%2C%20%22PPCG%22%5D%2C%20%5B9%2C%20%22X%22%5D%0A%2AHe%2AF%2ABuz%2AXrld%20%20%2APPCG&test_suite_input=%5B%5B0%2C%20%27Hello%27%5D%2C%20%5B8%2C%20%27World%27%5D%2C%20%5B3%2C%20%27Fizz%27%5D%2C%20%5B5%2C%20%27Buzz%27%5D%2C%20%5B16%2C%20%27PPCG%27%5D%2C%20%5B9%2C%20%27X%27%5D%5D%0A%5B%5B10%2C%20%27OneLabel%27%5D%5D%0A%5B%5B0%2C%20%27Heathrow%27%5D%2C%20%5B2%2C%20%27Edinburgh%27%5D%2C%20%5B4%2C%20%27London%27%5D%2C%20%5B6%2C%20%27Liverpool%27%5D%2C%20%5B8%2C%20%27Oxford%27%5D%5D%0A%5B%5B20%2C%20%27alpha%27%5D%2C%20%5B4%2C%20%27beta%27%5D%2C%20%5B57%2C%20%27gamma%27%5D%2C%20%5B3%2C%20%27delta%27%5D%2C%20%5B22%2C%20%27epsilon%27%5D%2C%20%5B32%2C%20%27zeta%27%5D%2C%20%5B53%2C%20%27eta%27%5D%2C%20%5B27%2C%20%27theta%27%5D%5D%0A%5B%5B5%2C%20%27abc%27%5D%2C%20%5B5%2C%20%27d%27%5D%2C%20%5B10%2C%20%27abc%27%5D%2C%20%5B127%2C%20%27ABCDEFGHIJKLMNOPQRSTUVWXYZ%27%5D%5D&code=V.Tmrj%22%20%2A%22d9Qpe%2Bd-Nd&test_suite=0) or [Test Suite](http://pyth.herokuapp.com/?input=%5B0%2C%20%22Hello%22%5D%2C%20%5B8%2C%20%22World%22%5D%2C%20%5B3%2C%20%22Fizz%22%5D%2C%20%5B5%2C%20%22Buzz%22%5D%2C%20%5B16%2C%20%22PPCG%22%5D%2C%20%5B9%2C%20%22X%22%5D%0A%2AHe%2AF%2ABuz%2AXrld%20%20%2APPCG&test_suite_input=%5B%5B0%2C%20%27Hello%27%5D%2C%20%5B8%2C%20%27World%27%5D%2C%20%5B3%2C%20%27Fizz%27%5D%2C%20%5B5%2C%20%27Buzz%27%5D%2C%20%5B16%2C%20%27PPCG%27%5D%2C%20%5B9%2C%20%27X%27%5D%5D%0A%5B%5B10%2C%20%27OneLabel%27%5D%5D%0A%5B%5B0%2C%20%27Heathrow%27%5D%2C%20%5B2%2C%20%27Edinburgh%27%5D%2C%20%5B4%2C%20%27London%27%5D%2C%20%5B6%2C%20%27Liverpool%27%5D%2C%20%5B8%2C%20%27Oxford%27%5D%5D%0A%5B%5B20%2C%20%27alpha%27%5D%2C%20%5B4%2C%20%27beta%27%5D%2C%20%5B57%2C%20%27gamma%27%5D%2C%20%5B3%2C%20%27delta%27%5D%2C%20%5B22%2C%20%27epsilon%27%5D%2C%20%5B32%2C%20%27zeta%27%5D%2C%20%5B53%2C%20%27eta%27%5D%2C%20%5B27%2C%20%27theta%27%5D%5D%0A%5B%5B5%2C%20%27abc%27%5D%2C%20%5B5%2C%20%27d%27%5D%2C%20%5B10%2C%20%27abc%27%5D%2C%20%5B127%2C%20%27ABCDEFGHIJKLMNOPQRSTUVWXYZ%27%5D%5D&code=V.Tmrj%22%20%2A%22d9Qpe%2Bd-Nd&test_suite=1) ### Explanation ``` V.Tmrj" *"d9Qpe+d-Nd m Q map each pair d of the input to: j" *"d join d by the string " *" r 9 range-length encode (this gives x-coordinate spaces, a star and the label) .T transpose this table V for N in ^: -Nd remove spaces from N +d add a space at the beginning e take the last character p and print it (without newline) ``` [Answer] # JavaScript ES6, 104 bytes ``` c=>(a=Array(255).fill(" "))&&c.map(([u,v])=>a.splice(u,v.length+1,..."*"+v))&&a.join``.replace(/ +$/,"") ``` ## Example Usage Input into a compliant console: ``` t = [[0,"Hello"],[8,"World"],[3,"Fizz"],[5,"Buzz"],[16,"PPCG"],[9,"X"]]; (c=>(a=Array(255).fill(" "))&&c.map(([u,v])=>a.splice(u,v.length+1,..."*"+v))&&a.join``.replace(/ +$/,""))(t); ``` Output from the last statement: ``` "*He*F*Buz*Xrld *PPCG" ``` ## Explanation This creates an anonymous function from `c` to three expressions that have been logically-ANDed together. The first two statements are always truthy, and the JS short-circuit rules say that whenever the first is truthy, return the entire value on the right hand side (without coercing to boolean): so this is formally equivalent to ``` (function (c) { a = Array(255).fill(" "); // global variable `a` overwritten c.map(function (x) { // only side-effects are used here. var u = x[0], v = x[1]; // ES6 destructuring a.splice(u, v.length + 1, ..."*" + v)); // main logic }); return a.join("").replace(/ +$/, ""); // postprocessing and trim }) ``` The first statement has to be wrapped in parentheses above because the assignment operator `=` has lower precedence than the logical-AND operator `&&`. The "rest parameter" assembly `..."*"+v` is also part of ES6; it concatenates a leading `*` to the string and then interprets it as a list-like parameter, splitting it into a bunch of arguments which are provided to `Array.prototype.splice`, which takes `(m, n, ...rest)` and modifies its array at position `m` to remove `n` elements and then insert all of the `rest` arguments. To accomplish this before ES6 you would use the more cumbersome: ``` [].slice.apply(a, [u, v.length + 1].concat(("*" + v).split(""))) ``` The array then gets concatenated with the empty string and trailing whitespace is deleted. [Answer] # Ruby, ~~94~~ ~~81~~ 75 bytes Golfed: ``` s=" "*128;$<.map{|l|w,p=l.split;p=p.to_i;s[p..w.size+p]="*"+w};$><<s.rstrip ``` Here's the ungolfed code: ``` s = " "*128 $<.map{|l| # for each line entered via stdin, ctrl+D to stop w,p = l.split # had to move the chomp down here p = p.to_i # there's no 'to_i!'... s[p..w.size+p] = "*"+w # in the range of *foobar, replace the string } $><<s.rstrip # output suggested by w0lf ``` Thanks @w0lf for the suggestions on mapping the input! Thanks @w0lf and @Not that Charles for the thought on removing a variable. [Answer] # Javascript 121 chars Using non-standard features, works on Firefox. `x=Array(255).fill(" ");eval(prompt()).map(s=>{s[0].split``.map((n,i)=>x[s[1]+i+1]=n);x[s[1]]="*"});x=x.join``.trimRight()` Older version: `x=Array(255).fill(" ");eval(prompt()).map(s=>{s[0].split``.map((n,i)=>x[s[1]+i+1]=n);x[s[1]]="*"});x=x.join``.replace(/ +$/,"")` ``` x=Array(255).fill(" "); //Creates an array with spaces eval(prompt()) //Gets some input, has to look like [["Hello",4],["Hi",14],["Oi",0]] .map(s=>{s[0].split``.map((n,i)=>x[s[1]+i+1]=n);x[s[1]]="*"}); //Main "logic" x=x.join``.replace(/ +$/,"") //Gets rid of the trailing spaces ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` 0x;”*;µ/€Ṛo/o⁶ ``` [Try it online!](https://tio.run/##vZHNTsJAEMfP9CmaenJCwpf4EU6CfKhV8BOw6WFLV1qzdEkFRU7qxXcw8Q28auJVn0RepM5u64IePDpNmvz@Ozvz35kLythNFGUnpdntE5TeXzKz@@fPt0ee4bO71@jjYbkbRZaWsqxsWjcamM0NO61b60htHjJXUgGp5k@nEooI5XECuVWkVqtSl7SB0DFsO62llnQDGhRqgKnQwUK6DjJPE81yolszoCZxKFMXdBWgzrS5NzLyQn4tG@VRqLp@4IzDvieVFVRMHrg8kChsmf4VDYecM/Wi5uSch@6CQaiCiV@sJ83yohthQ4@owg4dxVBcQ@qTwYCoubiUJYd54YoOL32WmCgIYaruiuwYtBRmi1IjTwrz94Mspy9MgoAoCTJT1NJ/BaAGsSVpX6yHOD21qniDcuDfck723ixXtqq1emN7Z9fc22@2Dg6Pjk9O253u2c@FgOv00Ab@/jvgD4ua/QU "Jelly – Try It Online") Takes input as a list of pairs `[coordinate, label]`. The last test case does work, TIO simply has wrapping ## How it works ``` 0x;”*;µ/€Ṛo/o⁶ - Main link. Takes a list of pairs I € - Over each pair P in I: µ - Run the following, using: / - C (coord) as the left argument and L (label) as the right: 0x - Repeat 0 C times ;”* - Concatenate "*" ; - Append L Ṛ - Reverse I o/ - Reduce columnwise by logical OR This replaces 0s with the next non-zero element o⁶ - Replace the remaining zeros with spaces ``` [Answer] ## Python, 85 bytes ``` def g(p): z=[' ']*256 for a,b in p:z[b:b+len(a)+1]='*'+a return''.join(z).rstrip() ``` [Try it online](http://ideone.com/5TRBSW) [Answer] ## Perl, 66 bytes **63 bytes script + 3 bytes for `-p`** ``` $}||=$"x128;/\s+/,substr$},$',1+length$`,"*$`"}{$_=$};s/\s+$/ / ``` Nothing too special, utilising the variables `$`` and `$'` which are 'before the match' and 'after the match' respectively, instead of splitting the string. I used a `$}` for the string variable as originally it was saving me a byte, but isn't any more! ### Example run: ``` $perl -p overwritlabels.pl <<< 'Hello 0 World 8 Fizz 3 Buzz 5 PPCG 16 X 9' *He*F*Buz*Xrld *PPCG ``` --- ## Perl, 65 bytes **62 bytes script + 3 bytes for `-p`** Another version that prints out each line (for one less byte!). (Yes, I made this because I didn't read the question properly...) ``` $}||=$"x128;/\s+/;substr$},$',1+length$`,"*$`";$_=$};s/\s+$/ / ``` ### Example run: ``` $perl -p overwritlabels.pl <<< 'Hello 0 World 8 Fizz 3 Buzz 5 PPCG 16 X 9' *Hello *Hello *World *He*Fizz*World *He*F*Buzzorld *He*F*Buzzorld *PPCG *He*F*Buz*Xrld *PPCG ``` [Answer] # PHP -- 84 bytes ``` <? foreach(array_chunk(array_slice($argv,1),2) as $p) echo "␣[".($p[1]+1)."G*$p[0]"; ^ ESC character (\x1b) ``` Uses ANSI escape codes to position the cursor (`\x1b[XG`, featuring the Escape character and X being the 1-based coordinate), followed by the `*` then the input string for that row. Accepts input on the command line of the form: ``` php filename.php Heathrow 0 Edinburgh 2 London 4 Liverpool 6 Oxford 8 php filename.php abc 5 d 5 abc 10 ABCDEFGHIJKLMNOPQRSTUVWXYZ 127 ``` Accepts multi-word entries if they're in quotes, since they're command line arguments. [Answer] # C++11, 95 bytes Why not? As a function, receive input as a `map<int, string>` named `v` containing the position and the string. ``` string t(255,' ');for(auto&m:v){int i=m.first;t[i++]='*';for(auto&c:m.second)t[i++]=c;}cout<<t; ``` Usage ``` #include <iostream> #include <map> using namespace std; int main(){ map<int,string> v{{0,"Heathrow"},{2,"Edinburgh"},{4,"London"},{6,"Liverpool"},{8,"Oxford"}}; string t(255,' ');for(auto&m:v){int i=m.first;t[i++]='*';for(auto&c:m.second)t[i++]=c;}cout<<t; } ``` [Check it Running Here](https://ideone.com/dLZUuw) [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` Fż|mF(J'*eR' ``` [Try it online!](https://tio.run/##yygtzv7/3@3onppcNw0vda3UIHWF////R2sY6Ch5pObk5Ctp6mhY6CiF5xflpIDYxjpKbplVVSCmqY6SUymEaWimoxQQ4OwOYlvqKEUoacYCAA "Husk – Try It Online") Takes a list of pairs (coordinate, label) as input. N.B.: there is a space character at the end of the code. ### Explanation ``` Fż|mF(J'*eR' m For each pair in the input F apply the following function using the pair members as arguments R' Repeat a space (coord) time e put this in a list with the label J'* and join the strings in the list with "*" F Fold over the resulting list ż by zipping strings together (keeping extra characters in the longer string unchanged) | with OR (Second argument if truthy else first. Spaces in Husk are falsy) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 18 bytes ``` rÈh'*+YÎYÌ}Sp#ÿ)x1 ``` [Try it online!](https://tio.run/##y0osKPn/v@hwR4a6lnbk4b7Iwz21wQXKh/drVhj@/x8dreSRmpOTr6RjEKsTrRSeX5SToqRjAWK7ZVZVKekYg5hOpSCmKYgZEODsrqRjaAZiRyjpWMbGAgA "Japt – Try It Online") Takes input as an array of `[label, x-coordinate]` Explanation: ``` rÈh'*+YÎYÌ}Sp#ÿ)x1 # Sp#ÿ # Store 255 spaces as X r } ) # Do this for each pair in order: Èh # Overwrite part of X: YÌ # Starting at index equal to the second item of the pair '* # Write "*" +YÎ # Write the first item of the pair x1 # Remove any remaining whitespace on the right side ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 9 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` H{}0┘*;+╋ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjI4JXVGRjVCJXVGRjVEJXVGRjEwJXUyNTE4KiV1RkYxQiV1RkYwQiV1MjU0Qg__,i=JTVCJTVCJTIySGVsbG8lMjIlMkMwJTVEJTJDJTVCJTIyV29ybGQlMjIlMkM4JTVEJTJDJTVCJTIyRml6eiUyMiUyQzMlNUQlMkMlNUIlMjJCdXp6JTIyJTJDNSU1RCUyQyU1QiUyMlBQQ0clMjIlMkMxNiU1RCUyQyU1QiUyMlglMjIlMkM5JTVEJTVE,v=8) Same as my Stax answer, except canvas is better at grid overlaps. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 29 bytes ``` ~""\{~." "*3$\+<"*"+\+.,@>+}/ ``` [Try it online!](https://tio.run/##HctBDsIgEIXhq5AXV8VUAzbdGOM9gAUqtk2oJZaVxl4dmdl9f2besMTnen9PKZeyAfa7tRBo9M7KMxpIK9v99SJ/h1KMgY9p9BDq6ITBLeTqE3Hw81zd9RSPEOmgySGtU1xedaIoPzzRbGbHX3nkUL1zfw "GolfScript – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~11~~ 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ┤6╧ß╡⌠░$ ``` [Run and debug it](https://staxlang.xyz/#p=b436cfe1b5f4b024&i=%5B%5B0,+%22Hello%22%5D,+%5B8,+%22World%22%5D,+%5B3,+%22Fizz%22%5D,+%5B5,+%22Buzz%22%5D,+%5B16,+%22PPCG%22%5D,+%5B9,+%22X%22%5D%5D%0A%5B%5B10,+%22OneLabel%22%5D%5D%0A%5B%5B0,+%22Heathrow%22%5D,+%5B2,+%22Edinburgh%22%5D,+%5B4,+%22London%22%5D,+%5B6,+%22Liverpool%22%5D,+%5B8,+%22Oxford%22%5D%5D%0A%5B%5B20,+%22alpha%22%5D,+%5B4,+%22beta%22%5D,+%5B57,+%22gamma%22%5D,+%5B3,+%22delta%22%5D,+%5B22,+%22epsilon%22%5D,+%5B32,+%22zeta%22%5D,+%5B53,+%22eta%22%5D,%5B27,+%22theta%22%5D%5D%0A%5B%5B5,+%22abc%22%5D,+%5B5,+%22d%22%5D,+%5B10,+%22abc%22%5D,+%5B127,+%22ABCDEFGHIJKLMNOPQRSTUVWXYZ%22%5D%5D&m=2) Takes input as a list of pairs `[coordinate, label]`. Thanks to caird coinheringaahing for the testcases. ## Explanation ``` zsFE'*s+|% zs push empty list and swap with the input F for each element, E push each item onto stack '*s+ add asterisk to label Stack: [index,label] |% embed in the array ``` ]
[Question] [ [Pyth](https://pyth.herokuapp.com/) is a golfing language based on Python. It uses prefix notation, with each command having a different arity (number of arguments it accepts). Your task is to write a syntax checker for a (non-existent) Pyth-like language, Pith. ## Pith's syntax Pith only has 8 single-char commands: ``` 01234()" ``` `01234` each have arity of the corresponding number, and hence expect that many arguments after it. For example, ``` 400010 ``` is a correct Pith program because `4` is followed by four arguments `0` `0` `0` and `10`, the last of which is a `1` followed by the single argument `0`. To visualise this, we can look at the following tree: ``` R | 4 | ------------- | | | | 0 0 0 1 | 0 ``` where `R` is the root node. An alternative way to think about this is that each number refers to the number of children the corresponding node has in the tree above. Here's another valid Pith program, with more than one base command: ``` 210010 ``` corresponding to ``` R | ------------- | | 2 1 | | --------- 0 | | 1 0 | 0 ``` On the other hand, ``` 3120102100 ``` is *not* a correct Pith program because the initial `3` only has two arguments, which we can see by looking at the tree below: ``` R | 3 | ------------------------ ?? | | 1 2 | | 2 ------ | | | ------ 1 0 | | | 0 1 0 | 0 ``` Next `(` starts an unbounded, and `)` ends an unbounded. An unbounded takes any number of arguments (greedily), and counts as a single argument to any parent command. Any unboundeds still open by the end of the program are automatically closed. A `)` command is not an error if no unboundeds are open — it just does nothing.\* For instance, the Pith program ``` )31(0)0(201000100 ``` corresponds to the tree ``` R | 3 | ------------------------------ | | | 1 0 ( | | ( ----------------------------- | | | | | | 0 2 0 0 1 0 | | ------- 0 | | 0 1 | 0 ``` Empty unboundeds are okay, so `()` is a valid Pith program. An invalid Pith program with an unbounded is ``` 12(010 ``` since the `2` only receives one argument (the unbounded). Finally, `"` starts and ends a string, which is always 0 arity and counts as a single argument, e.g. ``` 2"010""44)()4" ``` which is just a `2` being passed two string arguments `"010"` and `"44)()4"`. Like unboundeds, strings may also be empty, and any unclosed strings by the end of the program are automatically closed. \*This part is different from the original Pyth which actually *does* do something in a case like `1)`, ending the 1-arity and raising an error. ## Input/output Input will be a single non-empty string consisting of only the characters `01234()"`. You may optionally assume that an additional trailing newline is always present. You may write a function or a full program for this challenge. You should output a truthy value if the input is syntactically valid Pith, or a falsy value otherwise. The truthy and falsy values must be fixed, so you can't output `1` for one valid program and `2` for another. ## Scoring This is code-golf, so the code in the fewest bytes wins. ## Test cases Truthy: ``` 0 ) ( " () "" 10 400010 210010 ("")00 3""""" (0)))0)1)0 2(2(2(0)0)0)0 2"010""44)()4" )31(0)0(201000100 ())2)1))0"3())")) 3("4321("301(0)21100"4")"123"00)40"121"31000""01010 ``` Falsy: ``` 1 1(310 (1)0) 12(010 4"00010" 3120102100 20(2((0)(0))) 2(2(2(0)0)0)01) 4(0102)00)00000 2"00"("00"2("")) ``` [Answer] # CJam, 65 bytes ``` q'"/La+2%{0s*}:Z~_,:L')*+{L{4{)_Z+s/Z}/L{'(\Z')++/Z}/}*')-}2*0s-! ``` *Gosh, I wish CJam had Regex, this could have been completed in less than 50 bytes then* The main idea is to keep reducing stuff to `0` i.e. `10` to `0`, `200` to `0` and so on. Once that is done, we reduce all matched brackets to `0`, i.e. `()` to `0`, `(0)` to `0`, `(00)` to `0` and so on. The we repeat the cycle `L` times, where `L` is the input length. The input string initially goes through extra processing where we adjust for unmatched `"` and add lots of `)` to compensate for unmatched `(` This ensures that after all the iterations, we should only have `0` (and no-op `)`) left in the string. *Update - fixed a bug where top level `)` no-op are considered harmful* **Code expansion** ``` q'"/La+2%{0s*}:Z~_,:L')* "Part 1 - Preprocessing"; q'"/ "Read the input and split it on quote"; La+ "Add an extra empty array to the split array to compensate"; "for unmatched ending quote"; 2% "Take every other splitted part, ignoring the contents"; "of the strings in the code"; {0s*}:Z~ "Join the parts by string 0. Also create a function Z"; "that does that for future use. We are now done with"; "reducing "XYZ" to 0 "; _,:L "Store the length of the remaining code in L"; ')* "Append L ) to the string to compensate for unmatched ("; {L{4{)_Z+s/Z}/L{'(\Z')++/Z}/}*')-}2* "Part 2 - the reducing loop"; L{ }* "Run the reduction logic L times"; 4{)_Z+s/Z}/ "Part 2a - reducing arities"; 4{ }/ "Run the iteration for 0, 1, 2 and 3"; )_ "Increment the iteration number and make a copy"; Z+s "Get that many 0 and append it to the number"; /Z "Split the code onto this number and convert it"; "to 0. This successfully reduces 10, 200, "; "3000 and 4000 to 0"; L{'(\Z')++/Z}/ "Part 2b - reducing groups"; L{ }/ "Run the iteration for 0 through L - 1"; '(\Z')++ "Get the string '(<iteration number of 0>)'"; /Z "split on it and join by 0. This successfully"; "reduces (), (0), (00) and so on .. to 0"; ')- "After running the part 2 loop L times, all"; "reducible arities and brackets should be reduced"; "except for cases like '30)00' where the no-op )"; "breaks the flow. So we remove ) from the code"; "and run Part 2 L times again"; 0s-! "Now, if the code was valid, we should only have 0 in the"; "remaining code. If not, the code was invalid"; ``` [Try it online here](http://cjam.aditsu.net/#code=q'%22%2FLa%2B2%25%7B0s*%7D%3AZ~_%2C%3AL')*%2B%7BL%7B4%7B)_Z%2Bs%2FZ%7D%2FL%7B'(%5CZ')%2B%2B%2FZ%7D%2F%7D*')-%7D2*0s-!&input=3(%224321(%22301(0)21100%224%22)%22123%2200)40%22121%2231000%22%2201010) or [run the whole suite](http://cjam.aditsu.net/#code=qN%2F%7B_'%22%2FRa%2B2%25%7B0s*%7D%3AZ~_%2C%3AL')*%2B%7BL%7B4%7B)_Z%2Bs%2FZ%7D%2FL%7B'(%5CZ')%2B%2B%2FZ%7D%2F%7D*')-%7D2*0s-!%22%20-%3E%20%22%5CN%7D%2F&input=0%0A2)00%0A)%0A(%0A%22%0A()%0A%22%22%0A10%0A400010%0A210010%0A(%22%22)00%0A3%22%22%22%22%22%0A2(2(2(0)0)0)0%0A2%22010%22%2244)()4%22%0A)31(0)0(201000100%0A3(%224321(%22301(0)21100%224%22)%22123%2200)40%22121%2231000%22%2201010%0A1%0A1(310%0A12(010%0A4%2200010%22%0A3120102100%0A20(2((0)(0)))%0A2(2(2(0)0)0)01)%0A4(0102)00)00000%0A2%2200%22(%2200%222(%22%22))) [Answer] # Regex, PCRE flavor, 83 bytes ``` ^(?3)*\)*$(()((?(2)|\)*)(\((?1)*(\)|$)|0|"[^"]*.?|(1|(2|(3|4(?3))(?3))(?3))(?3))))? ``` [Try it here.](https://regex101.com/r/vL2eY0/4) # Regex, PCRE flavor, 85 bytes ``` ^((?(3)|\)*)(?>\((?2)*(()(?1))?(\)|$)|0|"[^"]*.?|(1|(2|(3|4(?1))(?1))(?1))(?1)))*\)*$ ``` [Try it here.](https://regex101.com/r/vL2eY0/1) Used some ideas in [this dan1111's answer](https://codegolf.stackexchange.com/a/47571/25180). [Some explanations about `(?2)*(()(?1))?`](https://codegolf.stackexchange.com/a/47826/25180). [Answer] # 80386 Assembler, 97 bytes Hex dump: ``` 0000000: 8b54 2404 5589 e531 c96a ff8a 022c 303c .T$.U..1.j...,0< 0000010: f275 04f6 d530 c084 ed75 263c f875 0141 .u...0...u&<.u.A 0000020: 3cf9 750f 84c9 7419 4958 3c00 7c03 50eb <.u...t.IX<.|.P. 0000030: 2430 c084 c075 0958 483c ff7f 0140 ebf3 $0...u.XH<...@.. 0000040: 5042 8a02 84c0 75c5 4a84 edb0 2275 be84 PB....u.J..."u.. 0000050: c9b0 2975 b85a 31c0 39e5 7501 4089 ec5d ..)u.Z1.9.u.@..] 0000060: c3 . ``` This runs through the input once, pushing numbers greater than zero onto the stack and decrementing them when a zero is processed. Unboundeds are processed as a -1. Function prototype (in C) (function returns 0 if invalid and 1 if valid): ``` int __cdecl test(char *in); ``` Equivalent assembly (NASM): ``` bits 32 ; get input pointer into edx mov edx, [esp+4] ; 8B 54 24 04 ; save ebp; set ebp = esp push ebp ; 55 mov ebp, esp ; 89 E5 ; clear ecx xor ecx, ecx ; 31 C9 ; push base -1 push byte(-1) ; 6A FF ; get top char mov al, [edx] ; 8A 02 sub al, 0x30 ; 2C 30 ; if al == quote cmp al, 0xF2 ; 3C F2 jne $+6 ; 75 04 ; set ch (in quote?) to opposite not ch ; F6 D5 ; set value to 0 xor al, al ; 30 C0 ; if in quote, continue test ch, ch ; 84 ED jnz $+40 ; 75 26 cmp al, 0xF8 ; 3C F8 jne $+3 ; 75 01 ; increment cl=depth inc ecx ; 41 cmp al, 0xF9 ; 3C F9 jne $+17 ; 75 0F ; check depth = 0 test cl, cl ; 84 C9 jz $+27 ; 74 19 ; decrement cl=depth dec ecx ; 49 ; pop and check -1 pop eax ; 58 cmp al, 0 ; 3C 00 jl $+5 ; 7C 03 push eax ; 50 jmp $+38 ; EB 24 xor al, al ; 30 C0 test al, al ; 84 C0 jnz $+11 ; 75 09 pop eax ; 58 dec eax ; 48 cmp al, -1 ; 3C FF jg $+3 ; 7F 01 inc eax ; 40 jmp $-11 ; EB F3 push eax ; 50 inc edx ; 42 mov al, [edx] ; 8A 02 test al, al ; 84 C0 jnz $-57 ; 75 C5 dec edx ; 4A ; in quote? test ch, ch ; 84 ED mov al, 0x22 ; B0 22 jnz $-64 ; 75 BE ; depth not zero? test cl, cl ; 84 C9 mov al, 0x29 ; B0 29 jnz $-70 ; 75 B8 ; pop base -1 pop edx ; 5A ; set return value based on ebp/esp comparison xor eax, eax ; 31 C0 cmp ebp, esp ; 39 E5 jne $+3 ; 75 01 inc eax ; 40 ; restore esp mov esp, ebp ; 89 EC ; restore ebp pop ebp ; 5D ; return ret ; C3 ``` The following code in C can be used with GCC on a POSIX system to test: ``` #include <sys/mman.h> #include <stdio.h> #include <string.h> int main(){ char code[] = { 0x8b, 0x54, 0x24, 0x04, 0x55, 0x89, 0xe5, 0x31, 0xc9, 0x6a, 0xff, 0x8a, 0x02, 0x2c, 0x30, 0x3c, 0xf2, 0x75, 0x04, 0xf6, 0xd5, 0x30, 0xc0, 0x84, 0xed, 0x75, 0x26, 0x3c, 0xf8, 0x75, 0x01, 0x41, 0x3c, 0xf9, 0x75, 0x0f, 0x84, 0xc9, 0x74, 0x19, 0x49, 0x58, 0x3c, 0x00, 0x7c, 0x03, 0x50, 0xeb, 0x24, 0x30, 0xc0, 0x84, 0xc0, 0x75, 0x09, 0x58, 0x48, 0x3c, 0xff, 0x7f, 0x01, 0x40, 0xeb, 0xf3, 0x50, 0x42, 0x8a, 0x02, 0x84, 0xc0, 0x75, 0xc5, 0x4a, 0x84, 0xed, 0xb0, 0x22, 0x75, 0xbe, 0x84, 0xc9, 0xb0, 0x29, 0x75, 0xb8, 0x5a, 0x31, 0xc0, 0x39, 0xe5, 0x75, 0x01, 0x40, 0x89, 0xec, 0x5d, 0xc3, }; void *mem = mmap(0, sizeof(code), PROT_WRITE|PROT_EXEC, MAP_ANON|MAP_PRIVATE, -1, 0); memcpy(mem, code, sizeof(code)); int __cdecl (*test)(char *) = (int __cdecl (*)(char *)) mem; #define TRY(s) printf(s ": %d\n", test(s)) printf("Truthy tests:\n"); TRY("0"); TRY(")"); TRY("("); TRY("\""); TRY("()"); TRY("\"\""); TRY("10"); TRY("400010"); TRY("210010"); TRY("(\"\")00"); TRY("3\"\"\"\"\""); TRY("(0)))0)1)0"); TRY("2(2(2(0)0)0)0"); TRY("2\"010\"\"44)()4\""); TRY(")31(0)0(201000100"); TRY("())2)1))0\"3())\"))"); TRY("3(\"4321(\"301(0)21100\"4\")\"123\"00)40\"121\"31000\"\"01010"); printf("\nFalsy tests:\n"); TRY("1"); TRY("1(310"); TRY("(1)0)"); TRY("12(010"); TRY("4\"00010\""); TRY("3120102100"); TRY("20(2((0)(0)))"); TRY("2(2(2(0)0)0)01)"); TRY("4(0102)00)00000"); TRY("2\"00\"(\"00\"2(\"\"))"); munmap(mem, sizeof(code)); return 0; } ``` [Answer] # lex, 182 bytes (157 w/ fixed-size stack) These programs require the input to be a single new-line terminated string of valid characters. ``` %% int n=0,s=0,*t=0; [0-4] n+=*yytext-48-!!n; \( (t=realloc(t,(s+1)*sizeof n))[s++]=n-!!n;n=0; \) if(s&&n)exit(1);s&&(n=t[--s]); \"[^"]*.? n-=!!n; \n while(s)t[--s]&&n++;exit(!!n); ``` The above program will segfault if it runs out of memory, which could theoretically happen if you give it enough `(`. But since a segfault counts as failure, I'm taking that as "falsey", although the problem description doesn't say what to do if resources don't suffice. I cut it down 157 bytes by just using a fixed-size stack, but that seemed like cheating. ``` %% int n=0,s=0,t[9999]; [0-4] n+=*yytext-48-!!n; \( t[s++]=n-!!n;n=0; \) if(s&&n)exit(1);s&&(n=t[--s]); \"[^"]*.? n-=!!n; \n while(s)t[--s]&&n++;exit(!!n); ``` To compile: ``` flex -o pith.c pith.l # pith.l is the above file c99 -o pith pith.c -lfl ``` Test: ``` while IFS= read -r test; do printf %-78s "$test" if ./pith <<<"$test"; then echo "OK"; else echo "NO"; fi done <<EOT 0 ) ( " () "" 10 400010 210010 ("")00 3""""" 2(2(2(0)0)0)0 2"010""44)()4" )31(0)0(201000100 3("4321("301(0)21100"4")"123"00)40"121"31000""01010 1 1(310 12(010 4"00010" 3120102100 20(2((0)(0))) 2(2(2(0)0)0)01) 4(0102)00)00000 2"00"("00"2("")) EOT ``` Test output: ``` 0 OK ) OK ( OK " OK () OK "" OK 10 OK 400010 OK 210010 OK ("")00 OK 3""""" OK 2(2(2(0)0)0)0 OK 2"010""44)()4" OK )31(0)0(201000100 OK 3("4321("301(0)21100"4")"123"00)40"121"31000""01010 OK 1 NO 1(310 NO 12(010 NO 4"00010" NO 3120102100 NO 20(2((0)(0))) NO 2(2(2(0)0)0)01) NO 4(0102)00)00000 NO 2"00"("00"2("")) NO ``` [Answer] # Python 2, 353 bytes The parse function steps through the tokens one at a time and builds a tree of the program structure. Invalid programs trigger an exception which causes a zero (Falsy) to be printed, otherwise successful parsing results in a one. ``` def h(f,k=0): b=[] if k: while f:b+=[h(f)] return b q=f.pop(0) if q==')':return[] elif q=='"': while f: q+=f.pop(0) if q[-1]=='"':break elif q=='(': while f: if f and f[0]==')':f.pop(0);break b+=h(f) else: for i in range(int(q)):b+=h(f) assert len(b)==int(q) return[[q,b]] try:h(list(raw_input()));r=1 except:r=0 print r ``` The output of the tests showing the parser output: ``` ------------------------------------------------------------ True: 0 0 ------------------------------------------------------------ True: ) ------------------------------------------------------------ True: ( ( ------------------------------------------------------------ True: " " ------------------------------------------------------------ True: () ( ------------------------------------------------------------ True: "" "" ------------------------------------------------------------ True: 10 1 0 ------------------------------------------------------------ True: 400010 4 0 0 0 1 0 ------------------------------------------------------------ True: 210010 2 1 0 0 1 0 ------------------------------------------------------------ True: ("")00 ( "" 0 0 ------------------------------------------------------------ True: 3""""" 3 "" "" " ------------------------------------------------------------ True: 2(2(2(0)0)0)0 2 ( 2 ( 2 ( 0 0 0 0 ------------------------------------------------------------ True: 2"010""44)()4" 2 "010" "44)()4" ------------------------------------------------------------ True: )31(0)0(201000100 3 1 ( 0 0 ( 2 0 1 0 0 0 1 0 0 ------------------------------------------------------------ True: 3("4321("301(0)21100"4")"123"00)40"121"31000""01010 3 ( "4321(" 3 0 1 ( 0 2 1 1 0 0 "4" "123" 0 0 4 0 "121" 3 1 0 0 0 "" 0 1 0 1 0 ------------------------------------------------------------ False: 1 0 ------------------------------------------------------------ False: 1(310 0 ------------------------------------------------------------ False: 12(010 0 ------------------------------------------------------------ False: 4"00010" 0 ------------------------------------------------------------ False: 3120102100 0 ------------------------------------------------------------ False: 20(2((0)(0))) 0 ------------------------------------------------------------ False: 2(2(2(0)0)0)01) 0 ------------------------------------------------------------ False: 4(0102)00)00000 0 ------------------------------------------------------------ False: 2"00"("00"2("")) 0 ``` The code before the minifier: ``` def parse(tokens, first=False): toklist = [] if first: while tokens : toklist += [parse(tokens)] return toklist tok = tokens.pop(0) if tok == ')' : return [] elif tok == '"': while tokens: tok += tokens.pop(0) if tok[-1] == '"' : break elif tok == '(': while tokens: if tokens and tokens[0] == ')' : tokens.pop(0); break toklist += parse(tokens) else: for i in range(int(tok)) : toklist += parse(tokens) assert len(toklist) == int(tok) return [[tok, toklist]] try : parse(list(raw_input())); r = 1 except : r = 0 print r ``` [Answer] # [Pip](http://github.com/dloscutoff/pip), ~~88~~ 72 bytes Idea taken from [Optimizer's CJam](https://codegolf.stackexchange.com/a/47809/16766). My original stab at the problem with a recursive descent parser was... rather longer. ``` Qpz:,5.iX,5AL'(.0X,#p.')p^:'"Fj,#pIj%2p@j:0p:Jpp.:')X#pL#ppR:z0!pRM')Rz0 ``` Formatted, with explanation: ``` Qp Query user for p z: Store the following list in z: ,5 . 0X,5 For x in range(5), concatenate x zeros to it AL (append list) '(. 0X,#p .') For x in range(len(p)), concatenate x zeros inside parens p^: '" Split p on " and assign result back to p Fi,#p Loop over the indices of the resulting list: Ii%2 If index is odd: p@i:0 Replace that item with 0 p: Jp Concatenate the results and assign back to p p.: ')X#p Append len(p) closing parens to p L#p Loop len(p) times: pR:z0 Replace every occurrence in p of items of z with 0 ! pRM')Rz0 Remove ) from result and replace z with 0 one more time; then take logical negation, which will be true iff string is empty OR consists only of zeros ``` Interesting tricks: * Many operators work item-wise on lists and ranges. So `0X,5`, for example, is `0 X [0 1 2 3 4] == ["" "0" "00" "000" "0000"]`. * As of a few days ago, the ternary `R`eplace operator can take a list for any of its arguments: `"abracadabra" R ["br" "ca"] 'b` gives `ababdaba`, for example. I make good use of this feature with `z` here. * Falsy values in Pip include the empty string `""`, empty list `[]`, and any scalar that is zero. Thus, `0` is false, but also `0.0` and `"0000000"`. This feature is inconvenient sometimes (to test whether a string is empty, one must test its length because `"0"` is false too), but for this problem it's perfect. [Answer] # Javascript (ES6), ~~289~~ ~~288~~ ~~285~~ ~~282~~ ~~278~~ ~~244~~ ~~241~~ 230 bytes ``` c=prompt(k="0"),j=c[l="length"];if((c.match(/"/g)||[])[l]%2)c+='"';c=c[R="replace"](/".*?"/g,k);c+=")".repeat(j);while(j--)c=c[R](/\(0*\)/,k)[R](/10/g,k)[R](/200/g,k)[R](/3000/g,k)[R](/40000/g,k);alert(!c[R](/0/g,"")[R](/\)/g,"")) ``` ]
[Question] [ [sandbox (deleted)](https://codegolf.meta.stackexchange.com/a/17288/78039) Lets define a matrix of 9s as: $$ N = \begin{bmatrix} 9&9&9\\9&9&9\\9&9&9 \end{bmatrix} $$ Lets define an exploding number as a number at position \$(x,y)\$ that can be decomposed into equal integers between all its adjacent neighbors (including itself) and the absolute value of each portion is greater than 0. From the previous matrix, lets explode the number at position \$(1,1)\$ (0 indexed) $$ N = \begin{bmatrix} 9&9&9\\9&\color{red}9&9\\9&9&9 \end{bmatrix} $$ $$ N = \begin{bmatrix} 9+\color{red}1&9+\color{red}1&9+\color{red}1\\9+\color{red}1&\color{blue}0+\color{red}1&9+\color{red}1\\9+\color{red}1&9+\color{red}1&9+\color{red}1 \end{bmatrix} $$ $$ N = \begin{bmatrix} 10&10&10\\10&\color{red}1&10\\10&10&10 \end{bmatrix} $$ Sometimes, decomposing result into a rational number greater than 1. This is something we need to avoid when exploding numbers. In this cases the remainder will be assigned to the exploded number. To demonstrate it, lets continue working with our previous matrix. This time we will explode the number at position \$(0,0)\$ $$ N = \begin{bmatrix} \color{red}{10}&10&10\\10&1&10\\10&10&10 \end{bmatrix} $$ Here we have 3 neightbors and the number itself. Here the equation is something like \$10/4\$ which give us **2** for each and **2** as remainder. $$ N = \begin{bmatrix} \color{blue}2+\color{red}{2}&\color{red}{10+2}&10\\\color{red}{10+2}&\color{red}{1+2}&10\\10&10&10 \end{bmatrix} $$ $$ N = \begin{bmatrix} \color{red}{4}&12&10\\12&3&10\\10&10&10 \end{bmatrix} $$ As well, sometimes a number wont be big enough to be decomposed in equal parts (where the abs is greater than 0) between his neighbors (|rational number| < 1). In this cases we need to *"borrow"* from the exploded number in order to maintain the *"greater than 0"* condition. Lets continue with our previous example and explode the number at position \$(1,1)\$. $$ N = \begin{bmatrix} 4&12&10\\12&\color{red}3&10\\10&10&10 \end{bmatrix} $$ $$ N = \begin{bmatrix} 4+\color{red}1&12+\color{red}1&10+\color{red}1\\12+\color{red}1&\color{blue}0+\color{red}{1}-\color{green}6&10+\color{red}1\\10+\color{red}1&10+\color{red}1&10+\color{red}1 \end{bmatrix} $$ $$ N = \begin{bmatrix} 5&13&11\\13&\color{red}{-5}&11\\11&11&11 \end{bmatrix} $$ --- **The challenge** is, given a list of \$(x,y)\$ positions and an finite non-empty array of natural numbers, return the exploded form after each number from the positions list has been exploded. --- **Test cases** Input: `initial matrix: [[3, 3, 3], [3, 3, 3], [3, 3, 3]], numbers: [[0,0],[0,1],[0,2]]` Output: `[[1, 0, 1], [5, 6, 5], [3, 3, 3]]` --- Input: `Initial matrix: [[9, 8, 7], [8, 9, 7], [8, 7, 9]], numbers: [[0,0],[1,1],[2,2]]` Output: `[[4, 11, 8],[11, 5, 10],[9, 10, 4]]` --- Input: `Initial matrix: [[0, 0], [0, 0]], numbers: [[0,0],[0,0],[0,0]]` Output: `[[-9, 3],[3, 3]]` --- Input: `Initial Matrix: [[10, 20, 30],[30, 20, 10],[40, 50, 60]], numbers: [[0,2],[2,0],[1,1],[1,0]]` Output: `[[21, 38, 13], [9, 12, 21], [21, 71, 64]]` --- Input: `Initial Matrix: [[1]], numbers: [[0,0]]` Output: `[[1]]` --- Input: `Initial Matrix: [[1, 2, 3]], numbers: [[0,0], [0, 1]]` Output: `[[1, 1, 4]]` --- **Notes** * [Input/Output rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply * You can assume input matrix will never be empty * You can assume coordinates are always going to be valid * Input coord in test cases is given as (row, column). If you need it to be (x, y) you can swap the values. If so, please state that in your answer [Answer] # C(GCC) ~~220~~ ~~216~~ ~~214~~ 212 bytes credit to @ceilingcat for 2 bytes ``` #define L(v)for(int v=2;~v--;) #define P l/C+r<0|l/C+r>=R|l%C+c<0|l%C+c>=C f(int R,int C,int*m){for(int*i=m+R*C;~*i;) {int*M,l=*i+++C**i++,a=0,b;L(r)L(c)P?:++a;M=m+l;b=*M/a;b+=!b;*M- =b*a;L(r)L(c)M[r*C+c]+=P?0:b;}} ``` [Run it here](https://tio.run/##XZDBbsIwDIbvfQqPCSmJU1HojRA49EolxJVxaAOdIrVlyhibVMqrd0loYZqixPKf77edqPBdqa57PRwLXR9hTS60OBmi6zNc5EzcLmEoaDBcb6CcJGgW0dXHpdxey3GCygkuLmUSFN685e5M3Mkq2vQ1mZYVblkibkwL2jgl5aVkGhET5gLPZMRzsSaGromim9UcMROptZUilyydZCJH@ZILloYyZ9mDTHeG2Qn2KDeraJ6Ltu3cBFWma0KDJgC4p2ejf3Z7kNDE/P@K/JraPePhtBW9yZy@P60hHnJ1Kr@q@iEVxAG8V/m9BfU3/U8ai0bChoWvJQDRUHAzPRl1Z5Rl@koOUwMG8GEsVpDROIoPfNS3sY8epkFQe98VoA3@Gt7qkdfboO1@AQ) a slightly less golfed version ``` #define L(v)for(int v=2;~v--;) #define P l/C+r<0|l/C+r>=R|l%C+c<0|l%C+c>=C f(int R, int C, int*m) { for(int*i=m+R*C;~*i;) { int*M,l=*i+++C**i++,a=0,b; L(r) L(c) P?:++a; M=m+l; b=*M/a; b+=!b; *M-=b*a; L(r) L(c) M[r*C+c]+=P?0:b; } } ``` The calling code with an example ``` int main() { int matrix[] = {3,3,3,3,3,3,3,3,3,0,0,0,1,0,2,-1}; int rows = 3; int columns = 3; f(rows,columns,matrix); for(int r = 0; r < rows; ++r) { for(int c = 0; c < columns; ++c) { printf("%03d,",matrix[r*columns + c]); } printf("\n"); } } ``` and the output ``` 001,005,003, 000,006,003, 001,005,003, ``` [Answer] # JavaScript (ES7), ~~126 125 123~~ 121 bytes *Saved 2 bytes thanks to @Shaggy* Takes input as `(matrix)(list)`. Outputs by modifying the matrix. ``` m=>a=>a.map(([Y,X])=>(g=n=>m[m.map((r,y)=>r.map((_,x)=>(x-X)**2+(y-Y)**2<3&&r[n++,x]++)),(m[Y][X]+=~n)<n||g``,Y][X]++)``) ``` [Try it online!](https://tio.run/##lZJvb4IwEMbf@ynulWnl0Lb4B6Llc2iaZhCnZouAQbNo5vbVWUuHOF1cBiV9uB73u6flNX1L98vyZXfw8@J5Va1llck4NaOfpTtC1ALnmsqYbGQu40xlLlziyQRL9/KER5tx9Oe01xMeOfkLK2ZBt1uq3PPwqD2PUiSZWmg11578zOksP583SYIu4tEkodVhtT@ABJIhpBRkDO@wJhklKZ3Cssj3xXbV3xYbE5rCR6dj04lSAZpbI9wKqxRDZmeG3E1Cawq312BgMjkCQ6jTRghjhJErBXZo3dAiDHFiV0KMGjHB6AeNO5p4QBsalCGGdboRBsnrbyMrEIYt8WKB3Vhqw/eQe6IfWR/fltrqBiYYBnWtoNaujyHDEcPxhSmco2t/3KHr6sJ4CELTe9CYEAjCbYNZmphnfOWJt1b@av6RJ35VEcUvZ/6f4s1fwOvdr74A "JavaScript (Node.js) – Try It Online") ### How? If we were to strictly follow the algorithm described in the challenge, we'd have to perform the following operations for each position pair \$(x,y)\$: 1. walk through the matrix to compute the number of neighbors \$n\$ 2. compute \$\lfloor m(x,y) / n\rfloor\$ and deduce the quantity \$q\$ that needs to be added to each neighbor 3. walk through the matrix again to update each neighbor 4. update \$m(x,y)\$ Instead of that, we use a recursive function which executes a simpler flow of operations, repeated as many times as needed: 1. for each neighbor and for the reference cell itself: increment the cell and increment a counter \$n\$ (initialized to \$0\$) 2. subtract \$n+1\$ from the reference cell 3. if the above result is greater than or equal to \$n\$, do a recursive call 4. increment the reference cell (all steps of this kind are executed *in succession* when the last recursive call has completed) The main benefit is that we only need one loop over the matrix. The second benefit is that we don't have to compute any quotient at all. ### Example $$M=\begin{pmatrix} 0&0&0\\ 0&26&0\\ 0&0&0 \end{pmatrix}\text{ and }(x,y)=(1,1)$$ After **step 1** of the **first iteration**, we have: $$M=\begin{pmatrix} 1&1&1\\ 1&27&1\\ 1&1&1 \end{pmatrix}\text{ and }n=9$$ And after **step 2** of the **first iteration**: $$M=\begin{pmatrix} 1&1&1\\ 1&17&1\\ 1&1&1 \end{pmatrix}$$ The key point here is that the reference cell is updated by taking only the cost (\$-9\$) into account without the gain (\$+1\$), so that we know how much we can still draw from it. Consequently, the sum of the cells is no longer equal to \$26\$ at this point. But this will be corrected at the end of the process, where all gains on the reference cell are accounted at once. **Step 3** of the **first iteration**: because \$17\$ is greater than \$9\$, we do a recursive call. After **step 1** of the **second iteration**, we have: $$M=\begin{pmatrix} 2&2&2\\ 2&18&2\\ 2&2&2 \end{pmatrix}\text{ and }n=9$$ And after **step 2** of the **second iteration**: $$M=\begin{pmatrix} 2&2&2\\ 2&8&2\\ 2&2&2 \end{pmatrix}$$ **Step 3** of the **second iteration**: this time, we have \$8<9\$, so we stop there. We now increment the reference cell twice (**step 4** of **both iterations**), leading to the final result: $$M=\begin{pmatrix} 2&2&2\\ 2&10&2\\ 2&2&2 \end{pmatrix}$$ ### Commented ``` m => a => // m[] = input matrix, a[] = list of positions a.map(([Y, X]) => ( // for each pair (X, Y) in a[]: g = n => // g = recursive function expecting n = 0 m[ // m.map((r, y) => // for each row r[] at position y in m[]: r.map((_, x) => // for each value at position x in r[]: (x - X) ** 2 + // if the quadrance between (x, y) (y - Y) ** 2 < 3 // and (X, Y) is less than 3: && r[n++, x]++ // increment n and increment r[x] ) // end ), // end (m[Y][X] += ~n) // subtract n + 1 from m[Y][X] < n // if the result is greater than or equal to n: || g``, // do a recursive call Y // ][X]++ // increment m[Y][X] )`` // initial call to g ) // end ``` [Answer] # [R](https://www.r-project.org/), ~~163~~ ~~162~~ ~~161~~ ~~159~~ ~~155~~ 146 bytes ``` function(m,l){for(e in l){v=m[i<-e[1],j<-e[2]];s=m[x<--1:(i<dim(m))+i,y<--1:(j<ncol(m))+j];z=sum(1|s);d=max(1,v%/%z);m[x,y]=s+d;m[i,j]=v+d-d*z};m} ``` [Try it online!](https://tio.run/##bZDRboMgFIbv9xTeNIF5zETWdQ55i901XDRYE4xootZYtz67O9KuqWwJcA7n/Pwf0M5FIOfiVOveNDWxUNGvomnJMTB1gPkg7d5k0XHPFJRLTJQSHRbHLIrYBzFZbiyxlIYGztdSmdW6qVytVGKS3ckS9t1RkUt7GAmDYfOymahADzgr2YU5pgZKJYcwj/Ln6SLsZS6IPfStGUkKHDiFynQ90SSBhIJGE7aEZUfp013LV9qbiP0e4SutRud32OFM3bqDlC7H4dM3uDG5ZxCDa/iwe1jDGMpj4G5ggtvXGLYxvMV/qfyKe4QnniEClv4D3MPh5dCG/fce5n5t/gE "R – Try It Online") ### Explanation (Corresponds to a previous version of the code) ``` function(m,l) { # Take input as matrix m and 1-indexed list of explosion points l for(e in l) { # Loop over the list of explosion points i=e[1]; j=e[2] # Assign current coordinates to (i,j) for brevity x=-1:1+i # Assign the ranges of neighboring cells: (i-1) to (i+1), y=-1:1+j # and (j-1) to (j+1) s= # Take the submatrix s=m[x,y] m[x<-x[x<=dim(m)] # But first trim x and y from above to prevent out of bounds errors, ,y<-y[y<=ncol(m)]] # trimming from below isn't necessary, as R tolerates index 0 z=sum(1|s) # Count the neighbors d=max(1,m[i,j]%/%z) # Estimate, how much we'll distribute to each neighbor m[x,y]=s+d # Add the distributed amount to each cell of the submatrix m[i,j]=m[i,j]-d*z # Subtract the total amount from the exploded cell } m # Return the modified matrix } ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~181~~ 167 bytes ``` import StdEnv; ``` # ``` foldl\m(x,y)={{if(d>2)0b+e-if(d>0)0b*n\\e<-:l&v<-[0..],let{b=max m.[y,x]n/n;$a b=2+sign a-(a+1)/size b;n= $x l* $y m;d=(v-x)^2+(u-y)^2}}\\l<-:m&u<-[0..]} ``` [Try it online!](https://tio.run/##ZY69boMwGEXn5Ck@CRTZwSbA1jrOlA6VumUEKhkwkSXbVOFHUMSr13WrbtWV7j3bubWWwjrTNaOWYISyzCnz0T0GuA3Ni52Yuw3iMex3AbTAoe10owuDZrJgvq6qRc0lw0kVSfrLieejLQp5ps/6MJ1pnsRxSbQc1oobMYOJ84XMpT1ZFgqoeBb16m5BUCSiFJ969SmhYpZDOIM@QriAYQ1HE53xexahkS5@t60otDeYw/hn2PY7fw7WYA2eiM9G/sEGOUpJignKSOb7h0vmvupWi3vv6Oubuy5WGFX33w) In the form of a partially-applied function literal. Expanded (first version): ``` f // functinon f on {{Int}} and [(Int,Int)] = foldl \m (x, y) // fold :: (a -> b -> a) a [b] -> a with first argument \ {{Int}} (Int,Int) -> {{Int}} giving \ {{Int}} [(Int,Int)] -> {{Int}} = { // an array of { // arrays of if(d > 2) 0 b // the amount we give to the neighbors + e // plus the current entry - if(d > 0) 0 b // minus the amount taken from the target entry * n // times the number of neighbors, if we're on the target \\ // for each e <-: l // element of row l & v <- [0..] // and x-index v , let // local definitions: b // the amount given to the neighbors = max // we need at least 1 each, so take the largest of m.[y, x] // the target entry n // or the number of neighbors / n // divide it by the number of neighbors n // the number of neighbors = ( // sum of 1 // one + s x // if x is at the left edge = 0 else 1 + s ( // if x is at the right edge = 0 else 1 size l - x - 1 ) ) * ( // times the sum of 1 // one + s y // if y is at the top edge = 0 else 1 + s ( // if y is at the bottom edge = 0 else 1 size m - y - 1 ) ) d // distance from the target point = (v - x)^2 + (u - y)^2 } \\ // for each l <-: m // row l in matrix m & u <- [0..] // and y-index u } ``` [Answer] # Rust - 295 bytes ``` fn explode(p:(i8,i8),v:&mut Vec<Vec<i8>>){let x=v[p.0 as usize][p.1 as usize];let q=|x,y|x*x+y*y;loop{let mut t=0;for i in 0..v.len(){for j in 0..v[i].len(){if q(i as i8-p.0,j as i8-p.1)<3{v[i][j]+=1;v[p.0 as usize][p.1 as usize]-=1;t+=1;}}}if v[p.0 as usize][p.1 as usize]<=(x/t+x%t){break;}}} ``` This is pretty long due to Rust requiring unsigned integer indexing of vectors, but requiring signed integers to do subtraction resulting in negatives. However I believe my algorithm is the "shortest algorithm" so far. There is actually no need to deal with detecting edges, bottom, etc. Notice three things: One, the sum of all cells is always constant. Two, this is a division / remainder situation, so we can apply Bresenham-algorithm style thinking. Three, the question always adds the same number to all cells within a certain distance of the special position cell, before dealing with the "extra" stuff in the special position. Algorithm: Store original value of cell at position P into M. Begin Loop: Iterate over each cell I in the matrix. If the position of cell I is within 3 Quadrance (squared distance) of the position P, then subtract 1 from cell P and add 1 to the cell I. Count how many times this is done in one iteration through the matrix. If the value leftover in the cell at position P is less than or equal to M / Count + M modulo Count, then break the loop. Otherwise perform the loop again. The resulting matrix will be the exploded version. Count is basically a way to count neighbors without dealing with edges. Looping is a way to break down the division/addition stuff into a repeated single addition/subtraction of one. The modulo check ensures we will have appropriate remainder left at position P to deal with 'explosions' that are not evenly divisible amongst neighbors. The do/while loop structure allows P<0 to work properly. [Ungolfed version on the Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a9b034495766443fdafea121d4fcd367) [Answer] # Java 10, ~~194~~ ~~193~~ ~~191~~ ~~190~~ ~~184~~ ~~182~~ 171 bytes ``` M->C->{for(var q:C){int n,X=q[0],Y=q[1],x,y,c=0;do{c++;x=n=0;for(var r:M){y=0;for(int $:r)r[y]+=Math.hypot(x-X,y++-Y)<2?++n/n:0;x++;}}while((M[X][Y]+=~n)>=n);M[X][Y]+=c;}} ``` Iterative port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/180205/52210). -17 bytes thanks to *@Arnauld*. Modifies the input-matrix instead of returning a new one to save bytes. [Try it online.](https://tio.run/##nVTRjppAFH33KyakDxCuFHDb3cJi05g06YNpk33REB6miBWLAzsMroSwv25HGAUsbkmDUe@de8859wwzW7zH4@3q99GPcJqiOQ5JMUIoZZiFPtryVS1jYaStM@KzMCbaV/HnMSTM9VwP@opmMUmzXUDPRdMpWiPnOB9PZ@NpsY6pvMcUPVszpeAViMDCeXZ1D5b8x/DgADn4jm6v4sJXVfvgEB6cu6g1V4pcJE7d7yyqUDf3VGeO2Ubb5EnM5MN4AbmqjpfKo/lZVcl7Yun2gYOV5csmjAJZnrsLz13yrleiTB2i2JeEz4uO9ojbkGQ/I26DcGMfhyu04w7JT4yG5JfrIayc3EKIBSmTSfCCxMB1FqHiE/CnhDfDElC7tTDAKEvFfhvY0KH6NGA8RMZ1pq65ZtBB/zcDugPD7OKZgCbDGAbN8L/mQDUADCOZAH8a1N6wz58TSU1lDpnkAe4b1AcuvRPe90zSzACFOYSkamgHt2Sfv4e8RKYOkxbspMq0t/hOhw86fOxjMyvlzRTGhbMcNZdIdWwqCaKVnyF@fg5whkJ@HNNVSDAvEufpKU9ZsNPijGkJP2osIrL0jSQZs5AkhkpowFj@47Qq14BiQdwLHVxkdUjEbNcsslRIalPHbyRVgk7G4JnSvmjokSlWaiUaTpIoP8vTsO8HCZPbSm7iSN8zNmzeWyL@2oM2QncrhOuNc5gbJpZueMVZmov/C6U4TzUW1xejjBWhoDz@AQ) **Explanation:** ``` M->C->{ // Method with two integer-matrix parameters and no return-type for(var q:C){ // Loop over the coordinates: int n, // Count integer X=q[0],Y=q[1], // The current X,Y coordinate x,y, // Temp x,y coordinates c=0; // Counter, starting at 0 do{ // Do-while: c++; // Increase the counter `c` by 1 x=n=0; // (Re)set both `x` and the count `n` to 0 for(var r:M) // Loop over the rows `r`: y=0; // (Re)set `y` to 0 for(int $:r) // Loop over the cells of the current row: r[y]+= // Increase the value at x,y by: Math.hypot( // If the hypot (builtin for `sqrt(a*a, b*b)`) of: x-X, // the difference between `x` and `X`, y++-Y) // and difference between `y` and `Y` // (and increase `y` by 1 afterwards with `y++`) <2? // Is smaller than 2: ++n/n // Increase count `n` and the value at x,y both by 1 : // Else: 0; // Leave the value at x,y the same by increasing by 0 x++;}} // Increase `x` by 1 while((M[X][Y]+=~n) // Decrease the value at X,Y by n+1 >=n); // Continue the do-while if this new value is still larger // than or equal to count `n` M[X][Y]+=c;}} // Increase the value at X,Y with counter `c` ``` [Answer] # [Common Lisp](http://www.clisp.org/), 498 bytes ``` (defmacro s(l c x)`(incf(aref m,l,c),x)) (defmacro w(a &rest f)`(if(,a(or(= l 0)(= l(d 0)))(or(= c 0)(= c(d 1)))),@f)) (defmacro d(n)`(1-(array-dimension m,n))) (defmacro p(i l m &rest f)`(loop for,i from(1-,l)to(1+,l)when(and(>=,i 0)(<=,i,m))do,@f)) (defmacro g()`(or(p i l(d 0)(p j c(d 1)(s i j 1)))(s l c(- v)))) (defun f(m l c)(let((v(w and 4(w or 6 9))))(if (<(/(s l c 0)v)1)(g)(loop for i to(1-(/(s l c 0)v))do(g))))) (defun c(m n)(dotimes(i(length n))(f m(nth 0(nth i n))(nth 1(nth i n))))m) ``` [Try it online!](https://tio.run/##XVHRToNAEHz3KzYx0dkIEaoxMWmN/onk4Npr4I4c2Navx7m22mJI2GEYZuYW07qhnybUje0qE4MMaMXIQT/hvLGoYmOly9rMaHZQvbkI96jkLjbDKDaJLbIKIWIlrRSaBmoC1RNpTqQhWZLU7N3O3Gp4upQ5A2P1ndeua/zggme215myh2NEd5XdhtCLDTFzYmPo6JK1OgaUD5z7TeNR@RpvK75niSVn1qnW4X@HNWjGtr24c3vC7bkzBrLbY3lC7gi57PS32pcXiy7RirYZgR32wlR55gxRXuQ1abkmwRKPJwcG7JTOa/07AjNS8XwmYVVqrrMMs7yiDiP3NMAx06/HDTkFfxc8cXG8uyOXUHl5Vu10Qh@dH2HkdvEBPAkvnQ@9B4q0hSKdv5BF@nL6AQ "Common Lisp – Try It Online") Use this function as `(print (c #2A((3 3 3) (3 3 3) (3 3 3)) '((0 0)(0 1)(0 2))))` Better readable version: ``` (defmacro s (l c x) `(incf (aref m ,l ,c) ,x)) (defmacro w (a &rest f) `(if (,a (or (= l 0) (= l (d 0))) (or (= c 0) (= c (d 1)))) ,@f)) (defmacro d (n) `(1- (array-dimension m ,n))) (defmacro p (i l m &rest f) `(loop for ,i from (1- ,l) to (1+ ,l) when (and (>= ,i 0) (<= ,i ,m)) do ,@f)) (defmacro g () `(or(p i l (d 0) (p j c (d 1) (s i j 1))) (s l c (- v)))) (defun f (m l c) (let ((v (w and 4 (w or 6 9)))) (if (< (/ (s l c 0) v) 1) (g) (loop for i to (1- (/ (s l c 0) v)) do (g))))) (defun c (m n) (dotimes (i (length n)) (f m (nth 0 (nth i n)) (nth 1 (nth i n)))) m) ``` Output example: ``` (print (c #2A((3 3 3) (3 3 3) (3 3 3) (3 3 3) (3 3 3) (3 3 3)) '((5 0)(4 1)(0 2)))) ;; #2A((3 4 0) (3 4 4) (3 3 3) (4 4 4) (5 -4 4) (1 5 4)) (print (c #2A((3 3 3) (3 3 3) (3 3 3)) '((0 0)(0 1)(0 2)))) ; #2A((1 0 1) (5 6 5) (3 3 3)) => #2A((1 0 1) (5 6 5) (3 3 3)) (print (c #2A((9 8 7) (8 9 7) (8 7 9)) '((0 0)(1 1)(2 2)))) ;; #2A((4 11 8) (11 5 10) (9 10 4)) => #2A((4 11 8) (11 5 10) (9 10 4)) (print (c #2A((0 0) (0 0)) '((0 0)(0 0)(0 0)))) ;; #2A((-9 3) (3 3)) => #2A((-9 3) (3 3)) (print (c #2A((10 20 30)(30 20 10)(40 50 60)) '((0 2)(2 0)(1 1)(1 0)))) ;; #2A((21 38 13) (9 12 21) (21 71 64)) => #2A((21 38 13) (9 12 21) (21 71 64)) ``` [Answer] # [Python 2](https://docs.python.org/2/), 171 bytes ``` M,p=input() l=len for i,j in p: y=[(i+y,j+x)for x in-1,0,1for y in-1,0,1if l(M)>j+x>-1<i+y<l(M[0])];x=max(M[i][j]/l(y),1);M[i][j]-=x*l(y) for i,j in y:M[i][j]+=x print M ``` [Try it online!](https://tio.run/##TY1BDoMgEEX3nGKWTB1T6FLFG3gCwqKLmmIoEqMJnJ5Caho3M//9Pz8T0v5e/SPniYKyPhw7R@aUe3k2rxtYWsB6CB2DpDS3TaKliVijWIJWkiBZKf3JzuD4hGO5G1s5lMpQWAuDpo/q84wFrNGLuTuekCT2J7cq3qrF4PI5dWfaqMjCZv0OU85ca0EgDMFvV1FUMS7T4Bc "Python 2 – Try It Online") ]
[Question] [ ## A celebration of the many faces of APL Given a string among those in column 1 or column 2 of the below table, return the string's neighbor to its right. In other words, if given a string in column 1 then return column 2's string on that row, and if given a string in column 2 then return column 3's string on that row. The codepoints (other than [`:`](http://help.dyalog.com/15.0/Content/Language/Defined%20Functions%20and%20Operators/DynamicFunctions/Guards.htm)'s) are listed on the far right. column 1   column 2   column 3  [`:⊢`](http://help.dyalog.com/15.0/Content/Language/Symbols/Right%20Tack.htm) → [`⍡`](http://wiki.nars2000.org/index.php/Convolution) → [`⊣:`](http://help.dyalog.com/15.0/Content/Language/Symbols/Left%20Tack.htm#kanchor3371)   U+22a2 U+2361 U+22a3  `:▷` → [`⍢`](http://www.jsoftware.com/papers/APLDesignExercises1.htm#39) → `◁:`   U+25b7 U+2362 U+25c1  [`:⋆`](http://microapl.com/apl_help/ch_020_020_200.htm) → [`⍣`](http://help.dyalog.com/15.0/Content/Language/Symbols/DieresisStar.htm) → [`⋆:`](http://microapl.com/apl_help/ch_020_020_200.htm)   U+22c6 U+2363 U+22c6  [`:∘`](http://help.dyalog.com/15.0/Content/Language/Symbols/Jot.htm) → [`⍤`](http://help.dyalog.com/15.0/Content/Language/Symbols/Jot%20Diaresis.htm#kanchor3364) → [`∘:`](http://help.dyalog.com/15.0/Content/Language/Symbols/Jot.htm)   U+2218 U+2364 U+2218  [`:○`](http://help.dyalog.com/15.0/Content/Language/Symbols/Circle.htm) → [`⍥`](http://jsoftware.com/papers/APLDictionary1.htm#hoof) → [`○:`](http://help.dyalog.com/15.0/Content/Language/Symbols/Circle.htm)   U+25cb U+2365 U+25cb  `:≀` → [`⍨`](http://help.dyalog.com/15.0/Content/Language/Primitive%20Operators/Commute.htm) → `≀:`   U+2240 U+2368 U+2240  [`:∧`](http://help.dyalog.com/15.0/Content/Language/Primitive%20Functions/And%20Lowest%20Common%20Multiple.htm) → [`⍩`](http://jsoftware.com/papers/APLDictionary1.htm#withe) → [`∨:`](http://help.dyalog.com/15.0/Content/Language/Primitive%20Functions/Or%20Greatest%20Common%20Divisor.htm)   U+2227 U+2369 U+2228 *Anecdote:* Most of these symbols are valid or proposed in some APL dialect (they are all links). Per request, just the symbols: ``` :⊢ ⍡ ⊣: :▷ ⍢ ◁: :⋆ ⍣ ⋆: :∘ ⍤ ∘: :○ ⍥ ○: :≀ ⍨ ≀: :∧ ⍩ ∨: ``` [Answer] ## JavaScript (ES6), ~~108~~ 107 bytes ``` s=>(S="⊢▷⋆∘○≀∧⍡⍢⍣⍤⍥⍨⍩⊣◁⋆∘○≀∨")[S.search(s[1]||s)+7]+(s[1]?'':':') ``` ### Demo ``` let f = s=>(S="⊢▷⋆∘○≀∧⍡⍢⍣⍤⍥⍨⍩⊣◁⋆∘○≀∨")[S.search(s[1]||s)+7]+(s[1]?'':':') ;[ ":⊢", ":▷", ":⋆", ":∘", ":○", ":≀", ":∧", "⍡", "⍢", "⍣", "⍤", "⍥", "⍨", "⍩" ] .forEach(s => console.log(s + ' → ' + f(s))) ``` [Answer] # [Python 3](https://docs.python.org/3/), 105 bytes ``` lambda s:":⊢⍡⊣:▷⍢◁:⋆⍣⋆:∘⍤∘:○⍥○:≀⍨≀:∧⍩∨:".split(s)[1][:3-len(s)] ``` [Try it online!](https://tio.run/##Tc49asNAEAXgWnuKwZUWFENQN7Cn2FJWsbJlLFAU4RWEdHFj/MO2sVtbNpZPkPvMRZSZVGkevJmBb9rPbvXepOPSzMbavRULBx4nSIcrhQsdeqTvHwpXOm2QjlsKPSfS7kzhxol0OlK4cyLtvygMnLx9UHjSbsDJ1Ld11cVeZ695hulLXTZc8tGaPwLYAEFAGG48YQiE4taDYCActxsICEJyu4OgICy3AQSWywe3J/zHtVIfq6ouwaKKXFIkczBg@ZtcRe26arrYJcvYaY5Caz7xvlx3ICNjCnDNAmRjzFxF1tgsxXz8BQ "Python 3 – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 148 134 bytes ``` s=>{var c="⊢⍡⊣▷⍢◁⋆⍣⋆∘⍤∘○⍥○≀⍨≀∧⍩∨";return c[c.IndexOf(s[s.Length-1])+1]+(s.Length<2?":":"");} ``` [Try it online!](https://tio.run/##Sy7WTc4vSv2vAATJOYnFxQoBRfnpRYm5XCCRajAJAsUliSWZyQpl@ZkpCr6JmXkamnAphCIQCK4sLknN1XMrzUu2KS4pysxL11GA0HYKaQq2XP@Lbe2qyxKLFJJtlR51LXrUu/BR1@JH07Y/6l30aHrjo@62R72LQWTHjEe9S0Dk9O5HvUtBZGfDo94VILJj@aPelY86VihZF6WWlBblKSRHJ@t55qWkVvinaRRHF@v5pOall2ToGsZqahvGamvABGyM7JWsgFBJ07r2vzUXNmc75@cV5@ek6oUXZZak@mTmpWqkaShZAZ2npKlpTbQGoMtJUm8FDAgSLViJor4WzKr9DwA "C# (.NET Core) – Try It Online") * 14 bytes saved after golfing a little. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 56 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “¤'aẎṚl’b4ạ37ż“ɱaɲṢbḊİcİðdðṖeṖ@h@'i(‘ḅ⁹Ọɓi@€Ṁ‘ị;⁸LḂx@”:¤ ``` A full program. **[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDS9QTH@7qe7hzVs6jhplJJg93LTQ2P7oHKHNyY@LJTQ93Lkp6uKPryIbkIxsOb0g5vOHhzmmpQOyQ4aCeqfGoYcbDHa2PGnc@3N1zcnKmw6OmNQ93NoBEd3dbP2rc4fNwR1OFw6OGuVaHlvw/uudwO1BBFhA/atynoJD1qHHv0cmxQK2HlhxaEvn/f7SS1aOuRUo6CkqPeheCKKtH07ZDuIsg3O42CHcxhNsxA8JdAuFO74Zwl0K4nQ0Q7gqo4uUQ7kqlWAA "Jelly – Try It Online")** *Note:* (`ɱaɲ`!) While there is some pattern to the non-`:` ordinals (middle column almost consecutive, many left and rights being the same - only two off by one and one off by ten) it just does not seem quite enough for such a small data set to allow any byte saves over this. The first thirteen bytes could also be `“¡ÐɼU¹’ṃ“"%#‘`. ### How? ``` “¤'aẎṚl’b4ạ37ż“ ... ‘ḅ⁹Ọɓi@€Ṁ‘ị;⁸LḂx@”:¤ - Main link: list of characters, frown “¤'aẎṚl’ - base 250 number = 4064044420859 b4 - to base 4 = [3, 2, 3, 0, 2, 0, 3, 2, 3, 3, 2, 3, 0, 2, 0, 3, 2, 3, 3, 2, 3] ạ37 - absolute diffence with 37 = [34, 35, 34, 37, 35, 37, 34, 35, 34, 34, 35, 34, 37, 35, 37, 34, 35, 34, 34, 35, 34] “ ... ‘ - code page indexes = [162, 97, 163, 183, 98, 193, 198, 99, 198, 24, 100, 24, 203, 101, 203, 64, 104, 64, 39, 105, 40] ż - zip together = [[34, 162], [35, 97], [34, 163], [37, 183], [35, 98], [37, 193], [34, 198], [35, 99], [34, 198], [34, 24], [35, 100], [34, 24], [37, 203], [35, 101], [37, 203], [34, 64], [35, 104], [34, 64], [34, 39], [35, 105], [34, 40]] ⁹ - literal 256 ḅ - convert from base = [8866, 9057, 8867, 9655, 9058, 9665, 8902, 9059, 8902, 8728, 9060, 8728, 9675, 9061, 9675, 8768, 9064, 8768, 8743, 9065, 8744] Ọ - convert to characters = "⊢⍡⊣▷⍢◁⋆⍣⋆∘⍤∘○⍥○≀⍨≀∧⍩∨" ɓ - dyadic chain separation, call that smiles i@€ - first index of €ach frown character in smiles Ṁ - maximum (any ':' was not found so yielded 0) ‘ - increment ị - index into smiles ¤ - nilad followed by link(s) as a nilad ⁸ - chain's left argument, frown L - length Ḃ - mod 2 ”: - literal ':' x@ - repeat with swapped @rguments ; - concatenate - implicit print ``` --- Employing [Emigna's 05AB1E method of compression](https://codegolf.stackexchange.com/a/127828/53748) saves three for **53 bytes**: ``` “ȤỤ.ḍṅfḲBṆ µṾḢƲ¿ṭVÄ⁹L5ı;ṡaÐ’Ds3Ḍ+⁽œẉỌɓi@€Ṁ‘ị;⁸LḂx@”:¤ ``` [Try it online!](https://tio.run/##AXsAhP9qZWxsef//4oCcyKThu6Qu4biN4bmFZuG4skLhuYYgwrXhub7huKLGssK/4bmtVsOE4oG5TDXEsTvhuaFhw5DigJlEczPhuIwr4oG9xZPhuonhu4zJk2lA4oKs4bmA4oCY4buLO@KBuEzhuIJ4QOKAnTrCpP///zriiKc) [Answer] # [Python 3](https://docs.python.org/3/), ~~140~~ ~~137~~ 116 bytes ``` lambda n,x=":⊢⍡⊣:▷⍢◁:⋆⍣⋆:∘⍤∘:○⍥○:≀⍨≀:∧⍩∨:":x[x.find(n)+len(n):x.find(n)+3] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFPp8JWyepR16JHvQsfdS22ejRt@6PeRY@mN1o96m571LsYSFo96pjxqHcJkLR6NL37Ue9SIGn1qLPhUe8KIAmUXf6od@WjjhVWSlYV0RV6aZl5KRp5mto5qXlAygohYBz7v6AoM69EI01DHahXXVPzPwA "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~58~~ ~~56~~ 54 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md) ``` • î]D£Èтн»“¿āp÷ŒRÃÙŽ^мηWX·ć•3ô8728+çJ3ô':ý':.øI¡`3Ig-£ ``` [Try it online!](https://tio.run/##AWIAnf8wNWFiMWX//@KAoiDDrl1EwqPDiNGC0L3Cu@KAnMK/xIFww7fFklLDg8OZxb1e0LzOt1dYwrfEh@KAojPDtDg3Mjgrw6dKM8O0JzrDvSc6LsO4ScKhYDNJZy3Co///OuKLhg "05AB1E – Try It Online") **Explanation** ``` • î]D£Èтн»“¿āp÷ŒRÃÙŽ^мηWX·ć• # push a 63-digit base-255 compressed number 3ô # split in pieces of 3 8728+ # add 8728 to each çJ # convert to a string with the corresponding code points 3ô # split in pieces of 3 ':ý # merge on ":" ':.ø # surround with ":" I¡ # split on input ` # push as separate to stack, the tail on top 3Ig-£ # take the first 3-len(input) characters ``` The above method should work with any number in the range `[8676 ... 8728]`, so if I can find a number there that can be generated in 3 bytes I could save a byte over the current solution. [Answer] # [PHP](https://php.net/), 147 bytes ``` <?=($f=array_flip($y=str_split(⍣⋆⍤∘⍥○⍨≀∧⍩∨⊢⍡⊣▷⍢◁,3))[trim($argn,":")])>7?$y[$f+1].":"[$f%3>1]:$y[$f^1].":"[$f&1]; ``` [Try it online!](https://tio.run/##PZDBSsMwHMbveQqJURKsQtlB6Gz7IF0cobRrYbYh7aWIoBeZG16dVzfF@QS@T97Bc/34C15Cfh/h933EVna8Sm1lWdm6wuSVzBiP/HrHA@6f33BG/uWbYEeweSTYE6xeCd4JthuCD4Kne4LD37NPgi/OtOmEcYtGsVuWJmiOpShj45wZ5uWytlIMcde7eWeXdS9Rgz74UQQxGmCEGkLY/OqAnRjp13tsxEC/fQgmSmW9q28k9aCdK62Sy1QMmSjPQn2BBLeTSRLqiMLr//A01NOxyKv2iB3zWU8GHjA@a/j0bvxp2vMcP1T8Ag "PHP – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 103 bytes -17 bytes thanks to Adám ``` (⌷∘S,':'/⍨14∘<)7+(S←'⊢▷⋆∘○≀∧⍡⍢⍣⍤⍥⍨⍩⊣◁⋆∘○≀∨')⍳⊢/ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X@NRz/ZHHTOCddSt1PUf9a4wNAHybDTNtTWCH7VNUH/UtejRtO2PutuAoo@mdz/qbHjUsfxR78JHvYse9S5@1LvkUe9SoK5HvSsfdS1@NL0RVeUKdc1HvZuBZuj/TwOa9qi371FX86PeNY96txxab/yobeKjvqnBQc5AMsTDM/h/moK6FVCxOleaAowJAA "APL (Dyalog Unicode) – Try It Online") # [APL (Dyalog Unicode)](https://www.dyalog.com/), 118 bytes Since the asker is an APL programmer... ``` {(':'/⍨14<X),⍨S⌷⍨X←7+⍸(S←'⊢▷⋆∘○≀∧⍡⍢⍣⍤⍥⍨⍩⊣◁⋆∘○≀∨')∘.=⊢/⍵} ``` [Try it online!](https://tio.run/##VU07CsJAFLyK3Sb4QxQE0cpGW9cibUBiE9BWRFCEJW58QQuNrYliBMFGibVHmYusr7WZD8zHnfrl0cz1J2Nj5pZoiSooqzXajl1iIbHNmRyoXbMI@liSlYBOcMwRKgQnxCE2SwQ30BmUgFLQBXTlFugOnSJe/SczYbOrdHiFv94L4/EmKIJegx6g1/dZh9ojOshBl3HY60vjFQQfiB8 "APL (Dyalog Unicode) – Try It Online") ## Explanation ``` S←'⊢▷⋆∘○≀∧⍡⍢⍣⍤⍥⍨⍩⊣◁⋆∘○≀∨' ⍝ S is the lookup table. ⍸()∘.=⊢/⍵ ⍝ Find the input in this LUT. X←7+ ⍝ Add the index by 7 and assign to X. S⌷⍨ ⍝ Index into the LUT. ,⍨ ⍝ Append: ':'/ ⍝ The colon (⍨14<X) ⍝ if X is larger than 14. ``` ]
[Question] [ This is a window: ``` --- | | --- ``` Let's add some walls `|`. Put two spaces on either side of it so that the window has plenty of room. ``` | --- | | | | | | --- | ``` Now let's add a roof and a ceiling. To keep the window in the middle of the room, let's add one more row above it and below it. ``` --------- | | | --- | | | | | | --- | | | --------- ``` Now, just add a roof. Put a slash as far left as possible, and a backslash as far right as possible, and we have this: ``` / \ --------- | | | --- | | | | | | --- | | | --------- ``` Then move the slash up one and right one. Move the backslash up one and left one: ``` / \ / \ --------- | | | --- | | | | | | --- | | | --------- ``` Repeat until the two slashes meet, then add an asterisk where they meet: ``` * / \ / \ / \ / \ --------- | | | --- | | | | | | --- | | | --------- ``` And you're done! This is a 1x1 house. a 2x2 house would look like this: ``` * / \ / \ / \ / \ / \ / \ / \ / \ ----------------- | | | | --- | --- | | | | | | | | | --- | --- | | | | |-------|-------| | | | | --- | --- | | | | | | | | | --- | --- | | | | ----------------- ``` and a 3x2 house: ``` * / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ ------------------------- | | | | | --- | --- | --- | | | | | | | | | | | | --- | --- | --- | | | | | |-------|-------|-------| | | | | | --- | --- | --- | | | | | | | | | | | | --- | --- | --- | | | | | ------------------------- ``` # The challenge You must write a full program that takes two integers, x and y, and prints a house that is *X* rooms wide and *Y* rooms tall. Your program should be able to handle houses up to 10x10. IO can be in any reasonable format. Trailing spaces on each line are allowed, and one trailing newline is allowed. Shortest answer in bytes wins. [Answer] # Vim ~~122~~, 89 Keystrokes ``` "aDJ"bD9i-<esc>Y2pVr <C-v>jr|$.Y4p3l<C-v>jljlr-jR| |<esc>{l<C-v>}d@apjdG@bp}Vr-{YPVr r/$r\qqYPllxx|P@qq@qddr* ``` [Try it online!](https://tio.run/nexus/v#@6@U6OKllORimalrk1qcbBdpVBBWpGDjrFtml1VUo6IXaVJgnAPh5mTlFOlmBdUo1IBVVkOEa1McEguyUtwdkgpqw4p0qyMDgPqL9FWKYgoLIwNycioqagIcCgsdClNSirT@/zfhMv2vWwYA "V – TIO Nexus") I've improved my vim-golfing skills significantly since I posted this answer, so I decided to go back and write this whole thing from scratch. Saved thirty-three bytes in the process! Input is assumed to be on two separate lines, so that the buffer looks like this before you start typing: ``` 3 4 ``` I had a very detailed explanation, but I don't feel like writing it all over again from the beginning... >\_< Check out the revision history if you still want to see it. [Answer] ## Python 3.6 (pre-release), ~~221~~ ~~210~~ 203 bytes ``` x,y=eval(input()) w=8*x+1;p='-'*w+'\n' for v in['*',*[f'/{" "*i}\\'for i in range(1,w-1,2)],p+p.join([''.join(f'{"".join([f"|{(a*3)[:3]:^7}"]*x)}|\n'for a in(*' -','| |',*'- '))]*y)+p]:print(v.center(w)) ``` Reads 2 integers (separated by comma) from stdin, prints the house to stdout. Readable version: ``` x, y = eval(input()) w = 8 * x + 1 # total width (in characters) p = '-' * w + '\n' # floors for v in [ '*', # asterisk *[f'/{" "*i}\\' for i in range(1, w-1, 2)], # roof p + p.join([''.join(f'{"".join([f"|{(a*3)[:3]:^7}"]*x)}|\n' for a in (*' -','| |',*'- '))]*y) + p # rooms ]: print(v.center(w)) ``` [Answer] ## Python 2, ~~190~~ 181 bytes ``` w,h=input();W=w*4 for i in range(~W,h*6+1):print['-'[i%(h*6):]*(W-~W)or[' %s '%' -|- - - -|- '[~i%6::5],'-'*7][i%6<1].join('|'*-~w),' '*~i+['/%*c'%(w*8-~i*2,92),'*'][W<-i]][i<0] ``` Pretty sure there's much to golf, especially the windows, but here's something for now. Input width and height comma-separated, e.g. `1,2`. Quick and rough explanation: ``` * <--- i = ~W = -w*4 - 1. <---\ / \ <--\ i = -W = -w*4 | Preceding spaces / \ | | are calculated / \ | | the same way / \ <--/ i = -1 <---/ /---> --------- <--- i = 0 | | | <--\ i = 1 <---\ Check | --- | | | Calculate inner string i%(h*6) | | | | | | and use to join '|'s is zero | --- | | | (ditto with |-------|) | | | <--/ i = h*6 - 1 <---/ \---> --------- <--- i = h*6 ^ ^ \-------/ W-~W = w*8 + 1 ``` [Answer] # JavaScript (ES6), ~~292~~ ~~270~~ ~~238~~ ~~215~~ 200 bytes *Thanks @Neil for helping trim this down!* ``` a=>b=>[(p=(c,d=' ')=>d.repeat(c))(m=4*a)+'*',...[...Array(m)].map((c,i)=>p(--m)+`/${p(i*2+1)}\\‌`),y=p(8*a+1,'-')].join` `+p(b,` `+[x=p(a,'|'+p(7)),w=p(a,'| --- '),p(a,'| | | '),w,x,y].join`| `) ``` Call as: `F(a)(b)` Builds the roof, then assembles the core house with layered string repeats. [Answer] # C++, 258 Bytes [Test Here](https://ideone.com/P1ZeVa) ``` #include<cstdio> int main(){for(int r=10,c=10,x,y,q,u,h=c*4,w=h*2,i=0;i<h+r*8+2;i++)for(q=0;q<w+2;q++)x=q%8,y=i%8,u=(i-(h+1))%8,putchar(q==w+1?10:i<=h?!i&&q==h?42:i==h-q?47:i==q-h?92:32:!u||(u==3||u==5)&&x>2&&x<6?45:!x||u==4&&(x==3||x==5)?124:32);return 0;} ``` Result: ``` * / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ --------------------------------------------------------------------------------- | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | --------------------------------------------------------------------------------- | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | --------------------------------------------------------------------------------- | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | --------------------------------------------------------------------------------- | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | --------------------------------------------------------------------------------- | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | --------------------------------------------------------------------------------- | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | --------------------------------------------------------------------------------- | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | --------------------------------------------------------------------------------- | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | --------------------------------------------------------------------------------- | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | --------------------------------------------------------------------------------- | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | --------------------------------------------------------------------------------- ``` [Answer] # C++, 282 bytes, fixes the problems with the previous entry: ``` #include<cstdio> int main(){for(int r=2,c=2,x,y,q,u,h=c*4,w=h*2,i=0;i<h+r*6+2;i++)for(q=0;q<w+2;q++)x=q%8,y=i%8,u=(i-h-1)%6,putchar(q==w+1?10:i<=h?!i&&q==h?42:i==h-q?47:i==q-h?92:32:!u&&x||!u&&(i<h+2||i==h+r*6+1)||(u==2||u==4)&&x>2&&x<6?45:!x||u==3&&(x==3||x==5)?124:32);return 0;} ``` Output: ``` * / \ / \ / \ / \ / \ / \ / \ / \ ----------------- | | | | --- | --- | | | | | | | | | --- | --- | | | | |-------|-------| | | | | --- | --- | | | | | | | | | --- | --- | | | | ----------------- ``` [Answer] # Ruby, Rev B 165 bytes ``` w=1-2*r=-4*x=gets.to_i puts (r-1..h=6*gets.to_i).map{|n|n<0?(n<r ??*:?/+' '*(w+n*2)+?\\).center(w):n%h<1?(?-*w):'|CCBABCC'.tr('CBA',' | \-'[1222>>n%6*2&6,3])*x+?|} ``` uses a single loop and several other golfing tricks. # Ruby, Rev A 179 bytes ``` w=1+8*x=gets.to_i y=gets.to_i b=(0..x*4).map{|n|(n<1??*:?/+' '*(n*2-1)+?\\).center(w)} a=(2..y*6).map{|n|('|CCBABCC'.tr('CBA',' | \\-'[4888>>n%6*2&6,3]))*x+?|} puts b,s=?-*w,a,s ``` **Ungolfed** ``` x=gets.to_i y=gets.to_i w=x*8+1 #calculate width of house b=(0..x*4).map{|n| #design a roof line by line (n<1??*:?/+' '*(n*2-1)+?\\).center(w) #first line is *, second line is /[spaces]\ } #centre correctly to the width of the house by padding a=(2..y*6).map{|n| #design a front facade line by line ('|CCBABCC'. #template for each row tr('CBA',' | \\-'[4888>>n%6*2&6,3])#substitute CBA for 3 characters from the string according to magic number 4888 )*x+?| #we need x copies, finishing with a | } puts b,s=?-*w,a,s #print a roof, a line of -, a facade and another line of - ``` [Answer] # C#, 361 353 bytes ``` string b(int w,int h){string m="",s,f,o=m,x,y,n="\n",p="|",q=" ";int i=0,v=w*4;Func<int,string,string>r=(j,c)=>{for(s="";j-->0;)s+=c;return s;};m+=r(v,q)+"*\n";for(;i<v;)m+=r(v-i-1,q)+'/'+r(i++*2+1,q)+"\\\n";f=r(w*8+1,"-");m+=f;x=n+r(w,p+r(7,q))+p;y=n+r(w,"| --- ")+p;o=x+y+n+r(w,"| | | ")+p+y+x;for(i=1;i++<h;)m+=o+x.Replace(q,'-');return m+o+n+f;} ``` ### Full Program: ``` using System; class House { static int Main() { var x = new House(); Console.WriteLine(x.b(1,1)); Console.WriteLine(); Console.WriteLine(x.b(2,2)); Console.WriteLine(); Console.WriteLine(x.b(2,3)); Console.WriteLine(); Console.WriteLine(x.b(9,9)); Console.WriteLine(); Console.Read(); Console.WriteLine(x.b(10, 10)); // Looks broken because Bash to small Console.Read(); return 0; } string b(int w,int h){string m="",s,f,o=m,x,y,n="\n",p="|",q=" ";int i=0,v=w*4;Func<int,string,string>r=(j,c)=>{for(s="";j-->0;)s+=c;return s;};m+=r(v,q)+"*\n";for(;i<v;)m+=r(v-i-1,q)+'/'+r(i++*2+1,q)+"\\\n";f=r(w*8+1,"-");m+=f;x=n+r(w,p+r(7,q))+p;y=n+r(w,"| --- ")+p;o=x+y+n+r(w,"| | | ")+p+y+x;for(i=1;i++<h;)m+=o+x.Replace(q,'-');return m+o+n+f;} // Without extra vars string b1(int w, int h) { string m = "", s, f, o = m, x, y; int i = 0, v = w*4; Func<int,string,string> r = (j,c) => { for(s = ""; j-->0;) s += c; return s; }; /// Roof m += r(v, " ") + "*\n"; for (; i < v;) m += r(v - i - 1, " ") + '/' + r(i++ * 2 + 1, " ") + "\\\n"; /// Ceiling f = r(w * 8 + 1, "-"); m += f; /// Room x = "\n" + r(w, "|" + r(7, " ")) + "|"; y = "\n" + r(w, "| --- ") + "|"; o = x + y + "\n" + r(w, "| | | ") + "|" + y + x; for (i = 1; i++ < h;) m += o + x.Replace(' ','-'); /// Floor return m + o + "\n" + f; } string build(int width, int height) { // House, tempStr, floor, room, x/y = room_row1/2 string house = "", s, ceil, room = "", x, y; int i, v = width*4; Func<int,string,string> rep = (j,c) => { s = ""; for(; j>0; j--) s += c; return s; }; /// Roof house += rep(v, " ") + "*\n"; for (i = 0; i < v;) { // LEFT Indent + '/' + Distance + '\' house += rep(v - i - 1, " ") + '/' + rep(i++ * 2 + 1, " ") + "\\\n"; } /// Ceiling ceil = rep(width * 8 + 1, "-"); house += ceil; /// Room x = "\n" + rep(width, "|" + rep(7, " ")) + "|"; y = "\n" + rep(width, "| --- ") + "|"; room = x + y + "\n" + rep(width, "| | | ") + "|" + y + x; for (i = 1; i < height; i++) { house += room;// + x.Replace(' ','-'); house += "\n" + rep(width, "|" + rep(7, "-")) + "|"; } /// Floor house += room + "\n" + ceil; return house; } } ``` [Answer] # VBA, 284 bytes ``` Function H(W,S) L=vbLf:H=Space(4*W)&"*"&L For R=1 To 4*W:H=H &Space(4*W-R)&"/"&Space(2*R-1)&"\"&L:Next J=".":P=String(W,J)&"|"&L D=String(8*W+1,"-")&L E=Replace(P,J,"| ") F=Replace(P,J,"| --- ") H=H &Replace(String(S,J),J,D &E &F &Replace(P,J,"| | | ")&F &E)&D End Function ``` The Replace function is a neat tool for making multiple copies in a way that the String function unfortunately doesn't want to. Invoke for best effect in the Immediate window of the VBA editor: `?H(8,8)` for example. ``` ?H(8,8) * / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ ----------------------------------------------------------------- | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | ----------------------------------------------------------------- | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | ----------------------------------------------------------------- | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | ----------------------------------------------------------------- | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | ----------------------------------------------------------------- | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | ----------------------------------------------------------------- | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | ----------------------------------------------------------------- | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | ----------------------------------------------------------------- | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | ----------------------------------------------------------------- ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 91 bytes ``` '*'↑⍨-1+3×w←⎕ ' /'[⊖a],' ',' \'[a←∘.=⍨⍳w×3] ' |-'[2⍪⍨2⍪¯1↓⊃⍪/⎕⌿⊂1,⍨⊃,/w/⊂⍉3⊤269+⎕AV⍳'4 4#'] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXI862tP@q2upP2qb@Kh3ha6htvHh6eVAGaAKLnUFffXoR13TEmN11BXUgThGPToRJNcxQ88WqPpR7@byw9ONY4EKa3TVo40e9a4CioKoQ@sNH7VNftTVDGTrA4161LP/UVeToQ5IU1ezjn65PpD7qLfT@FHXEiMzS22gEscwoHHqJgomyuqx/4Gu@p/GZQiEaVzGXCYA "APL (Dyalog Extended) – Try It Online") Full program, takes columns, then rows, on separate lines. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 76 bytes ``` 4*:×꘍,(¹4*n-‹\/꘍nd›\\꘍+,)¹8*›¤-?(…\|7꘍¹*\|+…\|:2꘍2-ømṪ¹*$+…»ŀ»‛ |τ¹*\|+,,,), ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=4*%3A%C3%97%EA%98%8D%2C%28%C2%B94*n-%E2%80%B9%5C%2F%EA%98%8Dnd%E2%80%BA%5C%5C%EA%98%8D%2B%2C%29%C2%B98*%E2%80%BA%C2%A4-%3F%28%E2%80%A6%5C%7C7%EA%98%8D%C2%B9*%5C%7C%2B%E2%80%A6%5C%7C%3A2%EA%98%8D2-%C3%B8m%E1%B9%AA%C2%B9*%24%2B%E2%80%A6%C2%BB%C5%80%C2%BB%E2%80%9B%20%7C%CF%84%C2%B9*%5C%7C%2B%2C%2C%2C%29%2C&inputs=2%0A3&header=&footer=) A. Mess. ]
[Question] [ # Introduction A palindromic closure of an input string is the shortest palindrome that can be constructed out of the input string where the final palindrome starts with the input string. For this challenge, we will consider a two-way palindromic closure such that * **Left Palindromic Closure** of an input string is the shortest palindrome possible that starts with the input string. * **Right Palindromic Closure** of an input string is the shortest palindrome possible that ends with the input string. * **Two-way Palindromic Closure** of an input string is the shorter of either of Left or Right Palindromic Closure of the input string. # Task Your task is simple. Given a string (consisting only of printable ASCII, new lines and white spaces), output the two-way palindromic closure of that string. In case of tie, either of the left or right palindromic closures are valid output. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument, and either printing the result to STDOUT (or closest alternative) or returning it as a string. You can assume that the input will never be an empty string. Few examples: ``` <Input> -> <Output> "abcdef" -> "abcdefedcba" (or "fedcbabcdef") "abcba" -> "abcba" "abcb" -> "abcba" "cbca" -> "acbca" ``` --- *Initial Idea credit goes to VisualMelon, final idea with help from Martin and Zgarb* *The terms palindromic closure, left-pallindromic closure and right-palindromic closure were first used and defined by [this paper](http://ac.els-cdn.com/S0304397596003106/1-s2.0-S0304397596003106-main.pdf?_tid=868f5514-cbf1-11e4-a30b-00000aacb35f&acdnat=1426520073_3471c7c0fc186b72aac6feec79f5).* [Answer] # Pyth, ~~22~~ 19 ``` hfq_TTsm,+z_d+_dzyz ``` Try it [online](https://pyth.herokuapp.com/?code=hfq_TTsm%2C%2Bz_d%2B_dzyz&input=cbca&debug=0). ## Explanation The two-way palindromic closure is either of the form `AX` or `XA`, where `X` is the input string and `A` is a substring of `X`. I actually has to be a contiguous substring of `X`, a prefix for the one form, a suffix for the other form. But I don't care about these defails. A substring (contiguous or not) is all I need in Pyth. ``` Implicit: z = raw_input() // Read a string yz A list with all substrings (contiguous or not) of z m For each of these substrings d, build , a pair of two strings: +z_d ( z + inveres(d) , +_dz inverse(d) + z ) s Sum (put all created pairs into a list) fq_TT filter elements T, where inverse(T) == T (Palindrom) h Take the first element ``` ## Edit The old version ordered the the strings after filtering by length `.olN...`. Just realized, that `y` returns the substrings ordered by length. So these palindromes are already sorted. [Answer] # [Clip](https://www.assembla.com/code/clip-language/subversion/nodes/4/trunk/Clip/dist/Clip.jar), 40 ``` (sl`f[a=ava}+m[i+v+ixx}Rlxm[i+xvu0ix}Rlx ``` ## Example ``` Documents>java -jar Clip4.jar palindrome.clip abcb abcba ``` ## Explanation ``` (sl` .- The shortest -. f[a=ava} .- palindrome -. + .- among the following two sets: -. m[i }Rlx .- For each number up to length(x) -. + .- combine -. v+ix .- the last i chars of x, reversed -. x .- and x. -. m[i }Rlx .- For each number up to length(x) -. + .- combine -. x .- x and -. vu0ix .- the first i chars of x, reversed.-. ``` [Answer] # CJam, 30 bytes Was really hoping to see a CJam answer by now.. So here it goes :P ``` q:Q,{)QW%/(Q+Q@+s}%{,}${_W%=}= ``` I really hate that `{,}$` block in there, but I get an unordered list of possible palindromes due to the generation algorithm I am using. **Code explanation** ``` q:Q,{ }% "Read the input string, store in Q, take length and"; "run the code block that many times"; )QW% "Increment the iteration index and Put reversed Q on stack"; / "Split reversed Q into parts of incremented iteration index"; (Q+ "Take out the first part and prepend it to Q"; Q@+s "Take the rest of the parts and append them to Q"; {,}$ "At this point, we have all possible prepended and appended"; "sequences of the input string. Sort them by length"; {_W%=}= "Take the first sequence which is a palindrome"; ``` [Try it online here](http://cjam.aditsu.net/#code=q%3AQ%2C%7B)QW%25%2F(Q%2BQ%40%2Bs%7D%25%7B%2C%7D%24%7B_W%25%3D%7D%3D&input=3212343) [Answer] ## Python 2, ~~115~~ ~~113~~ ~~109~~ ~~105~~ 96 bytes ``` f=lambda x:[x for x in sum([[x[:~i:-1]+x,x+x[i::-1]]for i in range(len(x))],[])if x==x[::-1]][0] ``` Can hopefully golf down further. Bits possibly worthy of note: * using sum for two list comprehensions in one * constructing terms in sorted order to avoid the need for min (suggested by @Jakube) [Answer] # Mathematica, 96 bytes There must be a more elegant way than this... ``` ""<>#&@@SortBy[r=Reverse;#/.{b___,a__/;r@{a}=={a}}:>{b,r@{b,a}}&/@{r@#,#}&@Characters@#,Length]& ``` This defines an unnamed function which takes a string and returns the result. The basic idea is to * Split the string into `Characters`. * Form an array with this list and its reverse. * Use pattern matching to find the right palindromic of each of them: ``` {b___,a__/;r@{a}=={a}}:>{b,r@{b,a}} ``` Note that this doesn't actually return a flat list. E.g. for `{a,b,c}` you'd get ``` {a,b,{c,b,a}} ``` * Sort the two results by length. * Pick the shorter and join it back into a string with `""<>#&@@`. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (2), 6 bytes, language postdates challenge ``` ~{↔?a} ``` [Try it online!](https://tio.run/nexus/brachylog2#@19X/ahtin1i7f//SslJyYlK/6MA "Brachylog – TIO Nexus") As usual for Brachylog, this is a function, not a full program. ## Explanation ``` ~{↔?a} ~{ } Find a value that produces {the input} upon doing the following: ↔ reversing it; ? asserting that we still have the same value; a and taking either a prefix, or a suffix. ``` As far as I know (it's not my language, but it seems unlikely), `a` wasn't added to Brachylog for this challenge, but it comes in really handy here. We use the "reverse, and assert it hasn't changed" method to assert that the value we find is a palindrome. As for why this produces the *shortest* palindrome, Prolog's (and hence Brachylog's) evaluation order is heavily influenced by the first thing it evaluates. In this case, that's a "reverse" command, and (like most list operations) it sets an evaluation order that aims to minimize the size of the resulting list. As that's the same as the size of the output, the program happily ends up minimizing exactly the right thing by chance, meaning that I didn't need to add any explicit hints. [Answer] # Ruby, 76 + 2 = 78 With command-line flags `-pl` (the `l` may not be needed depending on how you're doing input), run ``` $_=[[$_,r=$_.reverse]*"\0",r+"\0#$_"].min_by{|s|s.sub!(/(.*)\0\1/){$1}.size} ``` Given a string 'abaa', generates the strings 'cbca**0**acbc' and 'acbc**0**cbca', where **0** is the unprintable character with ascii code 0. It then deletes one copy of the longest repeated string framing **0** it finds in each, 'a' in the first and 'cbc' in the second, to get the two closures. It then outputs the shortest result. The only really weird thing about the golfed code is that it shortens the strings in place while sorting them, which we can get away with because `min_by` only executes the block once per element being compared (both because it's a [Schwartzian transform](http://en.wikipedia.org/wiki/Schwartzian_transform) and because there are only two elements to compare). [Answer] # Python 3, 107 bytes --- ``` f=lambda a:[i for i in[a[:i:-1]*j+a+a[-1-i::-1]*(1-j)for i in range(len(a))for j in(0,1)]if i==i[::-1]][-1] ``` To test: ``` >>> print("\n".join(map(f, ["abcdef", "abcba", "abcb", "cbca"]))) abcdefedcba abcba abcba acbca ``` [Answer] # Haskell, 107 bytes ``` import Data.List r=reverse f s=snd$minimum[(length x,x)|x<-map(s++)(tails$r s)++map(++s)(inits$r s),x==r x] ``` Test: ``` *Main> mapM_ (putStrLn.f) ["abcdef", "abcba", "abcb", "cbca"] abcdefedcba abcba abcba acbca ``` [Answer] # J, ~~66~~ 62 bytes ``` 3 :'>({~[:(i.>./)(#%~[-:|.)@>),(<@([,|.@{.~)"#:i.@#"1)y,:|.y' ``` Quite straightforward. The two tricks I use: The right palindromic closure is the left palindromic closure of the reversed string. Finding the length of the string with minimum length and palindromity with the expression min(is\_palindrome / length). ``` f=.3 :'>({~[:(i.>./)(#%~[-:|.)@>),(<@([,|.@{.~)"#:i.@#"1)y,:|.y' f 'lama' lamal ``` [Try it online here.](http://tryj.tk/) ]
[Question] [ Using only [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) (hex codes 20 to 7E), write a square N×N *core* program **without comments** that is surrounded by 4 more *[layers](https://www.youtube.com/watch?v=_bMcXVe8zIs)*, creating a (N+8)×(N+8) square program (N > 0). For N = 3 the layout (to be replaced by actual code) looks like this: ``` 44444444444 43333333334 43222222234 43211111234 4321CCC1234 4321CCC1234 4321CCC1234 43211111234 43222222234 43333333334 44444444444 ``` * The C's represent the core 3×3 program. * The 1`s represent the first layer, the 2's represent the second layer, etc. The program always takes a string of space separated integers such as `0 -1 31 -1 2 2 2` via stdin or similar (it should just be the plain numbers, no quotes or brackets or anything). The output depends on what parts of the layout were run. There are five ways to run the program (newlines are included in the run). Each does something different to the list: 1. Run just the core: ``` CCC CCC CCC ``` This computes the maximum of the absolute values of the input list elements, and prints `CORE` on a new line that many times. If the max is 0 nothing is output (a newline is fine). * The output for `0 -1 31 -1 2 2 2` would be ``` CORE CORE ... ``` 31 times. 2. Run the core with layer 1: ``` 11111 1CCC1 1CCC1 1CCC1 11111 ``` This outputs the average ([arithmetic mean](http://en.wikipedia.org/wiki/Arithmetic_mean)) of the list values to standard floating point precision. * The output for `0 -1 31 -1 2 2 2` would be 35 / 7 = `5` (`5.0` is fine). 3. Run the core with layers 1 and 2: ``` 2222222 2111112 21CCC12 21CCC12 21CCC12 2111112 2222222 ``` This outputs a space separated list of the input list reversed. * The output for `0 -1 31 -1 2 2 2` would be `2 2 2 -1 31 -1 0`. 4. Run the core with layers 1, 2, and 3 (the pattern should be obvious). This outputs a space separated list of the sorted input list. * The output for `0 -1 31 -1 2 2 2` would be `-1 -1 0 2 2 2 31`. 5. Run the core with layers 1, 2, 3, and 4. This outputs a space separated list of the input list with duplicates removed, the ordering doesn't matter. * The output for `0 -1 31 -1 2 2 2` could be `-1 0 2 31`. All output is to stdout or a similar alternative. Only these 5 layout combinations have specified behavior. ### Notes * **Comments are not allowed** in the core or layers or combinations thereof. Code that is a no-op or does nothing constructive does not count as a comment. * Remember that the core can have any (positive) N×N dimensions, but the layers are only one character thick. * You may assume the input has no leading or trailing spaces and exactly one space between numbers. It will always contain at least one number. (The output lists should be formatted like this too.) * You may assume the list and calculations necessary for output won't have values that overflow (or underflow) your integers (as long as their max is something reasonable like 216). # Scoring Writing this program normally would be easy. Writing it with a small core is hard. The program with the smallest core size (the smallest N) wins. In case of ties the winner is the full program (the (N+8)×(N+8) square) with the fewest distinct characters (not counting newlines). Please report your N value at the top of your answer. [Answer] # Python 2 - N = 17, 53 characters Oh I love source-layout challenges with Python... ``` i=4 ; ii=3 ; iii=2 ; iiii=1 ; iiiii=0;R=raw_input ; iiiii;w=R().split() ; iiiii;n=map(int,w) ; iiiii;S=set(n);M=max ; iiiii;s=sorted(n) ; iiiii;J="\n".join ; iiiii;j=" ".join ; iiiii;k=M(map(abs,n)) ; iiiii;A=J(["CORE"]*k) ; iiiii;B=sum(n)/len(n) ; iiiii;C=j(w[::-1]) ; iiiii;D=j(map(str,s)) ; iiiii;E=j(map(str,S)) ; iiiii;P=A,B,C,D,E ; iiiii;print P[i] ; iiiii;" /__----__\ " ; iiiii;"|/ (')(') \| " ; iiii;" \ __ / " ; iii;" ,'--__--'. " ; ii;" / :| \ " ; i;" (_) :| (_) "; ``` There's still some unused whitespace, though. I could still improve the unique character count, but I'll stick with better readability - if there is any at all. **Edit:** Oh, it's Stan [again](https://codegolf.stackexchange.com/a/36602/30372)! [Answer] ## CJam, N = 5, 27 (26) unique characters It's 26 characters if I don't count the spaces. The program could actually be converted to one that doesn't use spaces, by just filling up all empty spaces with no-ops (e.g. `_;` which duplicates the top stack element and then discards, or by sorting the array again and again), but it would just distract from the actual code. ``` l~]_|S* {l~]$S* {l~]W%S* {l~]_,\ {l~]{z }%$W= "CORE "* } ;:+d\/ } ; } ; } ; ``` [Test it here.](http://cjam.aditsu.net/) The core is ``` l~]{z }%$W= "CORE "* ``` (Plus an empty line.) I'm fairly sure that `N = 4` can't be done in CJam (and I'm sure Dennis will convince me otherwise :D). The above has 17 characters, and while it might be possible to get it down to 16 (e.g. if CJam didn't have a bug to choke on `:z`, which requires `{z}%`, or by using ARGV), I don't think you can fit it in the layout without introducing a line break within `CORE`. All of the implementations are very straightforward solutions to the given tasks. All of them start with `l~]` which reads STDIN, evaluates it, and puts it in an array. The previous layer is always surrounded in `{...}`, which makes it a block that isn't automatically executed. And instead of executing it, I just discard it from the stack with `;`, so no layer depends on code in the previous layer. In the Layer 1, the code didn't fit into the first line, so I continued it after discarding the core block. Now for the actual programs: * Core: ``` {z}%$W="CORE "* ``` Map `abs` onto the list, sort it, take the last element, repeat `CORE` (and a line break) that many times. * Layer 1: ``` _,\:+d\/ ``` Duplicate the list, take the length, swap the stack elements, get the sum, cast to `double`, swap the stack elements, divide. I think this can be shorter, but there's no incentive to do so. * Layer 2: ``` W%S* ``` Reverse the array, riffle with spaces. * Layer 3: ``` $S* ``` Sort the array, riffle with spaces. * Layer 4: Duplicate, take set union, riffle with spaces. Some other optimisations are also possible, like reusing the `;` and `*S` of Layer 2, but again, but it doesn't affect the score. [Answer] # Python 3: N=11, 40 distinct characters ``` if 1: if 1: if 1: if 1: p=print;R=0 a=input() b=a.split() m=map;a=abs E=max;l=len n=m(int,b); C=['CORE'] "R=E(m(a,n))" OO=C*R;s=sum "x='\n'.join" "p(x(O)) " "p(s(n)/l(b)) " "p(*b[::-1]) " "p(*sorted(n)) " p(*set(n)) ``` Thanks to @Falko for being my muse. This works, because Python does not create a new scope for each if statement, so the variables persist in the outer `print` statements. One annoying thing was that a `map` object (in our case `n`) can be used only once. So it was necessary to string out the `R=E(...)` line, but then `R` was not defined. Therefore I was lucky that there were four spaces left in the first line! The output can be solved by providing multiple elements `*b[::-1]` instead of the list. The alternative `' '.join(...)` would have been too long. [Answer] # [C (gcc)](https://gcc.gnu.org/), N = 15, 47 unique characters Assumes `sizeof(int) == 4` and `sizeof(int*) >= sizeof(int)`. ``` ; ; ; ; ; ; ; float s;c(a,b)int*a,* b;{b=*b-*a;}i,n ,*f;*q,*R,C,E ; main(a){for(;0< scanf("%i",&a); i=i<abs(a)?a:i, s+=f[n-!0]=a)f= realloc(f,++n*4 );qsort(f,n*C,4 ,c);for(i=q?R?n :!0:i;i--;a=f[i ])!E|n-i<2|a!=f [i]&&printf(q?R ?R:q:"CORE\n",! q+R?f[i]:s/n);} ;*q="%f"; ; ;*R="%.0f "; ; ;C=!0; ; ;E=!0; ; ``` [4 Layers](https://tio.run/##bdFBb8IgFAfwu5@CNtEUClt1O/VJemh6XtKr6@GVjOUljq6tN/Wzd6iRZlFIOPz@8CA8o76NmSZgzwYs2LMA2II9Cbws2P/A7js8sJuzEUyCsuXkDgKlYHdv4dhq0SqBcCbpgkthQfRS1LKU1a3s1X@QXIL8aLshgWwbfDTobBIvKZYr5PN@0rTFdvRHCsxJzvtTbXdORVmjkVsdfPjC/b4ziZVp6sR7cA792A0H706UcnZpOFzeQrov6mJ@fx5lOQEpBegvouANj6qTU7TdnDDSNviOmtXqd/DfYxNfKXhR530elx919eliGQXv07rwdZt8fHUcznf3f6bjpY1hbsu1X6L2/JJZdk@u/YJSRxk89BeqR/bBNGVMrdnb@rJuLvMP "C (gcc) – Try It Online") [3 layers](https://tio.run/##ZdGxboMwEAbgPU9hkBJhc25J2omLxYAyV2JNGQ4rrixRUyBbkmenpjGV2tiSh0@nO@s/LT@0niZkjwdX7JGRrdgfNm1HZzYrG1EnBA237iwIBLtrg5dGiUYKwpsFFxSEQdGDqKCEw0/DWT/JuoT4xXRDgtk@6KjJmSRe2xg2xJdaq@yemtGXF5RbWGpTZY5ORlmtiBsVdDhR23Y6MZCmTrwG5diP3XD26kQJi4LmOM@3qi@qYvlvHmW5RSslkh9gg9Y8OlydtPvdlSJlgh5tvdl8DT4Gk/geQYsq7/O4fKsO7y6GKGifVoXvV@fjs@N4u6tPRsVrE@Nv6F5RVB6fMsMW97vAUkXZvy3hNGVMbtnLdn538/0G "C (gcc) – Try It Online") [2 layers](https://tio.run/##XdCxasMwEAbgPU8hGxIs@dQ6aSdfhIeQueA19XAWUTlI5drOluTZXVkmUCqBho/TfzpZ/WXtNKH4v3Al/qK7dHQVKyFGtBlBK9lfFYESs7V4a41qtSJ8MPhooByqHlQNBzjOUcG@iX1G8ua6IcNiH2205F2WrjmFDcmljg3vqR1DaUUlw1KXG3fyOikaQ9KZaMOZLpfOZg7y3Kv3aBL7sRuuwbw6wGJgJc492fRVXS3vK5OiZGStkUIwR2tkcrx7zfvdnRLjop242Wx@hjCuy8LtaFVd9mV6@KiPnz6FJFqf11XIacrx1Ut8zBbmN@napc9/RLFCVQd6KZx4Kk5TIfRWvG3nczfvXw "C (gcc) – Try It Online") [1 layer](https://tio.run/##RdA9a8MwEAbgPb9CNiRY8ok6aSdfhAeTueA19XAWVTlI5fpjS/Lb3dNQKoGGh/d0Onn75f22ofpf4TbSulML@oJg0BxXQ2DUTg14H5wZrCF8MkQRMAHNBKaDFi4KRb6JY0H6Hsa5wOossniKocj3nMOBdMqw4zMNi8QaqhlSpnThGm1W9Y50cCLzJ91uoy8ClGU0byIap2WcV5FoWkgCXmPqw25quia9p86qmpGtRZILWaTX2eURLZ9PD8pcELlyfzj8zDJWKKROpOnqqc7b9@7yEXPIRKaya6S@r5eXqPGpdjKly/ch//sn3LZK2aN6PabzlPYv "C (gcc) – Try It Online") [Core](https://tio.run/##FY5Ba4QwFITv71eoUEniC3W3e0oMHsRzwevWwzM05cE2VrO33f3tVhkYGJhvGK9/vN@2ZL0gnCTHuyJUMNnH5NSkFdkXYwRUwaoF1YAd9pmFX@IoSD7CvApbN5A8xSCKNy6wJGmBHTc0pb3SkmGEVLlwjTqvR0cyOFi/6XabvQhYVVFdQNolzet9z1F1eAH00h7b7JZ2aCOYvDZsWWtL@xDDKPP@GTU35yflLsCVx7L8W/f7QewEtINZTNF9Dv1XLDCHpRranRtNeo/SvratzvQp@zgdfj70Dw "C (gcc) – Try It Online") [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), ~~N=9~~ N=8, 38 Characters ``` / o/\ \ \S\ " //RiU\ \} @ q " " }+1\r @ } ^U \ {q " \{\?)}\+ } o\/'|A:{:/R' S //r/Ril2=?\?R : ,A~/"OC"/=? { @| \"RE"\3= = D$\' /rqka/l2S? i \*@ il\/ 'R1i Ui ~ R$/Rak U \ ?!D Rlril1-{= R R: }S:{=?\~ ``` [Try it online!](https://tio.run/##TY5BawMhEIXv/opXCSxtGqZuboK4oem54LK3oRBykkhDhJ6M@9e3Y7aHPkXk4828l3@@43lZCFdiQK6IR1YaRCFOKwBXNeCfbtDi@FPdGs4YVJX/17TuKM2xjhb2z5W34hNwZeruB1sshQ6jkpAsMal3nn2AbSOvh5n057sm51EaGO5gHT407x2cwnHDHSjfLidK/egfKRH80grGxNRAF0x8pE8Rs0LYUDhd1rZSUME/HYGQckxmV5wKwoNFHW2RIvOyvGFnsDft7dv5BQ "Runic Enchantments – Try It Online") Turns out [I was wrong](https://codegolf.stackexchange.com/questions/40689/onion-programming#comment425999_40689), I forgot I had an explicit s`o`rt command already, due to having encountered the "sort a list" problem before. This does, however, limit the size of inputs that the final program can take (8 values) due to the internal costs of the sort command. [A slight tweak](https://tio.run/##LY7BasMwDIbvfoq/phC2bqhOWTvCglPWnQcOuYlB2cnUrMSwk@u8eian08GSPyS@P/7@@O95JlyJAabc04rASoPI@UFYKdaqw/8IEEZ0sgEMb/LkjeEIrbLMXwOWkzQiq/t@YvuQeQP0Aq5M1e3YpIZchUaJJIom1K1l65DKydNxIv35rqm1aAvobuJ3H5p3bW8VTmuuQHG8nCnUTIvFgx9LQB8wFVA54xf7IE3BrcmdL/f8ElDBrk6AC9EH85xa5YS7BrlvkgSZ5nkLgxo7bPGCPQ54lZ8RaGDqPw) can increase the input size to 13 at the cost of 1 unique character or to [19](https://tio.run/##LY7LasMwEEX3@oobETBtWiaTNI@aunJosi7IeDcUQlcipsGGrhT5192xU2105zDDud3vT/geBsKVBBBKFc0IYiyIfKiVjU@sKfEfAUKLUjfwXr8pSQuWDtYkzV81ppPYIpn7fhT3kGQBVAquQtntkMecfIbcqKRTTbMqnDiPOJ48HXqynx@WCodiBOVN/f5kZV1UzuA4lwzUtZczNSuhyRIgj2PB0KAfQeY5TPZaPwM/J3@@3PtrQQM3OwK@6ULDz7EwXrnPkao8apF@GJZgrLDGEhtsscNeJ1bIYA0v4A14C96B9@DXPw) for two unique characters (all additional characters are on Layer 1 and added at the same time, but the increased capacity of the IP's stack isn't needed until Layer 3, as C, L1, and L2 can perform their calculations without holding the entire input in memory). Core: [Try it online!](https://tio.run/##KyrNy0z@/z8uVCFGAQi4FGKqY@w1a2O49NVrHK2qrfS59IMyc4xs7WO4HOv0lfydlfS5avRilIJclWK41PX0iwqzE/W5MvVitByA2v//N1DQNVQwNgSRRiAIAA "Runic Enchantments – Try It Online") Layer 1: [Try it online!](https://tio.run/##HY2xCsIwGIT3/ymOLEGr/KbdCqUt4iwEuh2COAWLYMApra8eTe/gg1u@i59XeOSMLWvlKLhNYFlJACb2u5WVUO0ytqlVL1F9mOuuZy@H8avmejbaybCAxl8MG6GFxvfzrrMggPvhLwtivQvby5TzCUeHxhXWpT8 "Runic Enchantments – Try It Online") Layer 2: [Try it online!](https://tio.run/##JU5NC4MwFLu/XxGKUDY33qo3QaqMnQcFb4@B7FQUh4Wd1P31zo8EAiGQJHwH/44ROwRgjHQYLKmRsJpXswXAtCcyiT0tkoI@wnqui6lgp4kDO99npRXrCJf6x@p5V1xaQjVDlHsoyUtKRIPD2LXcZ2ubh5yrtdT3BO2M33cbTwm7tjteNDHecDXIzabZxj8 "Runic Enchantments – Try It Online") Layer 3: [Try it online!](https://tio.run/##TY5BC4JAEIXv@yteIkiZTKs3QVbJzsGGtyGQTotL4UIntb9urkX0Bmb4mMfjuefd3OYZRNo0jFUs8KceP5xiyW7Fa4PVPHy/PLDaThxjwQdTNFb5kJOOIIjcEm3TQrHS3ryvXhScjwEVymM5ggN9CjgrIOqQI5Dru5ZsevHJBrwr/bW@VaSlWZs0BkKHpNvu06yBUJsa0NYZK5OhmOcDEolM@p36eQM "Runic Enchantments – Try It Online") Layer 4: [Try it online!](https://tio.run/##TY5BawMhEIXv/opXCSxtGqZuboK4oem54LK3oRBykkhDhJ6M@9e3Y7aHPkXk4828l3@@43lZCFdiQK6IR1YaRCFOKwBXNeCfbtDi@FPdGs4YVJX/17TuKM2xjhb2z5W34hNwZeruB1sshQ6jkpAsMal3nn2AbSOvh5n057sm51EaGO5gHT407x2cwnHDHSjfLidK/egfKRH80grGxNRAF0x8pE8Rs0LYUDhd1rZSUME/HYGQckxmV5wKwoNFHW2RIvOyvGFnsDft7dv5BQ "Runic Enchantments – Try It Online") Further compression is highly unlikely, due to the smaller space necessitating an increase in the number of flow control characters. I found an arrangement that gave 9 empty spaces in the core program, but that is not enough, as we need (a correctly arranged) 15. Explaining how any of these programs work is difficult without a visual map of the path the IP takes, which is cumbersome and time consuming to construct. The initial entry point is the upper left corner of the Core program (`^`) which allows for consistent flow control as new layers are added, as each layer has an opportunity to intercept on the newly added line at the top or the bottom. Layers 1 and 2 intercept at the bottom (so that the top line remains empty for future layers) and then perform their operations along the right hand edge (a loop arranged vertically). Layer 1 is slightly too long and takes 3 characters along the top edge as well, but the diagonal reflector (`\`) in the top right realigns the IP with the next loop iteration. Layer 3 intercepts along the top edge in order to grab the first input value before redirecting to the bottom edge (Layer 4 leaves a NOP in this column on its bottom line) and reads the full input using the bottom edge loop, redirecting on the Down command (`D`) in the lower left. From there the IP bounces a few times before ending up in an output (`$`) loop in the lower left in order to space-separate the values. Layer 4 utilizes all of the functionality of layer 3 (hence the blank space), but intercepts on its own new top edge (upper left) in order to perform its own functionality at the end of Layer 3's processing. The top left corner inserts a string `"@"` which is used to denote the end of the array before entering the processing loop along the bottom. If a duplicate value is found, it's popped (`~`, lower right corner) otherwise the branch is taken that consumes the new right hand edge. This side branch checks to see if the end of the array has been reached, and if so, break out and head to the same space-separated output loop from Layer 3. Otherwise use the blank space on Layer 3 to return back to the main loop. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~N=14, C=44~~ N=13, C=40 ``` (s,a=s.split ` `)=>[[`CORE `.repeat(Math .max(...a.map (Math.abs)))] ,a.reverse(), [a.reduce((i, j)=>i- -j,2-2 )/a.length],[ ...new Set(a) ],[...a].sort ((i,j)=>i-j)] [[[[[2-2].join` ` - -2].join` ` -2/2].join` ` - -2-2/-2].join` ` -2/2].join` ` ``` [Try it online!](https://tio.run/##1ZPNbpwwEMfvPMWIk50Fk6WtKoVuLlWPVaVUPQESruPsGhFDbUNXW/XZt2M7UbKofYAahOE3X/Z/TM8XboVRk8v1eC/PD7MWTo0aJjM@To5Q@JWAkW42AQlpLeNmv9RlWyW/k@LqnOAAHMRmfGeZnQblAuigo7vbuu4@frn7FAkzcpLckc/cHQJhj/xIGGMcX6aYxtsY/24ppW0gGcewRRorCc0CqT25n4UkREXSYyWVQ95nZV4GQgvOBqn37tBmdazFmJY/4at0hNNA0OJrt8yOJq7ZJ4y5eqxe@4EJW9aPSuN@vA9WuQB5Wbz@9mZEr30uPM5XRbJwAwLVhh1a/yVf0@EdBGxeFGz@bwnDni5FfEYvIj2RlZCRrry6KnkYDRAv6AnVvK5w@gDvcNpswtENUqPFyx3F7RrdeanIEXa3cGR2UKjCW6x3ymD7HjZwovSvNLYQw6sE82k7DpIN454IugJpo@@knQd3k65NcuEDBpD0GvItvNn6Z@mvlK5dqf/BLtJ@0@rHLEEcuOHCYTtv0gyeG@L7IPzpGDiuvGh0sc8gTWmLm1EnSavzHw "JavaScript (Node.js) – Try It Online") # JavaScript (Browsers), N=15, C=52 Full program. The TIO uses `process.argv[2]` for `prompt()` ``` (r=4)?r: (r=3)?r: (r=2)?r: (r=1)?r: r=0;p=prompt(). split` `;m=p. reduce((i,j)=>i - -j)/p.length v=p.reverse(). join` `;t=[...p ].sort((i,j)=>i -j).join` `;s =new Set(p); console.log( ((((r==0?Array(Math .max(...p.map( Math.abs))) .fill(`CORE`) .join`\n`:``) + (r==1?m:``)) + (r==2?v:``)) + (r==3?t:``)) + [...s].join` `) ``` [Try it online!](https://tio.run/##vZRNj9owEEDv@RUjTvYChsD20KReVFU9VpW26mmDZDcY1ig4rm1SStXfntoOafnooYdVEykePQ8Tj5/DljfclkZqN1b1SrTrvSqdrBVoU@@0Qxh@JGCE25uISmEt4WbTPM2WefIzmdy1yNB7vDBZAj6ad1EIZ6cwxGkfg6HTXNO@OInM6ko6BizfUd0RI1b7UiAkR1tMH2RkYxhv8USTSqiNe46o8flGNMJY0dfa1lKFUo4@EUJ0ZEtia@Ouqm0x6XNtJFSJb/BJOKRxHkFZK1tXglT1BiXIX4bS6eKtMfw7@sBPSyA7fkDhTT7QKKIwR/gXizHuUtayqhB79/HxPTuR@OZCsYwxDDA87RJNF7tAcMiJNMDZovkDIw50vnDnNPDQsF32XeH2bpI03Pg2VgIosBfyVDAoXsxUV@xfXXXZ/8VWEXUV574KVhT@kfnxRlpkt9rO8IW4C36lLjaJWZ6sawMoCDx6e9PcD2/glR@Gw/hNRrV@Jugl3RfkD1Ts6wD0AQ7EVtKbufc6jiNIX8MQjhj/lf4@j34rz/exxFdgUKhHYfeVywZhSjS8uk3C4Y/h4leflfy6F1A@c8NL5w9BNhhBLzD0XvrDoSvuFzYp1GQzgsEAL/1a5VHgvG2nME5hnobnLNy/AA "JavaScript (Node.js) – Try It Online") [Answer] # [TlanG](https://github.com/tuddydevelopment/TlanG) 177 bytes N=4 (\*3) ``` ############ ############ ############ ####CORE#### ####||||#### ####CORE#### ############ ############ ############ ``` prints `CORE` Explaination on the github linked in title Not quite the requested but i think its fine! ]
[Question] [ [Hole #1](https://codegolf.stackexchange.com/questions/39748/9-holes-of-code-golf-kickoff?lq=1) Joe the snake is hungry. He eats pictures, one pixel at a time. He really likes bright pixels. ## The Challenge Program Joe to eat the most bright pixels he can find, given that he can only move up, down, left or right. ## Specifications * Joe must start at the upper left pixel of the image. * Joe can only move horizontally or vertically by 1 each move * Joe has only enough time to move 1/3 of the amount of pixels in the picture (1/3 as many moves as pixels). If the number of pixels is not a multiple of 3, round down to the nearest integer. * Joe may cross his path, though that counts as 0 brightness * Brightness is based on the sum of r,g and b, so rgb(0,0,0) has a brightness of 0 while rgb(255,255,255) has maximum brightness. ## Input You may input the image however you like. ## Output * an image showing the end result of your picture (with black being eaten pixels). * The amount of brightness eaten (please specify what range in your answer) ## Scoring Your program will be graded on: * The average brightness of pixels Joe eats / The average brightness of the pixels in the picture\* \*you may hardcode this in your program Your total score will be the average of the scores for the following images: Test images: ![enter image description here](https://i.stack.imgur.com/k1mvc.jpg) [![enter image description here](https://i.stack.imgur.com/ApAtk.png)](http://upload.wikimedia.org/wikipedia/commons/a/ae/BallsRender.png) <http://upload.wikimedia.org/wikipedia/en/thumb/f/f4/The_Scream.jpg/800px-The_Scream.jpg> [![enter image description here](https://i.stack.imgur.com/rRwZo.jpg)](http://upload.wikimedia.org/wikipedia/commons/b/b5/Mandel_zoom_04_seehorse_tail.jpg) [![enter image description here](https://i.stack.imgur.com/E1qUE.jpg)](http://upload.wikimedia.org/wikipedia/commons/0/0c/Red_Vortex_Apophysis_Fractal_Flame.jpg) ![enter image description here](https://i.stack.imgur.com/Ib5UL.jpg) [Answer] # C++, Score: ~~1.42042~~ 1.46766 This is essentially a slightly more sophisticated version of the two existing solutions: Of the four possible moves, it selects the one that maximizes brightness. However, instead of only looking at the brightness of the target pixel, it looks at the weighted sum of pixel-brightness in the neighborhood of the target pixel, where pixels closer to the target have a greater weight. **EDIT:** Using nonlinear brightness in neighborhood calculation improves the score slightly. Compile with `g++ joe.cpp -ojoe -std=c++11 -O3 -lcairo`. Requires cairo. Run with `joe <image-file> [<radius>]`. `<image-file>` is the input PNG image. `<radius>` (optional argument) is the radius of the summed-over neighborhood, in pixels (smaller is faster, larger is (roughly) better.) Outputs the score and an image named `out.<image-file>`. ``` #include <cairo/cairo.h> #include <iostream> #include <iterator> #include <algorithm> #include <string> using namespace std; int main(int argc, const char* argv[]) { auto* img = cairo_image_surface_create_from_png(argv[1]); int width = cairo_image_surface_get_width(img), height = cairo_image_surface_get_height(img), stride = cairo_image_surface_get_stride(img); unsigned char* data = cairo_image_surface_get_data(img); double* brightness = new double[width * height]; double total_brightness = 0; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { const unsigned char* p = data + stride * y + 4 * x; total_brightness += brightness[y * width + x] = p[0] + p[1] + p[2]; } } const int r = argc > 2 ? stoi(argv[2]) : 64, R = 2 * r + 1; double* weight = new double[R * R]; for (int y = -r; y <= r; ++y) { for (int x = -r; x <= r; ++x) weight[R * (y + r) + (x + r)] = 1.0 / (x*x + y*y + 1); } auto neighborhood = [&] (int x, int y) { double b = 0; int x1 = max(x - r, 0), x2 = min(x + r, width - 1); int y1 = max(y - r, 0), y2 = min(y + r, height - 1); for (int v = y1; v <= y2; ++v) { const double *B = brightness + width * v + x1; const double *W = weight + R * (v - (y - r)) + (x1 - (x - r)); for (int u = x1; u <= x2; ++u, ++B, ++W) b += (*W) * (*B) * (*B); } return b; }; int n = (2 * width * height + 3) / 6; int x = 0, y = 0; double path_brightness = 0; int O[][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; for (int i = 0; i < n; ++i) { if (i % 1000 == 0) cerr << (200 * i + n) / (2 * n) << "%\r"; path_brightness += brightness[width * y + x]; brightness[width * y + x] = 0; unsigned char* p = data + stride * y + 4 * x; p[0] = p[1] = 16 * i % 255; p[2] = 0; auto O_end = partition(begin(O), end(O), [&] (const int* o) { return x + o[0] >= 0 && x + o[0] < width && y + o[1] >= 0 && y + o[1] < height; }); const int* o_max; double o_max_neighborhood = -1; for (auto o = O; o != O_end; ++o) { double o_neighborhood = neighborhood(x + (*o)[0], y + (*o)[1]); if (o_neighborhood > o_max_neighborhood) o_max = *o, o_max_neighborhood = o_neighborhood; } x += o_max[0]; y += o_max[1]; } cout << (path_brightness * width * height) / (n * total_brightness) << endl; cairo_surface_write_to_png(img, (string("out.") + argv[1]).c_str()); delete []brightness; delete []weight; cairo_surface_destroy(img); } ``` ## Results ``` Bridge 1.39945 Balls 1.77714 Scream 1.38349 Fractal 1.31727 Vortex 1.66493 Tornado 1.26366 ----------------- Average 1.46766 ``` ![Bridge](https://i.stack.imgur.com/pQZkc.jpg) ![Balls](https://i.stack.imgur.com/Dd1F8.jpg) ![Scream](https://i.stack.imgur.com/HicAt.jpg) ![Fractal](https://i.stack.imgur.com/caUpQ.jpg) ![Vortex](https://i.stack.imgur.com/nZwMA.jpg) ![Tornado](https://i.stack.imgur.com/tp2qu.png) ## More eye-candy ![Vortex animation](https://i.stack.imgur.com/Ye5ZQ.gif) ![Tornado animation](https://i.stack.imgur.com/vyeq5.gif) [Answer] # Python 3, score = 1.57 First our snake travels the image creating vertical lines with equal distance from each other. ![a](https://i.stack.imgur.com/PNLo0.jpg) We can extend this snake by taking two points next to each other in a vertical line and creating a loop whose endpoints are them. ``` | | | => +----+ | +----+ | | ``` We organize the points into pairs and for every pair we store the size and average brightness value of the loop which gives has the greatest average brightness. At every step we choose the pair with highest value extend its loop to achieve maximum average brightness on the extension and calculate the new optimal loop size and brightness value for the pair. We store the (value,size,point\_pair) triplets in a heap structure sorted by value so we can remove the biggest element (in O(1)) and add the new modified one (in O(log n)) efficiently. We stop when we reachg the pixel count limit and that snake will be the final snake. The distance between the vertical lines has very little effect in the results so a constant 40 pixel was choosen. ## Results ``` swirl 1.33084397946 chaos 1.76585674741 fractal 1.49085737611 bridge 1.42603926741 balls 1.92235115238 scream 1.48603818637 ---------------------- average 1.57033111819 ``` ![a](https://i.stack.imgur.com/iX7BT.jpg) ![a](https://i.stack.imgur.com/FOTht.jpg) ![a](https://i.stack.imgur.com/9Irwv.jpg) ![a](https://i.stack.imgur.com/zIzPt.jpg) ![a](https://i.stack.imgur.com/KG7nI.jpg) ![a](https://i.stack.imgur.com/u1by4.jpg) *Note: the original "The Scream" picture was not available so I used an other "The Scream" picture with similar resolution.* Gif showing the snake extending process on the "swirl" image: ![a](https://i.stack.imgur.com/w4gRH.gif) The code takes one (or more space separated) filename(s) from stdin and writes the resulting snake images to png files and prints the scores to stdout. ``` from PIL import Image import numpy as np import heapq as hq def upd_sp(p,st): vs,c=0,0 mv,mp=-1,0 for i in range(st,gap): if p[1]+i<h: vs+=v[p[0],p[1]+i]+v[p[0]+1,p[1]+i] c+=2 if vs/c>mv: mv=vs/c mp=i return (-mv,mp) mrl=[] bf=input().split() for bfe in bf: mr,mg=0,0 for gap in range(40,90,1500): im=Image.open(bfe) im_d=np.asarray(im).astype(int) v=im_d[:,:,0]+im_d[:,:,1]+im_d[:,:,2] w,h=v.shape fp=[] sp=[] x,y=0,0 d=1 go=True while go: if 0<=x+2*d<w: fp+=[(x,y)] fp+=[(x+d,y)] sp+=[(x-(d<0),y)] x+=2*d continue if y+gap<h: for k in range(gap): fp+=[(x,y+k)] y+=gap d=-d continue go=False sh=[] px=im.load() pl=[] for p in fp: pl+=[v[p[0],p[1]]] px[p[1],p[0]]=(0,127,0) for p in sp: mv,mp=upd_sp(p,1) if mv<=0: hq.heappush(sh,(mv,1,mp+1,p)) empty=False pleft=h*w//3 pleft-=len(fp) while pleft>gap*2 and not empty: if len(sh)>0: es,eb,ee,p=hq.heappop(sh) else: empty=True pleft-=(ee-eb)*2 mv,mp=upd_sp(p,ee) if mv<=0: hq.heappush(sh,(mv,ee,mp+1,p)) for o in range(eb,ee): pl+=[v[p[0],p[1]+o]] pl+=[v[p[0]+1,p[1]+o]] px[p[1]+o,p[0]]=(0,127,0) px[p[1]+o,p[0]+1]=(0,127,0) pl+=[0]*pleft sb=sum(pl)/len(pl) ob=np.sum(v)/(h*w) im.save(bfe[:-4]+'snaked.png') if sb/ob>mr: mr=sb/ob mg=gap print(bfe,mr) mrl+=[mr] print(sum(mrl)/len(mrl)) ``` [Answer] # Python 2 (score: 0.0797116) Just a very simple and naïve greedy algorithm to get the ball rolling. ``` #!/usr/bin/python from PIL import Image OFFSETS = [(-1, 0), (0, -1), (1, 0), (0, 1)] def test_img(filename): img = Image.open(filename) joe, eaten = (0, 0), [] img_w, img_h = img.size all_pixels = [ sum(img.getpixel((x, y))) for x in xrange(img_w) for y in xrange(img_h) ] total_brightness = float(sum(all_pixels)) / len(all_pixels) for _ in xrange(0, (img_w*img_h)/3): max_offset, max_brightness = (0, 0), 0 for o in OFFSETS: try: brightness = sum(img.getpixel((joe[0] + o[0], joe[1] + o[1]))) except IndexError: brightness = -1 if brightness >= max_brightness: max_offset = o max_brightness = brightness joe = (joe[0] + max_offset[0], joe[1] + max_offset[1]) eaten.append(max_brightness) img.putpixel(joe, (0, 0, 0)) eaten_brightness = float(sum(eaten)) / len(eaten) print('%d of %d (score %f)' % (eaten_brightness, total_brightness, eaten_brightness / total_brightness)) img.show() test_img('img0.jpg') test_img('img1.png') test_img('img2.jpg') test_img('img3.jpg') test_img('img4.jpg') ``` Output: ``` llama@llama:~/Code/python/ppcg40069hungrysnake$ ./hungrysnake.py 15 of 260 (score 0.060699) 9 of 132 (score 0.074200) 16 of 300 (score 0.055557) 4 of 369 (score 0.010836) 79 of 400 (score 0.197266) ``` [Answer] ## Java (score: 0.6949) A simple algorithm which eats the brightest pixel out of the four pixels surrounding the current pixel. In the case of a tie, the pixel eaten is random, leading to differing scores and resulting images each execution. As such, the scores below are the averages over 50 executions on each image. To run it, either edit the three arguments (existing as class constants) in the source, or pass them via command line in the form `java HungryImageSnake <source> <iterations> <printScores>` where `<source>` is the source file of the image to eat, `<iterations>` is the number of times to eat the image (taking the average score and saving the best score over all iterations), and `<printScores>` is true to print each iteration's score or false to not. ``` import javax.imageio.ImageIO; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; public class HungryImageSnake { private static final String SOURCE = "tornado.jpg"; private static final int ITERATIONS = 50; private static final boolean PRINT_SCORES = true; public static void main(String[] args) { try { String source = args.length > 0 ? args[0] : SOURCE; int iterations = args.length > 1 ? Integer.parseInt(args[1]) : ITERATIONS; boolean printScores = args.length > 2 ? Boolean.parseBoolean(args[2]) : PRINT_SCORES; System.out.printf("Reading '%s'...%n", source); System.out.printf("Performing %d meals...%n", iterations); BufferedImage image = ImageIO.read(new File(source)); double totalScore = 0; double bestScore = 0; BufferedImage bestImage = null; for (int i = 0; i < iterations; i++) { HungryImageSnake snake = new HungryImageSnake(image); while (snake.isHungry()) { snake.eat(); } double score = snake.getScore(); if (printScores) { System.out.printf(" %d: score of %.4f%n", i + 1, score); } totalScore += score; if (bestImage == null || score > bestScore) { bestScore = score; bestImage = snake.getImage(); } } System.out.printf("Average score: %.4f%n", totalScore / iterations); String formattedScore = String.format("%.4f", bestScore); String output = source.replaceFirst("^(.*?)(\\.[^.]+)?$", "$1-b" + formattedScore + "$2"); ImageIO.write(bestImage, source.substring(source.lastIndexOf('.') + 1), new File(output)); System.out.printf("Wrote best image (score: %s) to '%s'.%n", bestScore, output); } catch (IOException e) { e.printStackTrace(); } } private int x; private int y; private int movesLeft; private int maximumMoves; private double eatenAverageBrightness; private double originalAverageBrightness; private BufferedImage image; public HungryImageSnake(BufferedImage image) { this.image = copyImage(image); int size = image.getWidth() * image.getHeight(); this.maximumMoves = size / 3; this.movesLeft = this.maximumMoves; int totalBrightness = 0; for (int x = 0; x < image.getWidth(); x++) { for (int y = 0; y < image.getHeight(); y++) { totalBrightness += getBrightnessAt(x, y); } } this.originalAverageBrightness = totalBrightness / (double) size; } public BufferedImage getImage() { return image; } public double getEatenAverageBrightness() { return eatenAverageBrightness; } public double getOriginalAverageBrightness() { return originalAverageBrightness; } public double getScore() { return eatenAverageBrightness / originalAverageBrightness; } public boolean isHungry() { return movesLeft > 0; } public void eat() { if (!isHungry()) { return; } int[][] options = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; shuffleArray(options); // prevent snake from getting stuck in corners int[] bestOption = null; int bestBrightness = 0; for (int[] option : options) { int optionX = this.x + option[0]; int optionY = this.y + option[1]; if (exists(optionX, optionY)) { int brightness = getBrightnessAt(optionX, optionY); if (bestOption == null || brightness > bestBrightness) { bestOption = new int[]{ optionX, optionY }; bestBrightness = brightness; } } } image.setRGB(bestOption[0], bestOption[1], 0); this.movesLeft--; this.x = bestOption[0]; this.y = bestOption[1]; this.eatenAverageBrightness += bestBrightness / (double) maximumMoves; } private boolean exists(int x, int y) { return x >= 0 && x < image.getWidth() && y >= 0 && y < image.getHeight(); } private int getBrightnessAt(int x, int y) { int rgb = image.getRGB(x, y); int r = (rgb >> 16) & 0xFF; int g = (rgb >> 8) & 0xFF; int b = rgb & 0xFF; return r + g + b; } private static <T> void shuffleArray(T[] array) { Random random = new Random(); for (int i = array.length - 1; i > 0; i--) { int index = random.nextInt(i + 1); T temp = array[index]; array[index] = array[i]; array[i] = temp; } } private static BufferedImage copyImage(BufferedImage source){ BufferedImage b = new BufferedImage(source.getWidth(), source.getHeight(), source.getType()); Graphics g = b.getGraphics(); g.drawImage(source, 0, 0, null); g.dispose(); return b; } } ``` Average scores, by image, over fifty iterations: ``` Bridge - 0.7739 Spheres - 0.5580 Scream - 0.8197 Fractal - 0.3850 Vortex - 0.9158 Tornado - 0.7172 ``` Best scores, by image, over the same fifty iterations: ``` Bridge - 0.8996 Spheres - 0.8741 Scream - 0.9183 Fractal - 0.5720 Vortex - 1.1520 Tornado - 0.9281 ``` The highest scoring runs' images: ![Bridge - 0.8996](https://i.stack.imgur.com/pwoPr.jpg) ![Spheres - 0.8741](https://i.stack.imgur.com/Niji0.jpg) ![Scream - 0.9183](https://i.stack.imgur.com/cqbst.jpg) ![Fractal - 0.5720](https://i.stack.imgur.com/KhYsj.jpg) ![Vortex - 1.1520](https://i.stack.imgur.com/IhRPu.jpg) ![Tornado - 0.9281](https://i.stack.imgur.com/1ZlMH.jpg) As is evident from the images, far less than a third of the pixels are actually eaten, as the snake occasionally gets stuck among pixels it has already eaten, at which it remains stuck within the dead area until the randomness of its movements bring it to an edible portion of the image. Also as a result of the snake re-eating pixels, the scores are biased downward, as the zero-brightness of the dead pixels is again factored into the average. I would expect to see far higher scores if the scoring algorithm was modified to only divide by the number of moves that led to eating new pixels, rather than all moves (including those where the snake eats a now-dead pixel that it has eaten before). Of course, a better approach would be to create some sort of brightness heuristic for each pixel and find the path of `width * height / 3` pixels with the highest average brightness, but I doubt this approach will be optimal in run time, especially on larger images, as the number of possible permutations would be very large. I may take a shot at some form of this approach later and post it in a separate answer if so. [Answer] # Python 2, Score: 1.205 I put together a quick Python solution some time ago but forgot to post it. Here it is. It finds the richest blocks in the image, then travels to each block, eating all the best blocks it comes to. ### Results ``` bridge.jpg: 591.97866/515.41501 = 1.14855 BallsRender.png: 493.24711/387.80635 = 1.27189 Mandel_zoom_04_seehorse_tail.jpg: 792.23990/624.60579 = 1.26838 Red_Vortex_Apophysis_Fractal_Flame.jpg: 368.26121/323.08463 = 1.13983 The_Scream.jpg: 687.18565/555.05221 = 1.23806 swirl.jpg: 762.89469/655.73767 = 1.16341 AVERAGE 1.205 ``` ### Example Picture ![Processed bridge picture](https://i.stack.imgur.com/0O9G6.jpg) ### Python 2.7 Code ``` from pygame.locals import * import pygame, sys, random fn = sys.argv[1] screen = pygame.display.set_mode((1900,1000)) pic = pygame.image.load(fn) pic.convert() W,H = pic.get_size() enough = W*H/3 screen.blit(pic, (0,0)) ORTH = [(-1,0), (1,0), (0,-1), (0,1)] def orth(p): return [(p[0]+dx, p[1]+dy) for dx,dy in ORTH] def look(p): x,y = p if 0 <= x < W and 0 <= y < H: return sum(pic.get_at(p)) else: return -1 # index picture locs = [(x,y) for x in range(W) for y in range(H)] grid = dict( (p,sum(pic.get_at(p))) for p in locs ) rank = sorted( grid.values() ) median = rank[ len(rank)/2 ] dark = dict( (k,v) for k,v in grid if v < median ) good = dict( (k,v) for k,v in grid if v > median ) pictotal = sum(rank) picavg = 1.0 * pictotal/(W*H) print('Indexed') # compute zone values: block = 16 xblocks, yblocks = (W-1)/block, (H-1)/block zones = dict( ((zx,zy),0) for zx in range(xblocks) for zy in range(yblocks) ) for x,y in locs: div = (x/block, y/block) if div in zones: colsum = sum( pic.get_at((x,y)) ) zones[div] += colsum # choose best zones: zonelist = sorted( (v,k) for k,v in zones.items() ) cut = int(xblocks * yblocks * 0.33) bestzones = dict( (k,v) for v,k in zonelist[-cut:] ) # make segment paths: segdrop = [(0,1)] * (block-1) segpass = [(1,0)] * block segloop = [(0,-1)] * (block-1) + [(1,0)] + [(0,1)] * (block-1) segeat = ( segloop+[(1,0)] ) * (block/2) segshort = [(1,0)] * 2 + ( segloop+[(1,0)] ) * (block/2 - 1) def segtopath(path, seg, xdir): for dx,dy in seg: x,y = path[-1] newloc = (x+dx*xdir, y+dy) path.append(newloc) # design good path: xdir = 1 path = [(0,0)] segtopath(path, segdrop, xdir) shortzone = True while True: x,y = path[-1] zone = (x/block, y/block) if zone in bestzones: if shortzone: seg = segshort else: seg = segeat else: seg = segpass segtopath(path, seg, xdir) shortzone = False # check end of x block run: x,y = path[-1] zone = (x/block, y/block) if not ( 0 <= x < xblocks*block ): del path[-1] segtopath(path, segdrop, xdir) shortzone = True xdir = xdir * -1 if len(path) > enough: break print('Path Found') # show path on picture: loc = path.pop(0) eaten = 1 joetotal = grid[loc] i = 0 while eaten <= enough: loc = path[i] i += 1 pic.set_at(loc, (0,0,0)) joetotal += grid[loc] eaten += 1 if i % 1000 == 0: screen.blit(pic, (0,0)) pygame.display.flip() for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) # save picture and wait: screen.blit(pic, (0,0)) pygame.display.flip() pygame.image.save(pic, 'output/'+fn) joeavg = 1.0 * joetotal/eaten print '%s: %7.5f/%7.5f = %7.5f' % (fn, joeavg, picavg, joeavg/picavg) while True: for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) ``` ]
[Question] [ [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) is the standard that defines all the country codes. The well-known two-letter codes (US, GB, JP, etc.) are called Alpha-2 codes. With two letters, there are only 262 = 676 possible codes, which can be nicely arranged in a grid. [This table](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Decoding_table) can be useful as an overview, to see which codes are actually in use, reserved, etc. This challenge is simple: you're to print all *assigned* codes of this grid to STDOUT, using plain ASCII, exactly as shown below: ``` AA AC AD AE AF AG AI AL AM AN AO AP AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BU BV BW BX BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CP CR CS CU CV CW CX CY CZ DE DG DJ DK DM DO DY DZ EA EC EE EF EG EH EM EP ER ES ET EU EV EW FI FJ FK FL FM FO FR FX GA GB GC GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU IB IC ID IE IL IM IN IO IQ IR IS IT IU IV IW IX IY IZ JA JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LF LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NT NU NZ OA OM PA PE PF PG PH PI PK PL PM PN PR PS PT PW PY QA QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ RA RB RC RE RH RI RL RM RN RO RP RS RU RW SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO SR SS ST SU SV SX SY SZ TA TC TD TF TG TH TJ TK TL TM TN TO TP TR TT TV TW TZ UA UG UK UM US UY UZ VA VC VE VG VI VN VU WF WL WO WS WV XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ YE YT YU YV ZA ZM ZR ZW ZZ ``` (If I made any mistakes copying it down, the table here in this post is normative for the challenge, not the one on Wikipedia.) You may or may not use trailing whitespace in each line which doesn't contain the `*Z` code, but not beyond the 77th character in that line (i.e., at most, you can make it a rectangular block, ending in `Z`s and spaces). Also, you may or may not use a single trailing new line at the end. This is code golf, so the shortest answer (in bytes) wins. [Answer] # Python 2, 240 bytes Straightforward binary encoding implementation. ``` R=range(26) print"\n".join(" ".join(chr(65+r)+chr(65+c)if int("8hfxckgq1olihfa47x3rrdkojzkklec7qk1hp4ht6avmzxfg7c4uv14xe0pzvvg93x81ag2bf88v2w0p3p08g8nwtuktbwosj9dytset3qmhdl72v5u62nepapgabdqqu7x",36)&1<<c+r*26 else" "for c in R)for r in R) ``` The script for generating the integer is quick and dirty: ``` codes="""AA AC AD AE AF AG AI AL AM AN AO AP AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BU BV BW BX BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CP CR CS CU CV CW CX CY CZ DE DG DJ DK DM DO DY DZ EA EC EE EF EG EH EM EP ER ES ET EU EV EW FI FJ FK FL FM FO FR FX GA GB GC GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU IB IC ID IE IL IM IN IO IQ IR IS IT IU IV IW IX IY IZ JA JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LF LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NT NU NZ OA OM PA PE PF PG PH PI PK PL PM PN PR PS PT PW PY QA QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ RA RB RC RE RH RI RL RM RN RO RP RS RU RW SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO SR SS ST SU SV SX SY SZ TA TC TD TF TG TH TJ TK TL TM TN TO TP TR TT TV TW TZ UA UG UK UM US UY UZ VA VC VE VG VI VN VU WF WL WO WS WV XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ YE YT YU YV ZA ZM ZR ZW ZZ """ n = sum(1 << (x/3) for x in range(0, len(codes), 3) if codes[x] != " ") def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"): return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b]) print baseN(n, 36) ``` [Answer] # CJam, ~~125~~ ~~122~~ 121 bytes ``` "^Kéÿ·^?{ÿ·¿oÂ^Ú^À:ð^×à^Cé^Dÿ^Ýú^À^K^V^G^Áïþ ,^@^K^ÍBù(^_+óÿþºMa^À^H^@#ï^\¨^@ÿÿ¦|¨ÿþ}íßÕ^Ø\"^Â^Nª^P ^D^R$?ÿÿð^À^AÂ^@!^I"256b2b'[,65>_m*]z{~S2*?}%26/Sf*N* ``` The above uses caret notation for control characters. Printable version (**141 bytes**) for the [online interpreter](http://cjam.aditsu.net/ "CJam interpreter"): ``` "J`ki4#'Tr{$V!AcG)\d6o+rW97;#1|jN!WXL%GRuqYos0xCaaBzYgN97DOA'f@#@k'867BrCc1h?&d0LBq[st0YW^?b2Jfx.&gG:O(&"31f-95b2b'[,65>_m*]z{~S2*?}%26/Sf*N* ``` --- ### Example run ``` $ base64 -d > cc.cjam <<< Igvp/7d/e/+3v2/CmoA68JfgA+kE/536gAsWB4Hv/iAsAAuNQvkoHyvz//66TWGACAAj7xyoAP//pnyo//597d/VmFwigg6qECAEEiQ////wgAHCACEJIjI1NmIyYidbLDY1Pl9tKl16e35TMio/fSUyNi9TZipOKg== $ LANG=en_US cjam cc.cjam AA AC AD AE AF AG AI AL AM AN AO AP AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BU BV BW BX BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CP CR CS CU CV CW CX CY CZ DE DG DJ DK DM DO DY DZ EA EC EE EF EG EH EM EP ER ES ET EU EV EW FI FJ FK FL FM FO FR FX GA GB GC GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU IB IC ID IE IL IM IN IO IQ IR IS IT IU IV IW IX IY IZ JA JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LF LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NT NU NZ OA OM PA PE PF PG PH PI PK PL PM PN PR PS PT PW PY QA QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ RA RB RC RE RH RI RL RM RN RO RP RS RU RW SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO SR SS ST SU SV SX SY SZ TA TC TD TF TG TH TJ TK TL TM TN TO TP TR TT TV TW TZ UA UG UK UM US UY UZ VA VC VE VG VI VN VU WF WL WO WS WV XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ YE YT YU YV ZA ZM ZR ZW ZZ ``` [Answer] # Ruby, ~~269 246 241 235~~ 227 ``` g="b6wapsm769n90ongzuvadg5vdat6ap7v1oyyie3j5wxbq9xtycezrtt9xamn9riqnnxnsxjx0al8uk8rmk5snb7quly7t5i9rkq21r1vnns5vdm7gwzqtxwwwmj02nqxlhl".to_i 36 l=*?A..?Z 676.times{|i|print g.to_s(2)[i]==?1?l[i/26]+l[i%26]:" ",i%26==25?$/:" "} ``` `g` is a matrix where each cell that has a country code is a `1` and all others are `0`. All rows are written behind and the resulting binary number has been converted to a base 36 representation. Then I just iterate over all cells and check if the code shall be printed. [Answer] ## CJam, ~~152 149 148 145 144 140~~ 139 bytes, printable ``` ". QH%$ydK0]cg:WSSlFu0z>O$T1<hO)Q63@D7;\KDJ^!NQN!tFr'>x@*!nf`Ut<s=N_[\%Ec0AXXZ`hayqIi'qj)jnonEj!n(ZjpjW("31f-96b2b'[,65>_m*]z{~SS+?S}%52/N* ``` Thanks Dennis for pointers. Pretty straightforward approach. **How it works:** ``` ". Q .... jW(" "Push this string to stack. This is a compressed string" "which results to a 26 by 26 grid of 0 and 1 representing" "whether that block contains country code or empty space"; 31f-96b2b "Remove 31 from ASCII code of each of the character," "treat the number array as of base 96 and convert it to" "a base 2 number"; '[, "Create an array of characters of ASCII code 0 to 91"; 65> "Take last 26 characters, which are A to Z"; _m* "Copy the array and create all combinations {XX|X ∈ [A,Z]}"; ]z "zip the first 26*26 array of 1 and 0 with the above" "26*26 array of XX such that the final array element" "is like ([B XX]|B={0,1},X∈[A,Z])"; {~SS+?S}% "For element, unwrap it from array, put " " to stack," "if first number is 1, take XX otherwise, the spaces" "and put a single space after each element"; 52/ "split the array into chunks of 52,i.e 26 XX and 26 spaces"; N* "Join each chunk of 52 elements with new line" ``` [Try it online here](http://cjam.aditsu.net/) (Now only if I knew how to do a non printable character version) [Answer] # JavaScript ES6, 336 322 ``` a='ABCDEFGHIJKLMNOPQRSTUVWXYZ' alert(r='tr20d,yxurj,soeyn,1migz,rbh14,5hqc,13w82y,z1c,iqx33,l8dmo,1swln,zokqa,tukfz,r8voh,jzd34,mflqi,jzjen,10gn1k,13ycc7,sn0bd,kbb0j,qm2hs,mvf4,13ydj3,18y9c,jzdah'.split(',').map((n,i)=>(1e10+(parseInt(n,36).toString(2))).slice(-26).replace(/./g,(m,j)=>+m?a[i]+a[j]+' ':' ')).join('\n')) ``` The big string is each row put into binary (`1` if there was a country code there, `0` if not) and then base36. Try it out in Firefox at <http://jsfiddle.net/twduhqz6/1/>. [Answer] # Bash+coreutils, 361 Basic regex removal of the combos we don't want. Some mild compression of the regex: ``` a=({A..Z}) f=(BHJKVY CKP BEJQT A-DFHILNP-X BDI-LNOQX-Z A-HNPQS-WYZ JKOVXZ A-JLO-QSV-Z AF-KP B-DF-LNQ-Z A-DFJ-LOQS-VX DEGHJL-QWXZ BIJ BDHJKMNQSV-Y B-LN-Z B-DJO-QUVXZ B-L DFGJKQRTVX-Z PQW BEIQSUXY B-FH-JLN-RT-X BDFHJ-MO-TV-Z A-EG-KMNP-RTUW-Z _ A-DF-SW-Z B-LN-QS-VXY) for i in ${!a[@]};{ s+="${a[i]}[${f[i]}]|" } echo {A..Z}{A..Z}|sed -r "s/Z /Z\n/g;s/${s%|}/ /g" ``` [Answer] # Haskell, 357 Damn, this is kinda hard. ``` import Data.List.Split az=['A'..'Z'] k=0x9084004380010ffffffc24482004085570414419abfbb7be7fff153e65ffff001538f7c400100186b25d7fffcfd4f8149f42b1d00034047ff781e068d0015fb9ff2097c007e90f5c015943f6fdedffdefeedff97d l i (a:b)|i`mod`2>0=a:l(i`div`2)b|1>0=" ":l(i`div`2)b l _ _=[] main=putStr$unlines$chunksOf 78$unwords$l k[a:[b]|a<-az,b<-az] ``` Prints to STDOUT when compiled (thus the main). Using proper compression would make this a lot shorter... ideas welcome [Answer] # JavaScript (E6) 350 Not the right tool for this task (maybe thanks to *String.fromCharCode*?) ``` r=0,Q=x=>String.fromCharCode(x+64), console.log("2dff97d 3ff7bfb 3f6fded 3005650 7e90f5 825f00 15fb9ff 1a3400 3ff781e d011 342b1d0 13e0527 3fffcfd 21ac975 1001 14e3df1 3fff001 54f997 3be7fff 26afeed 3041441 102155 244820 3ffffff 380010 2421001" .replace(/\w+./g,x=>{for(x='0x'+x,s=c=o='',++r;++c<27;s=' ',x/=2)o+=s+(x&1?Q(r)+Q(c):' ');return o+'\n'})) ``` [Answer] ## J, 172 chars (printable) ``` echo}:"1,.u:32+(26 26$,(6#2)#:34-~3 u: 'QKa]?a@a`YQXa$HJ"\^+AB"`F&a[Y\B"N8#Z)QaD"N""P/2QFJ)TQUaa\\58("$""E]STJ"1aaKITJaa[_]?a7H$,$%LJ2*"24+%aaaa$"">*"*2F' )*0,"1~33+,"0/~i.26 ``` Line breaks for legibility. Straightforward binary packing, with six bits per string character (offset 34 to get into the printable range as well as avoid `'`). [Answer] # Wolfram language, 244 ~~255~~ bytes ``` Table[Table[If[BitGet[36^^b6wapsm769n90ongzuvadg5vdat6ap7v1oyyie3j5wxbq9xtycezrtt9xam\n9riqnnxnsxjx0al8uk8rmk5snb7quly7t5i9rkq21r1vnns5vdm7gwzqtxwwwmj02nqxl\hl,675-i*26-j]==1,FromCharacterCode[{i,j}+65]<>" "," "],{j,0,25}]<>"\n",{i,0,25}]<>"" ``` The number from fireflame241's answer was used and repacked into 36-ary form. No builtin country data were used. [Answer] # PHP, 323 Bytes ``` $p=explode(_,"^BHJKVY_^CKP_^BEJQT_EGJKMOYZ_ACE-HMPR-W_I-MORX_^JKOVXZ_KMNRTU_^AF-KP_AEMOP_EGHIMNPRWYZ_ABCFIKR-VY_^BIJ_ACEFGILOPRTUZ_AM_AE-IK-NR-TWY_AM-Z_A-CEHIL-PSUW_^PQW_^BEIQSUXY_AGKMSYZ_ACEGINU_FLOSV_\w_ETUV_AMRWZ"); foreach($r=range(A,Z)as$k=>$v) foreach($r as$w)echo preg_match("#[{$p[$k]}]#",$w)?$v.$w:" "," "[$w>Y]; ``` [Try it online!](https://tio.run/nexus/php#TY7LboJAGIX3PgUZZyEJ0weoVQOEyzAODMNNsPKHWKqJbSG0EZOmz26HdNPluXwn52nTn/s77lftrX/rXtoFGKi2/IDlJdQ2E1BbThCn4HgB41FZgWk7xOdCkgIo4ZHcQR2wKN9VwHgo0wxq0yWKMx0eCYX5lIdCFhNp2S5lkkzLFg2mJdej20goSqVcIYQyEkqSFqXSRJnEdny6JSLJCqhFXEx3aJxkO1XwGE/@Dnk0zMDdRkkOzyM4aZYrXBYV0pez125om@N5gYfV0Hyc2oVpVHrziS@rNb7q/2JNmaPeHs@d1g/tCd6bL@Wj@f4b93t8Ofwc5shQjQ2@PuDxEWkaMpA2Q3s8rsvD8n7/BQ "PHP – TIO Nexus") [Answer] ## C, 373 bytes ``` main(i,j){char e[]="0BHJKVY|0CKP|0BEJQT|EGJKLMOYZ|0BDIJKLNOQXYZ|IJKLMORX|0JKOVXZ|KMNRTU|0AFGHIJKP|AEMOP|EGHIMNPRWYZ|ABCFIKRSTUVY|0BIJ|0BDHJKMNQSVWXY|AM|0BCDJOPQUVXZ|0BCDEFGHIJKL|0DFGJKQRTVXYZ|0PQW|0BEIQSUXY|AGKMSYZ|ACEGINU|FLOSV|0|ETUV|AMRWZ",*t,*p=e,*s="|";for(i=0;t=strtok(p,s);p=0,i++)for(j=0;j<27;j++)printf(j-26?!strchr(t,65+j)^(*t!=48)?"%c%c ":" ":"\n",65+i,65+j);} ``` [Try it online](https://tio.run/nexus/c-gcc#JVBrb4JAEPwreI0JIG0uprVNkRpAQEDeT@0jMVTrYYsE6adef7vdq182uzM7M5u9Ik31@f2@5aanviPNx83@6fy1IQ1PpFr4qfabjts@vyoIawvHzVcU625IsWY4UUoNy3GXXrBaAzC3ofeDqITJ/ofjkmLHDfJyTV3Pj9OMYtW0FkCGVDW8IAT9wvb8MC5Ao2q6abtxkmYsRLMd5gmRnh8leVGuqOoBos@dIIwy5skG4@K3pHhuwi1RnOYsH4dRwW60oyRjSsv1EhahG5btZ9RcBklOMTUgC2zjYo0ksZfEVtlK4klBFMm7Y8cTBcu9Al/pjwe@lU6C3CpYIqORwNga2Ho6vpdrAFr4XL/j6@vxZDYARbXv@F6a3I1q4Y0X@4Fy@yDM0LAaVhx6RBzH6kuD2Aa5rMm/5/Mf) [Answer] ## Wolfram language, 389 bytes ``` c=CountryData;r=Riffle;StringReplace[""<>r[#~r~" "&/@Array[CharacterRange["A","Z"][[{##}]]&,{26,26}],n=" "],{"GZ"|"WE"->" ",x:("X"~~_~~" "|n)|##&@@(Cases[#~c~"CountryCode"&/@c[],_String]~Join~(""<>#&/@Partition[Characters@"AACPSXQNICRANTAPEAQPEPEUMQQRCSXQXDGCWLRNTPEVAQUMQVEWLRPIXDYUMQSUMQWVEFRBQYVIBXEMQMQOAQZRBLFRBUKRLIBVIUKGSSFXHRMQTFLIVIWOARIYVIZZRHMFIOAXJA",2,1])):>x,Except@n->" "}] ``` More readable: ``` c = CountryData; r = Riffle; StringReplace[ "" <> r[#~r~" " & /@ Array[CharacterRange["A", "Z"][[{##}]] &, {26, 26}], n = "\n"], {"GZ" | "WE" -> " ", x : ("X" ~~ _ ~~ " " | n) | ## & @@ (Cases[#~c~"CountryCode" & /@ c[], _String]~ Join~("" <> # & /@ Partition[ Characters@ "AACPSXQNICRANTAPEAQPEPEUMQQRCSXQXDGCWLRNTPEVAQUMQVEWLRPIXDY\ UMQSUMQWVEFRBQYVIBXEMQMQOAQZRBLFRBUKRLIBVIUKGSSFXHRMQTFLIVIWOARIYVIZZR\ HMFIOAXJA", 2, 1])) :> x, Except@n -> " "}] ``` Wolfram has an in-built list of ISO country codes, so this should be the perfect language for the job. However, it only knows about the country codes that are actually the codes for countries, and not the ones reserved for other uses, which are still included in this table. We therefore need to add a lot of the country codes in manually. Explanation: * `""<>r[r[#," "]&/@Array[CharacterRange["A","Z"][[{##}]]&,{26,26}],n="\n"]` is a string array of all pairs of letters from "A" to "Z". * `#~c~"CountryCode"&/@c[]` (where `c=CountryData` is defined earlier) gives a list of all country codes that Wolfram Language knows about. A couple of these are `Missing["NotApplicable"]`, so we remove those with `Cases[...,_String]`. * `(""<>#&/@Partition[Characters@"AACP...AXJA",2,1])` makes 83 of the remaining country codes manually using a 138-character string, where the pairs of adjacent characters are the required country codes. This string was found more or less by hand (with the help of the `FindPostmanTour` function!), and there is some repetition, so there's potentially more golfing to be done here. * `StringReplace[ <full array> ,{"GZ"|"WE"->" ",x:("X"~~_~~" "|n)|##&@@( <known country codes> ~Join~ <extra codes> ):>x,Except@n->" "}]` first gets rid of two codes, "GZ" and "WE", which Wolfram thinks are country codes but aren't according to the table; then matches all codes starting with "X", plus the known codes and the ones we added manually, and replaces them with themselves; then finally everything else which isn't a newline and hasn't already been matched is turned into a space. [Answer] # Deadfish~, 9662 bytes ``` {iiiiii}iiiiicc{ddd}dddcccc{iii}iiiciic{ddd}dddddc{iii}iiiciiic{ddd}ddddddc{iii}iiiciiiic{dddd}iiic{iii}iiiciiiiic{dddd}iic{iii}iiiciiiiiic{dddd}icccc{iii}iiic{i}ddc{dddd}dccccccc{iii}iiic{i}ic{dddd}ddddc{iii}iiic{i}iic{dddd}dddddc{iii}iiic{i}iiic{dddd}ddddddc{iii}iiic{i}iiiic{ddddd}iiic{iii}iiic{i}iiiiic{ddddd}iic{iii}iiic{i}iiiiiic{ddddd}ic{iii}iiic{ii}dddc{ddddd}c{iii}iiic{ii}ddc{ddddd}dc{iii}iiic{ii}dc{ddddd}ddc{iii}iiic{ii}c{ddddd}dddcccc{iii}iiic{ii}iic{ddddd}dddddc{iii}iiic{ii}iiic{ddddd}ddddddcccc{iii}iiic{ii}iiiiic{{d}ii}c{iiiii}iiiiiicdc{ddd}dddc{iii}iiiicc{ddd}ddddcccc{iii}iiiiciic{ddd}ddddddc{iii}iiiiciiic{dddd}iiic{iii}iiiiciiiic{dddd}iic{iii}iiiiciiiiic{dddd}ic{iii}iiiiciiiiiic{dddd}c{iii}iiiic{i}dddc{dddd}dc{iii}iiiic{i}ddc{dddd}ddcccc{iii}iiiic{i}c{dddd}ddddc{iii}iiiic{i}ic{dddd}dddddc{iii}iiiic{i}iic{dddd}ddddddc{iii}iiiic{i}iiic{ddddd}iiicccc{iii}iiiic{i}iiiiic{ddddd}ic{iii}iiiic{i}iiiiiic{ddddd}c{iii}iiiic{ii}dddc{ddddd}dc{iii}iiiic{ii}ddc{ddddd}ddc{iii}iiiic{ii}dc{ddddd}dddc{iii}iiiic{ii}c{ddddd}ddddc{iii}iiiic{ii}ic{ddddd}dddddc{iii}iiiic{ii}iic{ddddd}ddddddc{iii}iiiic{ii}iiic{dddddd}iiic{iii}iiiic{ii}iiiic{{d}ii}c{iiiiii}dddcddc{ddd}dddcccc{iii}iiiiicc{ddd}dddddc{iii}iiiiicic{ddd}ddddddcccc{iii}iiiiiciiic{dddd}iic{iii}iiiiiciiiic{dddd}ic{iii}iiiiiciiiiic{dddd}c{iii}iiiiiciiiiiic{dddd}dcccc{iii}iiiiic{i}ddc{dddd}dddc{iii}iiiiic{i}dc{dddd}ddddc{iii}iiiiic{i}c{dddd}dddddc{iii}iiiiic{i}ic{dddd}ddddddc{iii}iiiiic{i}iic{ddddd}iiic{iii}iiiiic{i}iiic{ddddd}iicccc{iii}iiiiic{i}iiiiic{ddddd}c{iii}iiiiic{i}iiiiiic{ddddd}dcccc{iii}iiiiic{ii}ddc{ddddd}dddc{iii}iiiiic{ii}dc{ddddd}ddddc{iii}iiiiic{ii}c{ddddd}dddddc{iii}iiiiic{ii}ic{ddddd}ddddddc{iii}iiiiic{ii}iic{dddddd}iiic{iii}iiiiic{ii}iiic{{d}ii}c{ii}ii{c}cc{iii}iiiiiicic{dddd}iiicccc{iii}iiiiiiciiic{dddd}iccccccc{iii}iiiiiiciiiiiic{dddd}ddc{iii}iiiiiic{i}dddc{dddd}dddcccc{iii}iiiiiic{i}dc{dddd}dddddcccc{iii}iiiiiic{i}ic{ddddd}iii{cc}cccccccc{iii}iiiiiic{ii}ic{dddddd}iiic{iii}iiiiiic{ii}iic{{d}ii}c{iiiiii}dcddddc{ddd}dddcccc{iiii}dddcddc{ddd}dddddcccc{iiii}dddcc{dddd}iiic{iiii}dddcic{dddd}iic{iiii}dddciic{dddd}ic{iiii}dddciiic{dddd}{c}ccc{iiii}dddc{i}ddc{dddd}dddddccccccc{iiii}dddc{i}ic{ddddd}iicccc{iiii}dddc{i}iiic{ddddd}c{iiii}dddc{i}iiiic{ddddd}dc{iiii}dddc{i}iiiiic{ddddd}ddc{iiii}dddc{i}iiiiiic{ddddd}dddc{iiii}dddc{ii}dddc{ddddd}ddddc{iiii}dddc{ii}ddc{ddddd}dddddccccccccc{dd}ddc{ii}ii{cc}cccc{iiii}ddciiic{dddd}dc{iiii}ddciiiic{dddd}ddc{iiii}ddciiiiic{dddd}dddc{iiii}ddciiiiiic{dddd}ddddc{iiii}ddc{i}dddc{dddd}dddddcccc{iiii}ddc{i}dc{ddddd}iiiccccccc{iiii}ddc{i}iic{ddddd}{c}cccccc{iiii}ddc{ii}ddc{ddddd}ddddddcccccc{dd}ddc{iiiiii}icddddddc{ddd}dddc{iiii}dcdddddc{ddd}ddddc{iiii}dcddddc{ddd}dddddc{iiii}dcdddc{ddd}ddddddc{iiii}dcddc{dddd}iiic{iiii}dcdc{dddd}iic{iiii}dcc{dddd}ic{iiii}dcic{dddd}c{iiii}dciic{dddd}dccccccc{iiii}dciiiiic{dddd}ddddc{iiii}dciiiiiic{dddd}dddddc{iiii}dc{i}dddc{dddd}ddddddcccc{iiii}dc{i}dc{ddddd}iic{iiii}dc{i}c{ddddd}ic{iiii}dc{i}ic{ddddd}c{iiii}dc{i}iic{ddddd}dc{iiii}dc{i}iiic{ddddd}ddc{iiii}dc{i}iiiic{ddddd}dddcccc{iiii}dc{i}iiiiiic{ddddd}dddddcccc{iiii}dc{ii}ddc{dddddd}iiiccc{dd}ddc{ii}ii{cc}{c}{iiii}ciiic{dddd}dddcccc{iiii}ciiiiic{dddd}dddddc{iiii}ciiiiiic{dddd}dddddd{c}{iiii}c{i}c{ddddd}cccc{iiii}c{i}iic{ddddd}ddc{iiii}c{i}iiic{ddddd}ddd{c}ccccc{dd}ddc{ii}iiccc{iiii}ic{d}iiic{ddd}ddddc{iiii}icddddddc{ddd}dddddc{iiii}icdddddc{ddd}ddddddc{iiii}icddddc{dddd}iii{c}ccccccccc{iiii}iciiic{dddd}ddddc{iiii}iciiiic{dddd}dddddc{iiii}iciiiiic{dddd}ddddddc{iiii}iciiiiiic{ddddd}iiicccc{iiii}ic{i}ddc{ddddd}ic{iiii}ic{i}dc{ddddd}c{iiii}ic{i}c{ddddd}dc{iiii}ic{i}ic{ddddd}ddc{iiii}ic{i}iic{ddddd}dddc{iiii}ic{i}iiic{ddddd}ddddc{iiii}ic{i}iiiic{ddddd}dddddc{iiii}ic{i}iiiiic{ddddd}ddddddc{iiii}ic{i}iiiiiic{dddddd}iiic{iiii}ic{ii}dddc{{d}ii}c{iiiiii}iiiic{d}ic{ddd}ddd{c}{iiii}iicdddddc{dddd}iii{cc}cc{iiii}iiciiic{dddd}dddddcccc{iiii}iiciiiiic{ddddd}iiic{iiii}iiciiiiiic{ddddd}ii{cc}{c}{dd}ddc{ii}ii{c}cc{iiii}iiicddddddc{dddd}iiicccc{iiii}iiicddddc{dddd}ic{iiii}iiicdddc{dddd}c{iiii}iiicddc{dddd}d{c}{iiii}iiiciic{dddd}dddddc{iiii}iiiciiic{dddd}ddddddcccc{iiii}iiiciiiiic{ddddd}iicccc{iiii}iiic{i}dddc{ddddd}{c}ccc{iiii}iiic{i}iic{ddddd}dddddcccc{iiii}iiic{i}iiiic{dddddd}iiic{iiii}iiic{i}iiiiic{{d}ii}c{iiiiii}iiiiiic{d}dc{ddd}dddc{iiii}iiiic{d}c{ddd}ddddc{iiii}iiiic{d}ic{ddd}dddddccccccc{iiii}iiiicddddddc{dddd}iiccccccc{iiii}iiiicdddc{dddd}dcccc{iiii}iiiicdc{dddd}ddd{c}ccccccccc{iiii}iiiiciiiiiic{ddddd}c{iiii}iiiic{i}dddc{ddddd}dc{iiii}iiiic{i}ddc{ddddd}ddc{iiii}iiiic{i}dc{ddddd}dddc{iiii}iiiic{i}c{ddddd}ddddccccccc{iiii}iiiic{i}iiic{dddddd}iiiccc{dd}ddc{{i}ddd}dddc{d}ddc{ddd}dddcccc{iiii}iiiiic{d}c{ddd}dddddc{iiii}iiiiic{d}ic{ddd}ddddddc{iiii}iiiiic{d}iic{dddd}iiic{iiii}iiiiic{d}iiic{dddd}iic{iiii}iiiiicddddddc{dddd}ic{iiii}iiiiicdddddc{dddd}ccccccc{iiii}iiiiicddc{dddd}dddc{iiii}iiiiicdc{dddd}ddddc{iiii}iiiiicc{dddd}dddddc{iiii}iiiiicic{dddd}ddddddc{iiii}iiiiiciic{ddddd}iiic{iiii}iiiiiciiic{ddddd}iic{iiii}iiiiiciiiic{ddddd}ic{iiii}iiiiiciiiiic{ddddd}c{iiii}iiiiiciiiiiic{ddddd}dc{iiii}iiiiic{i}dddc{ddddd}ddc{iiii}iiiiic{i}ddc{ddddd}dddc{iiii}iiiiic{i}dc{ddddd}ddddc{iiii}iiiiic{i}c{ddddd}dddddc{iiii}iiiiic{i}ic{ddddd}ddddddc{iiii}iiiiic{i}iic{dddddd}iiic{iiii}iiiiic{i}iiic{{d}ii}c{{i}ddd}ddc{d}dddc{ddd}dddcccc{iiii}iiiiiic{d}dc{ddd}dddddcccc{iiii}iiiiiic{d}ic{dddd}iiic{iiii}iiiiiic{d}iic{dddd}iic{iiii}iiiiiic{d}iiic{dddd}icccc{iiii}iiiiiicdddddc{dddd}dccccccc{iiii}iiiiiicddc{dddd}ddddccccccc{iiii}iiiiiicic{ddddd}iiic{iiii}iiiiiiciic{ddddd}iicccc{iiii}iiiiiiciiiic{ddddd}cccc{iiii}iiiiiiciiiiiic{ddddd}ddc{iiii}iiiiiic{i}dddc{ddddd}ddd{c}ccc{iiii}iiiiiic{i}iic{{d}ii}c{{i}ddd}dc{d}ddddc{ddd}ddd{cc}{c}cccc{iiiii}dddcddc{dddd}ddddd{cc}{c}ccccccccc{dd}ddc{{i}ddd}c{d}dddddc{ddd}ddd{c}{iiiii}ddc{d}dc{dddd}iiic{iiiii}ddc{d}c{dddd}iic{iiiii}ddc{d}ic{dddd}ic{iiiii}ddc{d}iic{dddd}c{iiiii}ddc{d}iiic{dddd}dcccc{iiiii}ddcdddddc{dddd}dddc{iiiii}ddcddddc{dddd}ddddc{iiiii}ddcdddc{dddd}dddddc{iiiii}ddcddc{dddd}dddddd{c}{iiiii}ddciic{ddddd}c{iiiii}ddciiic{ddddd}dc{iiiii}ddciiiic{ddddd}ddccccccc{iiiii}ddc{i}dddc{ddddd}dddddcccc{iiiii}ddc{i}dc{dddddd}iiiccc{dd}ddc{{i}ddd}ic{d}ddddddc{ddd}ddd{cc}{c}cccc{iiiii}dcddddc{dddd}dddddc{iiiii}dcdddc{dddd}ddddddc{iiiii}dcddc{ddddd}iiic{iiiii}dcdc{ddddd}iic{iiiii}dcc{ddddd}ic{iiiii}dcic{ddddd}c{iiiii}dciic{ddddd}dc{iiiii}dciiic{ddddd}ddc{iiiii}dciiiic{ddddd}dddc{iiiii}dciiiiic{ddddd}ddddc{iiiii}dciiiiiic{ddddd}dddddc{iiiii}dc{i}dddc{ddddd}ddddddc{iiiii}dc{i}ddc{dddddd}iiic{iiiii}dc{i}dc{{d}ii}c{{i}ddd}iic{dd}iiic{ddd}dddc{iiiii}c{d}ddddddc{ddd}ddddc{iiiii}c{d}dddddc{ddd}dddddcccc{iiiii}c{d}dddc{dddd}iiiccccccc{iiiii}c{d}c{dddd}c{iiiii}c{d}ic{dddd}dccccccc{iiiii}cddddddc{dddd}ddddc{iiiii}cdddddc{dddd}dddddc{iiiii}cddddc{dddd}ddddddc{iiiii}cdddc{ddddd}iiic{iiiii}cddc{ddddd}iiccccccc{iiiii}cic{ddddd}dcccc{iiiii}ciiic{ddddd}dddcccc{iiiii}ciiiiic{ddddd}dddddccccccccc{dd}ddc{{i}ddd}iiic{dd}iic{ddd}dddc{iiiii}ic{dd}iiic{ddd}ddddc{iiiii}ic{d}ddddddc{ddd}dddddc{iiiii}ic{d}dddddc{ddd}ddddddc{iiiii}ic{d}ddddc{dddd}iiic{iiiii}ic{d}dddc{dddd}iic{iiiii}ic{d}ddc{dddd}ic{iiiii}ic{d}dc{dddd}c{iiiii}ic{d}c{dddd}dc{iiiii}ic{d}ic{dddd}ddc{iiiii}ic{d}iic{dddd}dddc{iiiii}ic{d}iiic{dddd}ddddc{iiiii}icddddddc{dddd}dddddc{iiiii}icdddddc{dddd}ddddddc{iiiii}icddddc{ddddd}iiiccccccc{iiiii}icdc{ddddd}c{iiiii}icc{ddddd}dc{iiiii}icic{ddddd}ddc{iiiii}iciic{ddddd}dddc{iiiii}iciiic{ddddd}ddddcccc{iiiii}iciiiiic{ddddd}ddddddc{iiiii}iciiiiiic{dddddd}iiic{iiiii}ic{i}dddc{{d}ii}c{{i}ddd}iiiic{dd}ic{ddd}dddcccc{iiiii}iic{dd}iiic{ddd}dddddc{iiiii}iic{d}ddddddc{ddd}ddddddcccc{iiiii}iic{d}ddddc{dddd}iic{iiiii}iic{d}dddc{dddd}ic{iiiii}iic{d}ddc{dddd}cccc{iiiii}iic{d}c{dddd}ddc{iiiii}iic{d}ic{dddd}dddc{iiiii}iic{d}iic{dddd}ddddc{iiiii}iic{d}iiic{dddd}dddddc{iiiii}iicddddddc{dddd}ddddddc{iiiii}iicdddddc{ddddd}iiic{iiiii}iicddddc{ddddd}iicccc{iiiii}iicddc{ddddd}cccc{iiiii}iicc{ddddd}ddcccc{iiiii}iiciic{ddddd}ddddc{iiiii}iiciiic{ddddd}dddddccccccc{iiiii}iiciiiiiic{{d}ii}c{{i}ddd}iiiiic{dd}c{ddd}ddd{c}cccccc{iiiii}iiic{d}ddddc{dddd}i{c}{iiiii}iiic{d}c{dddd}dddcccc{iiiii}iiic{d}iic{dddd}ddddd{c}cccccc{iiiii}iiicddc{ddddd}d{c}cccccc{iiiii}iiiciiiic{dddddd}iiic{iiiii}iiiciiiiic{{d}ii}c{{i}ddd}iiiiiic{dd}dc{ddd}dddcccc{iiiii}iiiic{dd}ic{ddd}dddddcccc{iiiii}iiiic{dd}iiic{dddd}iiicccc{iiiii}iiiic{d}dddddc{dddd}icccc{iiiii}iiiic{d}dddc{dddd}d{c}ccc{iiiii}iiiic{d}iic{dddd}dddddd{c}ccccccccc{iiiii}iiiicdc{ddddd}ddd{c}ccccc{dd}ddc{ii}ii{c}ccccc{iiiii}iiiiic{dd}iiic{dddd}ii{c}cccccc{iiiii}iiiiic{d}dc{dddd}ddddccccccc{iiiii}iiiiic{d}iic{ddddd}iii{c}{iiiii}iiiiicddddc{ddddd}dccccccc{iiiii}iiiiicdc{ddddd}dddd{c}cc{dd}ddc{{i}dd}ddc{dd}dddc{ddd}dddc{iiiii}iiiiiic{dd}ddc{ddd}ddddc{iiiii}iiiiiic{dd}dc{ddd}dddddc{iiiii}iiiiiic{dd}c{ddd}ddddddc{iiiii}iiiiiic{dd}ic{dddd}iiic{iiiii}iiiiiic{dd}iic{dddd}iic{iiiii}iiiiiic{dd}iiic{dddd}ic{iiiii}iiiiiic{d}ddddddc{dddd}c{iiiii}iiiiiic{d}dddddc{dddd}dc{iiiii}iiiiiic{d}ddddc{dddd}ddc{iiiii}iiiiiic{d}dddc{dddd}dddc{iiiii}iiiiiic{d}ddc{dddd}ddddc{iiiii}iiiiiic{d}dc{dddd}dddddc{iiiii}iiiiiic{d}c{dddd}ddddddc{iiiii}iiiiiic{d}ic{ddddd}iiic{iiiii}iiiiiic{d}iic{ddddd}iic{iiiii}iiiiiic{d}iiic{ddddd}ic{iiiii}iiiiiicddddddc{ddddd}c{iiiii}iiiiiicdddddc{ddddd}dc{iiiii}iiiiiicddddc{ddddd}ddc{iiiii}iiiiiicdddc{ddddd}dddc{iiiii}iiiiiicddc{ddddd}ddddc{iiiii}iiiiiicdc{ddddd}dddddc{iiiii}iiiiiicc{ddddd}ddddddc{iiiii}iiiiiicic{dddddd}iiic{iiiii}iiiiiiciic{{d}ii}c{ii}ii{c}cc{iiiiii}dddc{dd}c{dddd}iii{cc}{cc}ccc{iiiiii}dddcdddddc{ddddd}ddc{iiiiii}dddcddddc{ddddd}dddc{iiiiii}dddcdddc{ddddd}dddd{c}cc{dd}ddc{{i}dd}c{dd}dddddc{ddd}ddd{cc}{c}cccc{iiiiii}ddc{d}dddc{dddd}ddddd{c}ccc{iiiiii}ddc{d}iic{ddddd}{c}ccc{iiiiii}ddcdddc{ddddd}dddddccccccc{iiiiii}ddcc ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~121~~ ~~120~~ ~~112~~ 110 bytes ``` “VV&ØṖgḳeƘKo⁾lc<Ṗɗẋ⁾ÆȤ¡rżQ5¤ø^k&`v®tḊẒḂṁz®ṙṂþ°~7<¹ṢƝƒ4ṇæÇZt9ẈÇḞƲY!u`İŀo0*dḅḥmȯḊȧṛƓXĠƈṾ’Bx2ða»32øØAp`OFµỌs2s26G ``` [Try it online!](https://tio.run/nexus/jelly#AcEAPv//4oCcVlYmw5jhuZZn4bizZcaYS2/igb5sYzzhuZbJl@G6i@KBvsOGyKTCoXLFvFE1wqTDuF5rJmB2wq504biK4bqS4biC4bmBesKu4bmZ4bmCw77CsH43PMK54bmixp3GkjThuYfDpsOHWnQ54bqIw4fhuJ7GslkhdWDEsMWAbzAqZOG4heG4pW3Ir@G4isin4bmbxpNYxKDGiOG5vuKAmUJ4MsOwYcK7MzLDuMOYQXBgT0bCteG7jHMyczI2R/// "Jelly – TIO Nexus") *-8 bytes thanks to @Dennis* *-2 bytes thanks to @Dennis's idea of Cartesian products* ### How it works **Simple:** The program multiplies one big binary list with another big list to get most of the output, then formats it **Medium:** The program encodes the big binary list ``` 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1 ``` into one big number, encoding which country codes are assigned. Each element is multiplied element-wise by each element of every possible country code to get a list of all assigned country codes, which is then formatted to the output list. **Lower level:** The bulk of the program uses data encoded in: ``` “VV&ØṖgḳeƘKo⁾lc<Ṗɗẋ⁾ÆȤ¡rżQ5¤ø^k&`v®tḊẒḂṁz®ṙṂþ°~7<¹ṢƝƒ4ṇæÇZt9ẈÇḞƲY!u`İŀo0*dḅḥmȯḊȧṛƓXĠƈṾ’ ``` It is a base-250 integer which holds the decimal number `233462323092263584350936137603939798267906095227198731310610883427614237299604158551774020670253062350084519623333781892392013977676150946873601610983221266427394582295973500719992107281184544524840476937`, which gets turned into the above binary list. For brevity, let's call this value `c` and replace the long string with `c` in the explanation ``` cBx2ða»32øØAp`OFµỌs2s26G - main link, takes no input c - literal value B - convert this to binary to get a list representing which codes are assigned x2 - repeat each element twice ða»32 - element-wise product (dealing with spaces) with... øØAp`OF - every possible country code in ASCII codes. µỌs2s26G - format the output to be correct ``` ]
[Question] [ Submit a well-formed program or function with **usual I/O rules** which satisfy the input, output, and algorithm conditions below. **Shortest submission (in bytes) wins.** As always, standard loopholes are forbidden. *In short:* Two distinct 8-bit integer inputs must produce two 8-bit integer outputs so that all four numbers are distinct, i.e., not equal. # Input Conditions Two distinct 8-bit integers, *a* and *b,* both of which are in 8-bit signed (or unsigned at your discretion) format. # Output Conditions Two 8-bit integers, *c* and *d,* which are in the same format as the input (signed or unsigned), such that *a,* *b,* *c,* and *d* are distinct, i.e., no two of them are equal to each other. # Algorithm Conditions 1. The algorithm must halt for all possible valid inputs. * Valid inputs are those where *a* and *b* are distinct. When *a* and *b* are equal, the behaviour of the algorithm is unspecified. 2. The algorithm must be deterministic. * Running the algorithm with the same input must produce the same output. 3. The algorithm must satisfy the *output conditions* for all valid inputs. # Verification There are two ways to verify your algorithm. 1. Brute force: explicitly check the program for all valid input combinations. 2. Prove/show, by analysis, that a clash is impossible (preferred). # FAQ 1. What if my programming language doesn't provide 8-bit integers? 2. What if my programming language doesn't support fixed-width integers? * Only the range of the outputs matter; internal computations may be in any precision. If the outputs can be rounded/scaled to the required integral range, then the programming language is good to go. --- # Edits **Edit 1:** Thank you for the submissions! I am glad to see so many creative solutions! Initially, I planned to restrict the algorithm to one-to-one mapping (i.e., invertible), however, decided against it to make the problem simpler. Looking at the enthusiastic response, I will consider submitting a second code golf with the one-to-one mapping requirement. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~35~~ ~~31~~ ~~27~~ 23 bytes *-4 bytes thanks to Arnauld and Kevin Cruijssen* *-4 bytes thanks to xnor* ``` a=>b=>[c=3^a&1^b&2,c^4] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i7J1i462dY4LlHNMC5JzUgnOc4k9n9yfl5xfk6qXk5@ukaahoEmEGlac6GKGmIVBao1wqoWJPofAA "JavaScript (Node.js) – Try It Online") Explanation: Takes the flipped 1 bit of the first number, and adds the flipped 2 bit of the second number, guaranteeing a number different from both inputs in the 2 least significant bits. Outputs this number, and 4 added to this number [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 20 bytes ``` {grep(.none,^4)[^2]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Or0otUBDLy8/L1UnzkQzOs4otvZ/cWKlQppCtKGOUaw1F5RjZqJjaYngGugYIjhGOsax1v8B "Perl 6 – Try It Online") Outputs the first two numbers from the range 0 to 3 that aren't in the input. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 69 bytes ``` ,+[->+>+>+<<<],[->>->-<<<]++>>>[[-]<<<->.>>]<+<+>[[-]<<->.>]<+<[->.<] ``` [Try it online!](https://tio.run/##LYpBCoAwDAQftE1fsOxHSg5VEUToQfD9MQHZy8yw2zOvdb77HdEwTKiR9JYikxUDksYwTzF1yQniLxXK89/pEcf8AA "brainfuck – Try It Online") My solution takes the first input and counts it upwards and prints the first two numbers unless they are the second input. So if the first input is A and the second input is B the output will be: A+2, A+3 if B = A+1 or A+1, A+3 if B = A+2 or A+1, A+2 else ``` This initializes position 1,2,3 of the band as the first input incremented by 1 ,[->>->-<<<] This substracts the second input from positions 2 and 3. ++ Set position 0 to 2, counting the numbers still to print The band now reads: (2) a+1 a-b+1 a-b+1 >>>[[-]<<<->.>>] If position 3 is not 0, print out position 1 and decrement position 0 <+<+> Increment the band in position 1 and 2 [[-]<<->.>] If position 2 is not 0, print out position 1 and derement position 0 <+<[->.<] Increment at position 1, Position 0 is now either 1 or 0. If it is 1 print position 1 one more time. ``` ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞IK2£ ``` I/O as a pair of integers. [Try it online](https://tio.run/##yy9OTMpM/f//Ucc8T2@jQ4v//4821DGOBQA) or [verify some more test cases](https://tio.run/##ASsA1P9vc2FiaWX/OcOdw6PKksOLX312ecKpPyIg4oaSICI//@KInnlLMsKj/yz/). **Explanation:** ``` ∞ # Push an infinite positive list [1,2,3,...] IK # Remove the values of the input-pair 2£ # Only leave the first two values # (after which the result is output implicitly) ``` [Answer] # [Haskell](https://www.haskell.org/), 32 bytes ``` a#b=take 2[i|i<-[1..],a/=i,b/=i] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P1E5ybYkMTtVwSg6sybTRjfaUE8vVidR3zZTJwlIxP7PTczMU7BVKCjKzCtRUFEwVjb6DwA "Haskell – Try It Online") We pick the first two positive integers that aren't input numbers. [Answer] # JavaScript (ES6), ~~32 27~~ 26 bytes Takes input as `(x)(y)`. ``` x=>y=>[x^=k=y^x^1?1:2,y^k] ``` [Try it online!](https://tio.run/##VY9NboMwEIX3nOJFihJbcaKm6qrUdMcFskmEgoKIqSgIV5i0niKfnZq0NMpmft73PON5zz4zk7flR7du9FkNhRysjEhGiU1lJSm16fZ1@/woKK2OQ6FbpitIdO1FCVhfPYQ@vfhs49iXqxVHHwCjk34x3TBNGCgLZjGToEkAkr3A4egfecQZ8fBP99ZGfWGnOpZYARK4GvnGlN9qnPF0mwHkujG6Vptav7FTnJW1Oo@/AZv31ol5T45jHY3tfmwPjp/@NwHX64qsNmrSXDBFF7jA88Xibsdyd8lzZcxsycPhBw "JavaScript (Node.js) – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~28~~ 22 bytes ``` @(x)setxor(1:4,x)(1:2) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzOLWkIr9Iw9DKRKdCE0gZaf5P04g2VjCK1fwPAA) ### Explanation Anonymous function that outputs the first 2 entries from the sorted symmetric difference between `[1 2 3 4]` and the input. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~27~~ 10 bytes ``` I…⁻E⁴ιE²N² ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sRhIVCbnpDpn5Bdo@GbmlRZr@CYWaJjoKGRq6iiAmEY6Cp55BaUlfqW5SalFGpqaQHEjIGn9/7@hgsF/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Uses the same set difference algorithm as everyone else. Less boring 27-byte version actually tries to produce interesting outputs for all inputs: ``` NθNηI﹪⁺÷¹²⁸⊕¬﹪⁻θη¹²⁸⟦θη⟧²⁵⁶ ``` [Try it online!](https://tio.run/##TYqxDsIgFEV3v4LxkeBQoo2moy4MbbobBwQSSOjDUujv43MxTveek2O8zibp2JrCdy1TXV4uw8qHwz974jkHLHDTW4Ex2RoTzLFuoLDcwx6sg05eBFNoslscFmdhSr90DEjtKpjnglHIOe3jy0868tyTGFrrrpL1p3bc4wc "Charcoal – Try It Online") Link is to verbose version of code. Takes unsigned integers. Explanation: Flips the top bits of the values, unless this would exchange them, in which case adds 64 (modulo 256) instead. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 32 bytes port of @Jo King's answer ``` Complement[Range@4,{##}][[;;2]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zk/tyAnNTc1ryQ6KDEvPdXBRKdaWbk2Njra2tooNlbtf0BRZl6JgkN6tKGOUSwXnGekY4LMNUCRNLMEyf7/DwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 27 bytes ``` lambda s:[*{0,1,2,3}-s][:2] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRodgqWqvaQMdQx0jHuFa3ODbayij2f0FRZl6JRppGtbGOWa2m5n8A "Python 3 – Try It Online") The input is a set `s` with the integers. We build the set `{0, 1, 2, 3, 4, 5, 6, 7, 8}` and then perform set subtraction to remove, from that set, any input numbers. We then convert to a list and extract two elements. *Thanks Surculose for saving me 2!* [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Hõ kU ¯2 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=SPUga1UgrzI&input=WzEsOF0) [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~31~~ 29 bytes Saved 2 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)!!! ``` lambda x,y:(k:=~x&1|~y&2,k+4) ``` [Try it online!](https://tio.run/##ZY6xDoIwGIR3nuKHgbSxDiIaQ1JHXkAHiDpUaZWAhRRI2iC8OhYc3e6/u//L1aZ9VXJ7qNUkgMJ1Ktn7njHQxESoiOio/c1nNH5AilWIp6qwpbPquCMqBRpyCYrJJ0fBbo8jB2bX/LmQC9AuNbOEhKRUIMvH82WTkkvU8BZdrEdsesPYpeHShVrlskXCi1le8mzB93ogvRlgfYQ@sTIdvIUEy7aYlQ13LLUqLOH37p26x4M3jevh6Qs "Python 3.8 (pre-release) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` >2-Uy ``` [Try it online!](https://tio.run/##K6gsyfj/385IN7Ty//9oAx3jWAA "Pyth – Try It Online") # Explanation ``` y # Repeat the input U # Generate a length range: [0 .. 3] - # Difference with implicit input >2 # Slice out the last 2 items of the resulting list ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~36~~ ~~34~~ 28 bytes Saved ~~2~~ 8 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` f(x,y){x=(~y&2|~x&1)*257+4;} ``` [Try it online!](https://tio.run/##VVDBbsIwFLvnKwxSUbIGDSrYDl048gO7tNIuKCUQaesm2KREbfj17nVtGFziZ8d@saLnB627znAnvWic4hc/y9qLmy3FQ7Z@Tld56D52tuaiYbb@xhEKy5yZzxPvqSO6yAleCJ0xNKapQMOAaPGDxY8WmqIDsPQuJgo@CiRRpCgpM1TKb2VS6SpBtn661ctBf7zTKa5UgbYFYdmjH7kfeUH4/y7wdaJlhk@3O/u@r/r@SCqZVJhvhuGtnkrqJAtZXnvh70cWkQYWz8ACswb8KK6LX3@03p/PE9pD@dD9Ag "C (gcc) – Try It Online") Uses [Paul Mutser](https://codegolf.stackexchange.com/users/86374/paul-mutser)'s [formula](https://codegolf.stackexchange.com/a/201603/9481). Returns the two 16-bit values in a 32-bit `int` since there are no tuples *&c* in C. [Answer] # [Bash](https://www.gnu.org/software/bash/) + Core utilities, 29 bytes ``` seq 4|egrep -v $1\|$2|head -2 ``` [Try it online!](https://tio.run/##S0oszvj/vzi1UMGkJjW9KLVAQbdMQcUwpkbFqCYjNTFFQdfo////hv@NAA "Bash – Try It Online") Input is passed in two arguments, and the output is printed to stdout. This prints the first two positive integers that aren't either of the two arguments. [Answer] # [Erlang (escript)](http://erlang.org/doc/man/escript.html), 43 bytes Outputs the first two numbers from the range 0 to 3 that aren't in the input. ``` f(A)->lists:sublist(lists:seq(0,3)--A,1,2). ``` [Try it online!](https://tio.run/##NctBCoAgFATQfSf5wjfUdi6CziEuLCw@lJUaHd8MavdmmPFxdWHhPk2RjlyaMsPAeL9Sykmna3wBX/InCOwY5wNKVKwtm6MAxtY97fqOlD2YGYxAYRlWyB8C1d9U2Hp9AA "Erlang (escript) – Try It Online") [Answer] # [W](https://github.com/A-ee/w), 5 [bytes](https://github.com/A-ee/w/wiki/Code-Page) Takes input as a pair of integers. ``` %G?←√ ``` Uncompressed: ``` 4k Range from 1 to 4 at Trim out all items that appear in the input 2< Take the first two items of the output list. ``` [Answer] # [Io](http://iolanguage.org/), 46 bytes Port of RGS's Python answer. ``` method(x,list(1,2,3,4)difference(x)slice(0,2)) ``` [Try it online!](https://tio.run/##y8z/n6ZgZasQ8z83tSQjP0WjQicns7hEw1DHSMdYx0QzJTMtLbUoNS85VaNCszgnE0gb6Bhpav5P0wCrM9Ax09QsKMrMK8nJ@w8A "Io – Try It Online") [Answer] # [Alchemist](https://github.com/bforte/Alchemist), 60 bytes ``` _->In_x+In_y+2n n+x+y->Out_z+z+Out_" " x+0y->z+3y y+0x->z+3x ``` [Try it online!](https://tio.run/##S8xJzkjNzSwu@f8/XtfOMy@@QhtIVGob5XHlaVdoV@ra@ZeWxFdpV2mDaCUFJa4KbQOgaJW2cSVXpbZBBZhZ8f@/AZchAA "Alchemist – Try It Online") As with many answers here, prints the first two non-negative integers not in the input. Input is unsigned, since Alchemist doesn't have signed numbers. I similarly can't just let a variable "go negative" after it hits zero, so I just let an input value `x` also exclude `x+4`, `x+8`, and so on. This has no effect on anything, provided both variables don't hit zero at the same time. Fortunately, if they ever become the same, both outputs will happen before they hit zero. [Answer] # [Ruby](https://www.ruby-lang.org/), 22 bytes ``` ->*a{([*6..9]-a)[0,2]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf104rsVojWstMT88yVjdRM9pAxyi29n@BQlq0sY5Z7H8A "Ruby – Try It Online") Same method as almost everybody. ]
[Question] [ # Name the poker hand Given five cards, output the name of the poker hand, which will be one of: ``` High card One pair Two pair Three of a kind Straight Flush Full house Four of a kind Straight flush Royal Flush ``` If in doubt, refer to the rules at <http://en.wikipedia.org/wiki/List_of_poker_hands>. ## Input 5 *cards* from either stdin or commandline arguments. A card is a two letter string on the form `RS`, where R is rank and S is suit. The **ranks** are `2` - `9` (number cards), `T` (ten), `J` (Jack), `Q` (Queen), `K` (King), `A` (Ace). The **suits** are `S`, `D`, `H`, `C` for spades, diamonds, hearts and clubs respectively. ### Example of cards ``` 5H - five of hearts TS - ten of spades AD - ace of diamonds ``` ### Example of input => desired output ``` 3H 5D JS 3C 7C => One pair JH 4C 2C JD 2H => Two pair 7H 3S 7S 7D 7C => Four of a kind 8C 3H 8S 8H 3S => Full house ``` ## Rules Shortest code wins ### Edit Looking great so far! I can't really verify all the answers, since I don't know these languages very well and don't have compilers/interpreters for all of them, but I suspect that not everyone have thought about that **Aces can be both the highest and the lowest cards of a Straight (flush)**. [Answer] Came up with an answer of my own :) # Python - 312 301 298 ``` R,K,F,S,g=' 23456789TJQKA2345A',' of a Kind','Flush','Straight ',sorted s,r=''.join(g(raw_input(),key=R.find)).split() n,m=g(map(r.count,set(r)))[-2:] print[[F,[0,'High Card','TOwnoe'[n&1::2]+' Pair',['Full House','Three'+K][n&1],'Four'+K][m]],[[S,'Royal '][r[0]=='T']+F,S]][r in R][len(set(s))>1] ``` Creates a 2x2 list where the indices of the two dimensions are boolean checks for flush and straight. In case of both, we check if it's a royal flush or just a straight flush. For not flush and not straight, we check for the other hands: `m` and `n` holds the highest and second highest amount of same-rank cards; the names of the hands are stored in a list with indices according to `m`. Sub-checks within this list's values are done with `n` to seperate one pair from two pair, and three of a kind from house. Edit: Thanks Nolen Royality for a total of 20 characters saved! [Answer] ## Ruby 1.9 (~~427~~ ~~359~~ ~~348~~ ~~338~~ ~~296~~ ~~292~~ 289) **EDIT**: Fixed to work with low aces. **EDIT**: Incorporated @je-je's fixes / improvements ``` o,p=%w(flush straight) f=/1{5}|^1+0+1$/ s=[0]*13 puts Hash[*$*.map{|c|s['23456789TJQKA'.index c[0]]+=1;c[1]}.uniq[1]?[f,p,?4,'four'+a=' of a kind',/^[^1]+$/,'full house',?3,'three'+a,/2.*2/,'two pair',?2,'one pair',0,'high card']:[/1{5}$/,'royal '+o,f,p+' '+o,0,o]].find{|r,y|s.join[r]}[1] ``` The basic idea is to build up an array of the quantity of card in each rank, concatenate the digits into a string, and then run regular expressions to see which hand shape fits. We count the number of distinct suits to determine whether to check it against the different flushes (flush, straight flush, royal flush) or to the other shapes (everything else). Takes the cards as separate command-line args, like so: ``` >ruby poker-hand-golf.rb 3H 5D JS 3C 7C one pair ``` [Answer] C, 454 characters ``` #define L for(a=1;a<6;a++)for(b=0;b<13;b++) #define U u[b+6] #define R(x,y) if(x)puts(#y);else b,f,r,h=0,s=0,u[20]={0};main(int a,char**v){L U+=v[a][0]=="23456789TJQKA"[b];f=v[1][1];L{if(v[a][1]!=f)f=0;u[a]+=a==U;if(b>7)h+=U;if(a*13+b<64||!U)r=0;else if(++r==5)s=1;}R(f&&h==25,Royal flush)R(f&&s,Straight flush)R(u[4],Four of a kind)R(u[3]&&u[2],Full house)R(f,Flush)R(s,Straight)R(u[3],Three of a kind)R(u[2]==2,Two pair)R(u[2],One pair)R(h,High card);} ``` Run from command line with cards as arguments, e.g. ./a.out 8C 3H 8S 8H 3S Expanded version, with comments: ``` #define L for(a=1;a<6;a++)for(b=0;b<13;b++) #define R(x,y) if(x)puts(#y);else #define U u[b+6] b,f,r,h=0,s=0,u[20]={0}; main(int a,char**v){ // card usage - u[6..] L U+=v[a][0]=="23456789TJQKA"[b]; // NOTE: lets expand the inner body of the loop in the answer so this looks more sane: // flush f=v[1][1];L if(v[a][1]!=f)f=0; // count of usages - u[0..5] L u[a]+=a==U; // high cards x5 L if(b>7)h+=U; // straights L if(a*13+b<64||!U)r=0;else if(++r==5)s=1; // display R(f&&h==25,Royal flush) R(f&&s,Straight flush) R(u[4],Four of a kind) R(u[3]&&u[2],Full house) R(f,Flush) R(s,Straight) R(u[3],Three of a kind) R(u[2]==2,Two pair) R(u[2],One pair) R(h,High card); } ``` Edits: 1. Saved 12 chars by combining and reusing loops. 2. Saved 9 chars by inlining string constant. 3. Saved 19 chars by using stringification in macro, nasty.. [Answer] ## GolfScript (209 208 207 206 200 199 197 196 chars) ``` 3/zip:^0={10,''*"TJQKA"+?}/]:?15,{?\{=}+,,}%2,-$6,14.),++@$/):|;[!!2*^1=.&,(!+5+]or{/}*'Full house Two pair One pair ThreeKFourKHigh card Flush Straight''K'/' of a kind '*n/~|1$"Royal"if" "+2$+](= ``` I'm exploiting the offered freedom to tweak capitalisation: my Straight Flush and Royal Flush both capitalise Flush in order to reuse the word from the simple flush. Note: some earlier versions were buggy: they only supported full house when the pair was of lower value than the pair royal. They can be corrected by replacing the space separating `- 0` with a `$`. [Demo](http://golfscript.apphb.com/?c=OyJBSCBLSCBRQyBUSCBKSCIKCjMvemlwOl4wPXsxMCwnJyoiVEpRS0EiKz99L106PzE1LHs%2FXHs9fSssLH0lMiwtJDYsMTQuKSwrK0AkLyk6fDtbISEyKl4xPS4mLCghKzUrXW9yey99KidGdWxsIGhvdXNlClR3byBwYWlyCk9uZSBwYWlyClRocmVlS0ZvdXJLSGlnaCBjYXJkCkZsdXNoClN0cmFpZ2h0JydLJy8nIG9mIGEga2luZAonKm4vfnwxJCJSb3lhbCJpZiIgIisyJCtdKD0%3D) [Answer] ## *Mathematica*, 365 Here is my take on David Carraher's answer. Shown with white space for some readability. ``` If[ a = Characters; x = Thread; r = Range; d = Sort[a@StringSplit@# /. x[a@"23456789TJQKA" -> 2~r~14]]; {t, u} = Sort[Last /@ Tally@#] & /@ x@d; c = First /@ d; f = u == {5}; S = "Straight"; c == r[b = d[[1, 1]], b + 4], If[f, If[c == 10~r~14, "Royal Flush", S <> " flush"], S], If[f, "Flush", Switch[t, {_, 4}, "Four of a kind", {2, 3}, "Full house", {__, 3}, "Three of a kind", {_, 2, 2}, "Two pair", {__, 2}, "One pair", _, "High card"] ] ] & ``` One line version: ``` If[a=Characters;x=Thread;r=Range;d=Sort[a@StringSplit@#/.x[a@"23456789TJQKA"->2~r~14]];{t,u}=Sort[Last/@Tally@#]&/@x@d;c=First/@d;f=u=={5};S="Straight";c==r[b=d[[1,1]],b+4],If[f,If[c==10~r~14,"Royal Flush",S<>" flush"],S],If[f,"Flush",Switch[t,{_,4},"Four of a kind",{2,3},"Full house",{__,3},"Three of a kind",{_,2,2},"Two pair",{__,2},"One pair",_,"High card"]]]& ``` [Answer] # K, 294 295 ``` d:{F:"Flush";S:"Straight ";P:" Pair";K:" of a kind";$[(f:1=#?,/-1#'c)&("AJKQT")~a@<a:,/j:1#'c:" "\:x;"Royal ",F;f&s:(4#1)~1_-':a@<a:,/(("A23456789TJQKA")!1+!14)@j;S,F;4=p:|/#:'=j;"Four",K;(2;3)~u:a@<a:,/#:'=j;"Full House";f;F;s;S;3=p;"Three",K;(1;2;2)~u;"Two",P;(1;1;1;2)~u;"One",P;"High Card"]} ``` . ``` k)d'("TS JS QS KS AS";"3S 4S 5S 7S 6S";"JC JH KS JD JS";"JC JH 2S JD 2C";"2C 9C TC QC 6C";"8C 5D 9H 6C 7D";"8C 8D 9H 8S 7D";"8C 8D 9H 2S 9D";"8C 8D 4H 2S 9D";"3C 8D 4H 2S 9D") "Royal Flush" "Straight Flush" "Four of a kind" "Full House" "Flush" "Straight " "Three of a kind" "Two Pair" "One Pair" "High Card" ``` edit: Added 1 char for Ace-low straights [Answer] ### Python 334, 326 322 Characters ``` p,f,l,t,o=" pair"," of a kind"," Flush","Straight","A23456789TJQK" v,u=zip(*raw_input().split()) s=''.join(sorted(v,key=o.find)) print{5:"High card",7:"One"+p,9:"Two"+p,11:"Three"+f,13:"Full house",17:"Four"+f,23:t,24:l[1:],25:t,42:t+l,44:"Royal"+l}[(sum(map(v.count,v)),24)[len(set(u))<2]+((0,20)[s=="ATJQK"],18)[s in o]] ``` I know that last one liner is getting pretty unreadable, I'll put up a non-golfed version when I'm happy with with my solution. [Answer] ### GolfScript, 258 250 characters ``` 3/zip~;.&,(!\{"23456789TJQKA"?}%$.(\{.@- 8%}%\;"\1"-!\.1/.&{1$\-,}%1.$?)"Four"" of a kind":k+{.,2="Full house"{.2\?)"Three"k+{.3-,({.3\?)"One pair"{;"Straight":?;2$2$&{(8="Royal"?if" flush"+}{;?{"Flush""High card"if}if}if}if}"Two pair"if}if}if}if])\; ``` The program expects input on STDIN as given above and outputs to STDOUT. You may [test the code yourself](http://golfscript.apphb.com/?c=OyI4QyAzSCA4UyA4SCAzUyIKCjMvemlwfjsuJiwoIVx7IjIzNDU2Nzg5VEpRS0EiP30lJC4oXHsuQC0gOCV9JVw7IlwxIi0hXC4xLy4mezEkXC0sfSUxLiQ%2FKSJGb3VyIiIgb2YgYSBraW5kIjprK3suLDI9IkZ1bGwgaG91c2Uiey4yXD8pIlRocmVlImsrey4zLSwoey4zXD8pIk9uZSBwYWlyIns7IlN0cmFpZ2h0Ijo%2FOzIkMiQmeyg4PSJSb3lhbCI%2FaWYiIGZsdXNoIit9ezs%2FeyJGbHVzaCIiSGlnaCBjYXJkImlmfWlmfWlmfWlmfSJUd28gcGFpciJpZn1pZn1pZn1pZl0pXDs%3D). ``` > 8C 3H 8S 8H 3S Full house > 8C 7H 6S TH 9S Straight > AH 3H 4S 2H 6S High card ``` *Edit:* Incorporated w0lf's suggestions. [Answer] # Mathematica - 500 494 465 chars This solution is based on a [poker demonstration](http://demonstrations.wolfram.com/Poker/) by Ed Pegg, Jr. In this version, the cards are treated internally as numbers in `Range[2,14]` ``` v[x_] := Block[{d, t, c, f, s}, d = Sort@ToExpression[Characters[ImportString[x, "Table"][[1]]] /. {"T" -> 10, "J" -> 11, "Q" -> 12, "K" -> 13, "A" -> 14}];t = Sort /@ Map[Length, Split /@ Sort /@ Transpose@d, {2}];c = d[[All, 1]];f = (t[[2]] == {5});s = c == Range[b = d[[1, 1]], b + 4]; If[s, If[f, If[c == 10~Range~14, "royal flush", "straight flush"],"straight"], If[ f, "flush", Switch[t[[1]], {1, 4}, "four of a kind", {2, 3}, "full house", {1, 1, 3}, "three of a kind", {1, 2, 2}, "two pair", {1, 1, 1, 2}, "one pair", {1, 1, 1, 1, 1}, "high card"]]]] ``` Sample inputs, outputs: ![data](https://i.stack.imgur.com/Mt8wB.png) **Notes:** f: flush c: cards (without suit) s: straight t: {cards, suites} d: [Answer] # [Factor](https://factorcode.org/) + `poker`, 16 bytes ``` string>hand-name ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQma9QkJ@dWqRgzcWlZOGsYOyhYBGsYOGhYBysxPW/uKQoMy/dLiMxL0U3LzE39X8BkF/yHwA "Factor – Try It Online") ]
[Question] [ There are quite a few accumulator-based programming languages featured in challenges across the site, but it's a little tiring to have to write almost identical code for each one. So in this challenge you will write a program which can generate interpreters from an input. How does this work? Let us take this example: ``` [a ** 3, b * 2, c + 15, d = 0, e / 8] ``` This is not the only input format allowed. You are allowed to take input as an array of directives, an array of strings or even an entire string composed of these directives. Each directive looks similar to this: ``` [a, *, 3] ``` In this case, the `a` command multiplies (`+` means add, `-` means subtract, `*` means multiply, `/` means divide, `**` means exponentiate and `=` means assignment) the accumulator by `3` (the third element). So with the aforementioned input, we end up with this schema: ``` the command `a` cubes the accumulator the command `b` doubles the accumulator the command `c` adds 15 to the accumulator the command `d` assigns the accumulator to 0 the command `e` divides the accumulator by 8 ``` This means that typing the command `cabdcbbe` will output 7.5, because: (these rules apply to all generated "languages") * the accumulator is automatically initialized to 0 at the beginning of a program * the accumulator is implicitly outputted at the end of a command * `(0 + 15)**3*2` is disregarded because d reassigns the accumulator to zero * `(0 + 15)*2*2/8 = 7.5` When given an array of directives, your program should output a complete program in your favorite language (might be the one you write your answer in, but not necessarily) which takes a valid program in the newly generated language and outputs the accumulator at the end of it. If I were using JavaScript and were passed the array we discussed, my program might output ``` const program = prompt(); let acc = 0; for (const command of program) { if (command === 'a') { acc = acc ** 3; } else if (command === 'b') { acc = acc * 2; } else if (command === 'c') { acc = acc + 15; } else if (command === 'd') { acc = 0; } else if (command === 'e') { acc = acc / 8; } } alert(acc); ``` now, for some more rules: * the input will always be valid. No destructive operators will be entered (such as a / 0 which divides the accumulator by zero. * each command will perform only one operation on the accumulator, so there will be no command which multiplies the accumulator by 3, squares it and adds 5 to it all in one go. * each command is one letter long. * the shortest answer in bytes wins. [code-golf rules] * the interpreter should read the program from STDIN or from a file. * on TIO, you may pre-define the input array in the header section, but your program should obviously be able to handle any valid input. * you only need to support the six operators mentioned previously. * commands can involve floating point numbers and not only integers * you may replace the operators but you must then state which ones you changed * you may output a float even if all operators yield integers. You may not truncate outputs however [Answer] # [J](http://jsoftware.com/), 61 56 53 52 bytes ``` 1 :0 ('0'".@,~,@,.&' ')[u".@;@}:@,@,."1;:@'=: & &' ) ``` [Try it online!](https://tio.run/##PY5RS8MwFIXf@yuOBXvbGUK7MZCUQfAHiPhaVJI0XSNbW2I6n@Zfr5k6nw7nnPtdzvuydDteQZRJTiWlXLIvJhnPCFQ0c/S1PAt5idKqFpJ2AhkySorl8YEjJ5RkTT/KH7IR5ygkifHqRlRyUzRJcqlBT37ce3XEx2SN65xRwY2DoN92il9rUfO3NUjhFRsGjRXWDAZ3qLYMLV5QMljc4p79UfRsw@wH2@JkvYY9qcOsQrSfLvRwwzQHpFZr02plUuTe7fuAMOJgu3A9jyuK/xnoQFeAlm8 "J – Try It Online") Note: -3 bytes off TIO for `f=:` Operator changes used to match J's built-ins: * `**` -> `^` * `/` -> `%` * `=` -> `]` Additional notes: * This is adverb that modifies the program to interpret, which is given as a list of 3-element directives. The resulting verb then takes the input as an argument, and returns the result. * Assumes the program string to execute will be read from right-to-left -- again, this is in keeping with J's normal convention. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) 7, 133 ... 101 100 bytes -5 bytes thanks to Wasif! Then +1 byte to fix an issue with `--` always being read as the decrement operator, regardless of context. -2 bytes thanks to mazzy! Takes input as an array of directives in the form `@('command','operation',number)`; the output is a TIO-Compatible PowerShell program. ``` 'switch("$args"|% T*y){' $args|%{$1,$2,$3=$_ "$1{`$a=" $2[1]?"""`$a*""*$3+1|iex}":"`$a$2 $3}"} '}$a' ``` Link is to a 116-byte TIO-Friendly (PowerShell 6 and below) version of the code. [Try it online!](https://tio.run/##HctBCsIwEIXhfU5RhinTpBFtguCm4CHca63RFgpqI1RJc/aYZPEW3w/v9VzMbAczTSGQXcZPP1SA3fywsJbFSfy4I5a9lg4biUqibvHMABt3wa4FNt4rVBvzJiGIOwCIWQAI1HWzjubrwZvJGpc6qgJ1DJ6Bj4QQwrGijmQ6S82TrkkkVUYfUZNs9lm3qJbkLsNEbOMOxP8 "PowerShell – Try It Online") ### Explanation ``` 'switch("$args"|% T*y){' # The first part of the interpreter switches # on the input program's characters. Switching # on an array in powershell processes the # switch statement for each element. $args|%{$1,$2,$3=$_ # For each array in the input array, set $1, # $2, $3 to the first, second, and third # element, respectively. "$1{`$a=" # output the case for the letter of the command # start the case with setting the accumulator # equal to whatever else is in this case $2[1] # If the second character of the command exists # In other words, the command is '**' ?"""`$a*""*$3+1|iex}" # Make the body of the case a special way to # calculate powers in PowerShell which is # shorter than [Math]::Pow - effectively # builds a string representation of the # calculation, then evaluates that string. :"`$a$2$3}"} # If the command isn't '**', we just make the # command '{accumulator}{command}{number}' # for example: '$a/3', making the whole case # '{$a=$a/3}' '}$a' # Close the switch block, output the accumulator ``` ### Output Outputs a very ugly interpreter; for the example input provided in the challenge, the interpreter looks like this: ``` switch("$args"|% T*y){ a{$a= "$a*"*3+1|iex} b{$a= $a*2} c{$a= $a+15} d{$a= $a=0} e{$a= $a/8} }$a ``` And, of course, [Try The Output Interpreter!](https://tio.run/##K8gvTy0qzkjNyfn/v7g8syQ5Q0NJJbEovVipRlUhRKtSs5orsVol0ZYLKKqlpGWsbViTmVpRy5UEFgSKKRjVciVDOdoKhqa1XClQnq2CQS1XKpSjr2BRy1Wrkvj//3/15MSklOSkpFR1AA "PowerShell – Try It Online") [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~120~~ ~~106~~ 93 bytes *Saved 27 bytes thanks to @kaya3* ``` lambda f:lambda i,a=0:[a:={n:eval({'=':v}.get(o,str(a)+o+v))for n,o,v in f}[k]for k in i][-1] ``` [Try it online!](https://tio.run/##LYrRCoMgFIZfpbuj5bZaDELwSVwXunSLmoYTYUTP7k6xi@/wfT9n@caXd223hGzFPc/qrQdVWP6XkSlRc6m4WB03Sc1kBQE8beenicSzTwxE0cpXiVLrQ@GYZ6kYXWE3OfX7Mu019vLU9HkJo4vEEklAAYOyxNMCZQT0nsj1qAdahTS3IwdUgdRHGbQL0gHtKf4qPTy0NkBp/gE "Python 3.8 (pre-release) – Try It Online") Hey, my first golf! This golf utilizes Python 3.8's [walrus operator](https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions). You can insert the interpreter's commands as a list tuples into a function that returns a function which accepts commands as a string/list of strings (and, optionally, an initial value for the accumulator). If this `lambda` is assigned to `f` and run as: ``` f([('a','**','3'),('b','*','2'),('c','+','15'),('d','=','0'),('e','/','8')]) ``` will give you: ``` <function __main__.<lambda>.<locals>.<lambda>(i, a=0)> ``` which if assigned to f2 can be run as: ``` f2('cabdcbbe') ``` which outputs: ``` 7.5 ``` Ungolfed version: ``` def interpreter_generator(commands): def interpreter(instructions, accum=0): for i in instructions: accum = {n: eval({'=': v}.get(o, str(accum) + o + v)) for n, o, v in commands}[i] return accum return interpreter commands = [('a','**','3'), ('b','*','2'), ('c','+','15'), ('d','=','0'), ('e','/','8')] instructions = 'cabdcbbe' my_interpreter = interpreter_generator(commands) print(my_interpreter(instructions)) ``` [Answer] # JavaScript (ES6), 73 bytes Expects an array of `[letter, operation, value]` triplets. Returns a function that expects an array of letters. ``` a=>`a=>a.reduce((A,c)=>eval({${a.map(([c,o,v])=>c+`:'A${o+v}'`)}}[c]),0)` ``` [Try it online!](https://tio.run/##TY7NCsIwDIDvewoRIa2L9Q9BhA687CVKYVlWRZl2bLrL2LPPVi8eAt9Hwkfu1FPH7a15rZ6@ctNFT6SzIgyp1lVvdkKckaXOXE@1GBYDqQc1QhhGj70NC06LE5wXg0/7EQo5joatxI0sJg7FmZ5dhDFAgLBcAu4tGiijAO4ic@AUcHuIUgXRgJvILvAa8GitTNg/O187VfuriFWZ5CH8femn/we5MEqpOVNZcVm6uZVy@gA "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~202~~ \$\cdots\$ ~~136~~ 134 bytes ``` lambda s:'%{\nfloat p;\n%}\n%%\n'+''.join(a+' p=p'+b+('(','w(p,')[b>'=']+c+');\n'for a,b,c in s)+'%%\nmain(){yylex();printf("%f",p);}' ``` [Try it online!](https://tio.run/##HYzvCoMgFEdfRYS4OmX/YjAW7UXSD1rJGqVSwRbRs7u7Phw458L9xWV@BZ8nV6rUm8E2hkwPyFblXR/MTGKhfLYhmfIgAI7v0HlmBJBYRhBWMGAg4cOiBF7ZJ5SgRS2A4x@4MBIjraxJ58nEBfxXBoMDfF2Wvv0yXsSx87NjNHNURl5skPYLc6yqqKGSBiSnWlbUoh2Q6141mkAutz0b1BI579WinZA71Zrz9AM "Python 3 – Try It Online") Inputs the target language as a list of 3-tuples of strings. Uses `o` as the power operator. Generates the Flex code that will generate a C program that will parse the input language. If this `lambda` is assigned to `f` and run as: ``` print(f([["a","o","3"],["b","*","2"],["c","+","15"],["d","=","0"],["e","/","8"]])) ``` then that will output: ``` %{ float p; %} %% a p=pow(p,3); b p=p*(2); c p=p+(15); d p=p=(0); e p=p/(8); %% main(){yylex();printf("%f",p);} ``` which if stored in file `write_an_interpreter_generator.l` and then run through flex and then compiled: ``` flex write_an_interpreter_generator.l gcc lex.yy.c -o write_an_interpreter_generator -lfl -lm ``` will produce lexer `write_an_interpreter_generator`, which if run as: ``` echo 'cabdcbbe' | ./write_an_interpreter_generator ``` outputs: ``` 7.500000 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ZyW€}FV ``` [Try it online!](https://tio.run/##y0rNyan8/z@qMvxR05pat7D///9HR6snqusoqGsZq8fqKESrJ4E4h6cbQXjJIJ62oSmElwLiPdw52wDCTQUr3W6hHhv7PzkxKSU5KSkVAA "Jelly – Try It Online") The example language would be represented like this: `[['a', '*3'], ['b', '×2'], ['c', '+15'], ['d', 'ṛ0'], ['e', '÷8']]` Operators: `ṛ` = assignment, `+` = addition, `_` = subtraction, `×` = multiplication, `÷` = division, `*` = power. The program is given as the second argument. [Answer] # [Haskell](https://www.haskell.org/), 121 bytes ``` f d="($0).foldr(\\(Just g)->(.g))id.map(`lookup`["++(init$d>>=(\(c,o,p)->["('",c,"',(",o,"(",p,"))),"]>>=id))++"]);x!y=y" ``` [Try it online!](https://tio.run/##PY/dCoJAEIXve4ochGbazf4IglgfILrrUgXNVVsyXXSNenqbvOjiHM43HGaYe9Y/iroex3KuFaC/oaBsa91hHON56N28olWIQUVkdPDMLKZ12z4Gm0YgBJrGOF@HocIYc9lKy@UIcAEyl7CQCDwDdiuBiCQkXDWaSAhI6PT2PuoDozZdkTvzKnoVIWQgYblk2wPxgtsPWbuJck6CtT1MqDl6rM1EBac16wiUzJ6ZaZQd3NV1l8bn5/5Hxi8 "Haskell – Try It Online") Uses the default operators except for `=` which is replaced by `!`. The function `f` accepts a list of directives such as `[("a","**","3"),("b","*","2"),("c","+","15"),("d","!","0"),("e","/","8")]` and returns a Haskell function such as ``` ($0).foldr(\(Just g)->(.g))id.map(`lookup`[('a',(**(3))),('b',(*(2))),('c',(+(15))),('d',(!(0))),('e',(/(8)))]);x!y=y ``` [(Try it online!)](https://tio.run/##JcfrCoIwGAbgW0kRfD@zZUUQxLqAbqECN7fWcB7wAHn1a@Hz7/mIsdbOeW84koLYu3NqwBP3eZw2hnY3MENkFWtEj9J1XT335QOpSHNkGU5ElCOV/@G4pgrZ4nBep8IiFGt0yB6XkBddv9HCF98I2/J@sO2UmLgSUlVS6tj/AA "Haskell – Try It Online"). This function is the interpreter; in the above example, when called with input `"cabdcbbe"`, it returns `7.5`. ## How? The idea is to use the list of directives to embed a lookup table in the interpreter. In the above example, the lookup table is `[('a',(**3)),('b',(*2)),('c',(+15)),('d',(!0)),('e',(/8))]` (some brackets removed for clarity). This table maps each character to the corresponding function. Using the lookup table, the interpreter is able to convert the list of characters (e.g. `"cabdcbbe"`) to a list of functions (e.g. `[(+15),(**3),(*2),(!0),(+15),(*2),(*2),(/8)]`), which is then `foldr`ed with the composition operator `(.)` to yield the full (interpreted) program. Finally, the program (which, like everything in Haskell, is a function) is applied to the value `0`, returning the desired result. # [Haskell](https://www.haskell.org/), 113 bytes Assuming the list of instructions can be read right-to-left. ``` f d="g i=foldr(.)id[f|c<-i,(a,f)<-["++(init$d>>=(\(c,o,p)->["('",c,"',(",o,"(",p,"))),"]>>=id))++"],a==c]0;x!y=y" ``` Same idea as above, but without the need to reverse the string. [Answer] # [Ruby](https://www.ruby-lang.org/), 55 bytes ``` ->x{"a=0;$<.chars{|c|a=eval(?a+#{x.to_h}[c])*1.0};p a"} ``` [Try it online!](https://tio.run/##Rc7RCoIwGAXg@z3Fz@yi1MyKILDVg4wR/@bEiyBzGob67Gt/BJ67892c0/b64ysQfnsdRo4iL1aXzNTYunEyEwr7xsf6hkk0Dln3vNezNGoT77N8LhpAPnvXWAMCJIMQyZGnwOP4yFX6F/2TwwKGINmfFilJRL6AJdidCRRrrQsDlaQlxSJo@s5BQPYKTP@oeIO6NFrbLw "Ruby – Try It Online") Outputs a full Ruby program which reads characters from the input. As it turns out, returning a function seems to be longer, by my attempt. Takes input as an array like: ``` [ ["a", "**3"], ["b", "*2"], ["c", "+15"], ["d", "=0"], ["e", "/8"], ] ``` The function simply converts this to a hash and indexes each character in the input by this. Unfortunately I can't use `$.` as the accumulator since it cannot store floats, apparently. The `a=0;...;p a` bit annoys me, but I couldn't quite squeeze it out. ## Alternative Attempts ``` ->x{"a=0;$<.chars{|c|a=eval ?a+#{x.to_h}[c]+'.0'};p a"} ->x{"p$<.chars.inject(0){|a,c|eval(?a+#{x.to_h}[c])*1.0}"} ->x{"p$<.chars.inject(0){|a,c|eval ?a+#{x.to_h}[c]+'.0'}"} ``` Similar variants for returning functions, but I couldn't find a neat way to abuse the function nature. [Answer] # [Haskell](https://www.haskell.org/), 89 bytes ``` f c="a!c"++concat["|c=='"++a++"'=a"++o++x|(a,o,x)<-c,o/="="]++"|1>0=0\ne=print.foldl(!)0" ``` [Try it online!](https://tio.run/##JYnBDoIwEAV/pWxMaGmVqjHx4PoTHpHDWiASa0uwJhz490rlMpk370mfV2ttjB0zCJQZkNJ4ZyhUMBvEfNkkJeRIi3kpp5mT8moSl61RvkRAqJd/3l816rtrcRh7F3adt43lmdAQ39Q7hmz4hlsYN6yrOBAoKApQDI4gFOPwSP4PhzWY5DJhf1pLkwYm6DW0ycuEM4g6/gA "Haskell – Try It Online") * generates this Haskell program: ``` a!c|c=='a'=a**3|c=='b'=a*2|c=='c'=a+15|c=='e'=a/8|1>0=0 e=print.foldl(!)0 ``` [Try it online!](https://tio.run/##HcZLDkAwEADQvVOUDSqhJRKbcZfpGNGoT7Ds3Yu@1VvwXtm5EDAlTwA55oBSdvHmfxtLXyvdx/P3ZvB6VKAShvOy@1PPh5tckZYqbGh3AYIzQjORMZyFFw "Haskell – Try It Online") * uses 1>0 guard to handle operator `=` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes ``` ”y≔⁰θF⁺Sψ≡ι”FA⭆⪪”y≔,θI,θ”,⁺§ιλκ”yIθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9Rw9zKR51THjVuOLfj/Z5ljxp3vd@z@XzHo86F53YC5YBC7/csfLS27dGqVVClOiCFK4EkkK8DVH9o@bmd53af2wWSBkqc2/H/f3R0tFKiko6C0vs9O4CUcayOQrRSEkjg8HQgaQTmJ4P4QP1AytAULJICFulrBzoGyDIAi6WCxTqmAimL2NhYAA "Charcoal – Try It Online") Generates this Charcoal program: ``` ≔⁰θF⁺Sψ≡ιa≔XθI3θb≔×θI2θc≔⁺θI15θd≔⎇⁰θI0θe≔∕θI8θIθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9R55RHjRvO7Xi/Z9mjxl3v92w@3/Goc@G5nYlAifd7doAkVhqf25EE5B6eDuYZnduRDNa1C8w1ND23IwXE72uHGrTS4NyOVJBIx1Qw1wJMntvx/39yYlJKclJSKgA "Charcoal – Try It Online") Explanation: ``` ”y≔⁰θF⁺Sψ≡ι” ``` Print code that initialises the accumulator and switches over the input's characters, plus a null terminator, in a loop. ``` FA ``` Loop over each directive. ``` ⭆⪪”y≔,θI,θ”,⁺§ιλκ ``` Interleave the directive with the characters needed to turn it into a case clause. ``` ”yIθ ``` Print code to output the final value of the accumulator. The commands can be any ASCII string of the user's choice, not just a single letter. The required operators are as follows: * `X`: Exponentiation * `×`: Multiplication * `∕`: Division * `⁺`: Addition * `⁻`: Subtraction * `⎇⁰`: Assignment Two other operators are also supported, these are: * `÷`: Integer division * `﹪`: Modulo [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 68 bytes ``` lambda c:(f:=lambda p,a=0:f(p[1:],eval(f'(a{c[p[0]]})'))if p else a) ``` [Try it online!](https://tio.run/##TczLCoMwEAXQfb4iuJnECtVKQQL5EusizzbgI0QpFPHb0xG66GY4w5078bO9lrntYspBPvKoJm0VNYJ5IX9LrJSshWexb8RQubcamQemdtPHvh6GgwPnwdNI3bg6qng2k12ppDsoEFCWLVSgT90QBnFp7iiLErJGOdS1g4PEtDyxWBilrdHaFYSEeXMpJocTk8DO35zgJQbsL2Rnl/P8BQ "Python 3.8 (pre-release) – Try It Online") replaces the '=' operator with ':=' in order to utilize python 3.8+ walrus expressions [Answer] # Excel outputs VBA, 167 bytes ``` ="Function f(s) for i =1 to len(s) j=mid(s,i,1) select case j "&TEXTJOIN(" ",,IF(A:A="","","CASE """&A:A&""" a"&IF(B:B="=","","=a")&B:B&C:C))&" End Select Next f=a End Function" ``` Input is in columns A, B, C. Oddly enough output must be pasted somewhere else before it can be copied into VBA. Otherwise it adds quotes in weird places. Excel is a quirky one. [Answer] # [Python 2](https://docs.python.org/2/), 153 bytes ``` print"0 v\n<vi<" for c,p in input():n=int(p[1:],16);p=[n/10*"a+"+`n%10`+p[0],":"*n+"*"*n][p[0]=="^"];print"^>:'"+c+"'=?!v~"+p+"\n^v <" print" >~n" ``` [Try it online!](https://tio.run/##Jc3LCsIwEAXQvV8RL0gfEzBVfFBN/ZA0pbUqdjMGqQE3/fUa22EYDsOF677988WbcXTvjnsoIXzJZ9@dsXi83qKVTnQc1n36OMlZh1DsTJZbme2Tk9OG15lK0RCo5lWmanJGWYkcKRPScK35f7RGBXuaW6oij0AtIdKXpR9AjlBy5cU8oXvOiWJgjKOJ0UCi2iKRMa6B6WZiG0i7w@Rb8KAm3gPlEYn9AQ "Python 2 – Try It Online") Example output: # [><>](https://esolangs.org/wiki/Fish), 146 bytes ``` 0 v <vi< ^>:'a'=?!v~:::*** ^v < ^>:'b'=?!v~2* ^v < ^>:'c'=?!v~5a++ ^v < ^>:'d'=?!v~~0 ^v < ^>:'e'=?!v~8, ^v < >~n ``` [Try it online!](https://tio.run/##S8sszvj/30BBoYzLpizThivOzko9Ud3WXrGszsrKSktLiyuuTAECIJJJEEkjDIlkiIRporY2ulQKRKrOAF0iFSJhoYMsoWBXl8f1/39yYlJKclJSKgA "><> – Try It Online") Currently this only handles positive integers; Negative integers could probably be handled with some more bytes but float arguments would be a huge pain. Division is floating point by default, however. Commands must be one character, but that character can be totally arbitrary. The ><> program works by keeping only the accumulator on the stack in between commands. `/` is denoted by `,`, its ><> equivalent. `^` doesn't exist in ><>, so it's done by multiplying the accumulator by itself `n` times: e.g. `::::****` for `n=4`. `=` is implemented by dropping the accumulator with `~` and pushing the new value `n`. Example ><> program, commented: ``` 0 v | push 0 onto the stack; proceed down <vi< | read a command from input ^>:'a'=?!v~:::*** | The following pairs of lines: ^v < | :'c'= | non-destructively compare to command character ^>:'b'=?!v~2* | ?!v | proceed downwards if not equal ^v < | | otherwise ^>:'c'=?!v~5a++ | ~ | destroy the command ^v < | n | push the operand ^>:'d'=?!v~~0 | op | do acc <op> n ^v < | | implicitly wrap around, hit ^, proceed back up ^>:'e'=?!v~8, | ^v < | if no match is found we must be done >~n | destroy the terminating character and output | the last line will repeat and crash due to empty stack ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 55 bytes ``` lD/*##@0&@@ToExpression[#/.(#->"#"<>##2<>"&"&@@@l)]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P@f9pIUu@lrKyg4Gag4OIfmuFQVFqcXFmfl50cr6ehrKunZKyko2dsrKRjZ2SmpKQDUOOZqxav/TFWwV0qKrq5USlXSU4oDYWKlWp1opCcjSAmIjMC8ZyNIGYkNTMDcFyLQFYgMwLxXI0gdiCzAvDcjSVQARJkq1tbFcAUWZeSXR6XCGA0Q7yESQRpCtILvSlGqRlYCkU4BC/wE "Wolfram Language (Mathematica) – Try It Online") Input `^` for exponentiation and `-` for subtraction. --- ### 42 bytes ``` lD/*##@0&@@<|#->Curry[#2]@#3&@@@l|>/@#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P@f9pIUu@lrKyg4Gag4ONjXKunbOpUVFldHKRrEOysZAMYecGjt9B2W1/@kKtgpp0dXVSolKOgH55alFOsa1OtVKSUo6IZm5qcU6RiBeMlAup7RYx9AUxEtR0glOLdExALFTlXRcMssyU1J1LGprY7kCijLzSqLT4QwHsGqQfpBKkB1Ak2uRpUFSKUCh/wA "Wolfram Language (Mathematica) – Try It Online") This one's probably a bit too cheaty with the operator symbols - input the appropriate Mathematica function's name instead of the corresponding symbol. [Answer] # [Emotion](https://github.com/Quantum64/Emotion), 74 [bytes](https://quantum64.github.io/EmotionBuilds/1.2.0/?state=JTdCJTIybW9kZSUyMiUzQSUyMmNvZGVwYWdlJTIyJTdE) ``` 🤒😊😅🥑🥕🍌🍏🧖🤽😊😄🥦☕🌽😍😄🤼🚶🖕😌🤝🤧😍😁🧝🧟🧡👽😷😘😴👎🤕💌🙍😔😀🏃👉😰😍🤣🤴😼🙋🙎🌶🏌💣💌🙍😔😄🏃👉😰😔😃🏃👉😑🤺😕😚🤐😎⛷🤔😎⛷🤔😦🏃😺 ``` [Try it online!](https://quantum64.github.io/EmotionBuilds/1.2.0/?state=JTdCJTIyaW50ZXJwcmV0ZXJDb2RlJTIyJTNBJTIyJUYwJTlGJUE0JTkyJUYwJTlGJTk4JThBJUYwJTlGJTk4JTg1JUYwJTlGJUE1JTkxJUYwJTlGJUE1JTk1JUYwJTlGJThEJThDJUYwJTlGJThEJThGJUYwJTlGJUE3JTk2JUYwJTlGJUE0JUJEJUYwJTlGJTk4JThBJUYwJTlGJTk4JTg0JUYwJTlGJUE1JUE2JUUyJTk4JTk1JUYwJTlGJThDJUJEJUYwJTlGJTk4JThEJUYwJTlGJTk4JTg0JUYwJTlGJUE0JUJDJUYwJTlGJTlBJUI2JUYwJTlGJTk2JTk1JUYwJTlGJTk4JThDJUYwJTlGJUE0JTlEJUYwJTlGJUE0JUE3JUYwJTlGJTk4JThEJUYwJTlGJTk4JTgxJUYwJTlGJUE3JTlEJUYwJTlGJUE3JTlGJUYwJTlGJUE3JUExJUYwJTlGJTkxJUJEJUYwJTlGJTk4JUI3JUYwJTlGJTk4JTk4JUYwJTlGJTk4JUI0JUYwJTlGJTkxJThFJUYwJTlGJUE0JTk1JUYwJTlGJTkyJThDJUYwJTlGJTk5JThEJUYwJTlGJTk4JTk0JUYwJTlGJTk4JTgwJUYwJTlGJThGJTgzJUYwJTlGJTkxJTg5JUYwJTlGJTk4JUIwJUYwJTlGJTk4JThEJUYwJTlGJUE0JUEzJUYwJTlGJUE0JUI0JUYwJTlGJTk4JUJDJUYwJTlGJTk5JThCJUYwJTlGJTk5JThFJUYwJTlGJThDJUI2JUYwJTlGJThGJThDJUYwJTlGJTkyJUEzJUYwJTlGJTkyJThDJUYwJTlGJTk5JThEJUYwJTlGJTk4JTk0JUYwJTlGJTk4JTg0JUYwJTlGJThGJTgzJUYwJTlGJTkxJTg5JUYwJTlGJTk4JUIwJUYwJTlGJTk4JTk0JUYwJTlGJTk4JTgzJUYwJTlGJThGJTgzJUYwJTlGJTkxJTg5JUYwJTlGJTk4JTkxJUYwJTlGJUE0JUJBJUYwJTlGJTk4JTk1JUYwJTlGJTk4JTlBJUYwJTlGJUE0JTkwJUYwJTlGJTk4JThFJUUyJTlCJUI3JUYwJTlGJUE0JTk0JUYwJTlGJTk4JThFJUUyJTlCJUI3JUYwJTlGJUE0JTk0JUYwJTlGJTk4JUE2JUYwJTlGJThGJTgzJUYwJTlGJTk4JUJBJTIyJTJDJTIyaW50ZXJwcmV0ZXJBcmd1bWVudHMlMjIlM0ElMjJhJTJDbWF0aC5wb3clMkMzJTIwYiUyQ211bHRpcGx5JTJDMiUyMGMlMkNhZGQlMkMxNSUyMGQlMkNzZXQlMkMwJTIwZSUyQ2RpdmlkZSUyQzglMjIlMkMlMjJtb2RlJTIyJTNBJTIyaW50ZXJwcmV0ZXIlMjIlN0Q=) [Try the sample interpreter!](https://quantum64.github.io/EmotionBuilds/1.2.0/?state=JTdCJTIyaW50ZXJwcmV0ZXJDb2RlJTIyJTNBJTIyJUYwJTlGJTk4JTgwJUYwJTlGJTk5JTg0JUYwJTlGJUE0JUE3JUYwJTlGJTk4JUI3JUYwJTlGJTk4JTk4JUYwJTlGJUE0JTk5JUYwJTlGJTk4JTlBJUYwJTlGJTk4JTgxJUYwJTlGJThGJTgzJUYwJTlGJTk4JTk5JUYwJTlGJTk4JThFJUYwJTlGJTk4JUI3JUYwJTlGJTk4JTk4JUYwJTlGJTkxJTg4JUYwJTlGJTk4JTlBJUYwJTlGJTk4JTg0JUYwJTlGJTk4JUEyJUYwJTlGJTk4JThFJUYwJTlGJTk4JUI3JUYwJTlGJTk4JTk4JUYwJTlGJTkxJTg5JUYwJTlGJTk4JTlBJUYwJTlGJTk1JUI0JUYwJTlGJUE0JTlDJUYwJTlGJTk4JUIwJUYwJTlGJTk4JThFJUYwJTlGJTk4JUI3JUYwJTlGJTk4JTk4JUYwJTlGJTkxJTg2JUYwJTlGJTk4JTlBJUYwJTlGJTk4JTgwJUYwJTlGJTk4JThFJUYwJTlGJTk4JUI3JUYwJTlGJTk4JTk4JUYwJTlGJTk2JTk1JUYwJTlGJTk4JTlBJUYwJTlGJTk5JTgyJUYwJTlGJTk4JUFEJUYwJTlGJTk4JThFJUYwJTlGJTk4JThFJTIyJTJDJTIyaW50ZXJwcmV0ZXJBcmd1bWVudHMlMjIlM0ElMjJjYWJkY2JiZSUyMiUyQyUyMm1vZGUlMjIlM0ElMjJpbnRlcnByZXRlciUyMiU3RA%3D%3D) The input is a string of space-separated directives. Each directive is a comma-separated list of the instruction name, the operation, and the value. The operation names have been changed for efficiency: `+` -> `add` `-` -> `subtract` `*` -> `multiply` `/` -> `divide` `**` -> `math.pow` Explanation ``` 🤒 Store the first stack value in the a register. 😊😅🥑🥕🍌🍏🧖🤽 Push literal load 0 😊😄🥦☕🌽 Push literal swp 😍😄🤼🚶🖕 Push literal iterate 😌 Push the value contained in the a register. 🤝 Push a list of the first stack values split by spaces. 🤧 Enter an iteration block over the first stack value. 😍😁🧝🧟🧡👽 Push literal ldr o 😷 Push the value contained in the iteration element register. 😘😴 Push literal , 👎 Push a list of strings obtained by splitting the second stack value with the first stack value. 🤕 Store the first stack value in the b register. 💌🙍 Push literal load 😔 Push the value contained in the b register. 😀 Push literal 0 🏃👉 Push the value in the list of the second stack value at the index of the first stack value. 😰 Push the sum of the second and first stack values. 😍🤣🤴😼🙋🙎🌶🏌💣 Push literal if equal 💌🙍 Push literal load 😔 Push the value contained in the b register. 😄 Push literal 2 🏃👉 Push the value in the list of the second stack value at the index of the first stack value. 😰 Push the sum of the second and first stack values. 😔 Push the value contained in the b register. 😃 Push literal 1 🏃👉 Push the value in the list of the second stack value at the index of the first stack value. 😑 Push a copy of the first stack value. 🤺😕 Push literal set 😚 Enter a conditional block if the top two stack values are equal. 🤐 Remove the first stack values from the stack. 😎 End a control flow structure. ⛷🤔 Push literal end 😎 End a control flow structure. ⛷🤔 Push literal end 😦 Collapse all stack values into a list, then push that list. 🏃😺 Compile a list of Emotion instructions on the top of the stack and print the compiler output. ``` [Answer] # [CSASM v2.3.0.1](https://github.com/absoluteAquarian/CSASM/releases/tag/v2.3.0.1), 985 bytes Looks like we've come full circle. CSASM is a language written with a C# backer and is parsed by a C# interpreter and this code generates C# code that's an interpreter for another language... --- Generates a C# file named `a` in the same directory the CSASM executable is executed from. Expects a space-separated string for the commands and no spaces within the commands themselves. **Example (input: `a+1 b*3 c**2 d/4 e=0`):** Output: ``` using System;class A{static void Main(){var a=0.0;var s=Console.ReadLine();for(int i=0;i<s.Length;i++){if(s[i]=='a')a=a+1;else if(s[i]=='b')a=a*3;else if(s[i]=='c')a=Math.Pow(a,2);else if(s[i]=='d')a=a/4;else if(s[i]=='e')a=a=0;}Console.Write(a);}} ``` Formatted: ``` using System; class Program{ static void Main(){ var a = 0.0; var s = Console.ReadLine(); for(int i = 0; i < s.Length; i++){ if(s[i] == 'a') a = a + 1; else if(s[i] == 'b') a = a * 3; else if(s[i] == 'c') a = Math.Pow(a, 2); else if(s[i] == 'd') a = a / 4; else if(s[i] == 'e') a = a = 0; } Console.Write(a); } } ``` ### Code ``` func main: .local a : i32 .local b : str .local c : f64 lda 0 sta $1 in "" push " " div pop $a push 1 pop $io.f0 push 2 pop $io.m0 push 1 pop $io.s0 push "a" pop $io.p0 io.w0 "using System;class A{static void Main(){var a=0.0;var s=Console.ReadLine();for(int i=0;i<s.Length;i++){" .lbl a push $a dup ldelem $1 dup pop b push "**" index push 1 add pop a push b len pop $5 push 0 pop $2 .lbl b push b conv ~arr:char ldelem $2 pop $3 clf.o push $2 push 2 comp.gte push $f.o brfalse m clf.o push $3 push '+' comp push $f.o brtrue g push $3 push '-' comp push $f.o brtrue g .lbl m clf.n push $3 conv str pop $3 clf.n push b push $2 push $5 substr conv f64 pop c push $f.n brtrue h push $2 brtrue f push $1 brfalse e io.w0 "else " .lbl e push "if(s[i]=='" push $3 add push "')a=" add pop $4 io.w0 $4 br i .lbl f push a brfalse g io.w0 "Math.Pow(a," inc $2 br i .lbl g push "a" push $3 add pop $3 io.w0 $3 br i .lbl h io.w0 c push $5 push 1 sub pop $2 push a brfalse k io.w0 ")" .lbl k io.w0 ";" .lbl i inc $2 push $2 push $5 sub brtrue b inc $1 push $a len push $1 sub brtrue a io.w0 "}Console.Write(a);}}" push null pop $io.p0 ret end ``` **Commented and ungolfed:** ``` func main: ; these locals are needed since CSASM only has 6 value registers .local hasExponent : i32 .local curCommand : str .local commandValue : f64 ; Initialize the outer loop counter to zero lda 0 sta $1 ; Get the input, split it along space chars and put it in $a in "" push " " div pop $a ; Initialize a file handle as writing, FileMode.Create and Stream push 1 pop $io.f0 push 2 pop $io.m0 push 1 pop $io.s0 ; Start the handle by setting the file path push "a" pop $io.p0 ; The first chunk of the generated program io.w0 "using System;class A{static void Main(){var a=0.0;var s=Console.ReadLine();for(int i=0;i<s.Length;i++){" .lbl outerLoop ; Get the value in $a at index $1 push $a dup ldelem $1 ; Then set the variable "hasExponent" to if said value contains "**" dup pop curCommand push "**" index push 1 add pop hasExponent ; Store the length into "$5" push curCommand len pop $5 ; Initialize the inner loop counter to zero push 0 pop $2 .lbl innerLoop ; Get the char in "curCommand" at index $2 and put it in $3 push curCommand conv ~arr:char ldelem $2 pop $3 ; Clear the Comparison flag clf.o ; if $2 >= 2, ignore the check below push $2 push 2 comp.gte push $f.o brfalse checkCommandValue clf.o ; if $3 == '+' or $3 == '-', don't try to parse the rest of the string ; as an <f64> yet push $3 push '+' comp push $f.o brtrue printCommandStart push $3 push '-' comp push $f.o brtrue printCompoundStart .lbl checkCommandValue ; Clear the Conversion flag clf.n ; Convert the current char into a string and put it back into $3 push $3 conv str pop $3 clf.n ; Get the rest of the substring push curCommand push $2 push $5 substr conv f64 pop commandValue push $f.n brtrue printStatementEnd ; If $2 is > 0, the stuff after the "a=" part needs to be checked push $2 brtrue checkPowStart ; If this is the first command being parsed, don't print the "else" part push $1 brfalse printStatementStart io.w0 "else " .lbl printStatementStart ; Begin the if block push "if(s[i]=='" push $3 add push "')a=" add pop $4 io.w0 $4 br getNextChar .lbl checkPowStart ; If a is non-zero, this command used "**". Thus, it needs to be converted ; to Math.Pow() push hasExponent brfalse printCompoundStart io.w0 "Math.Pow(a," inc $2 br getNextChar .lbl printCompoundStart ; The other commands follow the pattern of "a = a <operator> <value>;" push "a" push $3 add pop $3 io.w0 $3 br getNextChar .lbl printStatementEnd ; Print the value at the end of the command, then close the statement io.w0 commandValue push $5 push 1 sub pop $2 push hasExponent brfalse notPowStatementClose io.w0 ")" .lbl notPowStatementClose io.w0 ";" .lbl getNextChar ; Increment $2 and see if there's still more chars to parse inc $2 push $2 push $5 sub brtrue innerLoop ; Increment $1 and see if there's more commands to parse inc $1 push $a len push $1 sub brtrue outerLoop ; The last chunk of the generated program io.w0 "}Console.Write(a);}}" ; Close the file handle by setting the path to null push null pop $io.p0 ret end ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~102~~ 100 bytes Inspired by [@Zaelin Goodman](https://codegolf.stackexchange.com/a/221133/80745) ``` 'switch("$args"|% t*y){' $args-replace'^.','$0{$a=$a$''}#'-replace'.a.(\*\d+)','"$a*"$1+1|iex' '}$a' ``` [Try it online!](https://tio.run/##PYzRCoJAEADf/YrDNlb36vKKoBf/RILtXFI4SO4EC/XbL@mhx2GGGV6ThNiJ9ylhnPrRdUUOHJ4xX/ZqpE85Y/bjY5DBsxO8GzwgVDNwDQyI6w7/zrApGmpaXW7N9qEcrLZLL2/McAXGlBITXdSDzsppe1VtXSk53b4 "PowerShell – Try It Online") With arguments `a**3 b*2 c+15 d=0 e/8` the script generates: ``` switch("$args"|% t*y){ a{$a="$a*"*3+1|iex}#**3 b{$a=$a*2}#*2 c{$a=$a+15}#+15 d{$a=$a=0}#=0 e{$a=$a/8}#/8 }$a ``` [Try it online!](https://tio.run/##JchNCoMwEEDh/ZyiJCm048I/Cm5ymEkcqiC0GMEWnbNPU7J58L33a@c1TbwsqmmftzjdjKP1mcx5vWz4vR9AhyOfJxrsq/ac@SMWsYfw/3l3mR3Eoqp9iM2Bsdg3Yn0DXFQPYusBxJGqRgpjDIF/ "PowerShell – Try It Online") ]
[Question] [ ## Challenge: Given a square input matrix \$A\$, pad the matrix with one row and one column on all four sides. * The value of each element in the top and bottom row should be the sum of the elements in each corresponding column. * The value of each element in the left and right column should be the sum of the elements in each corresponding row. * The value of the elements in the top left, and bottom right corner should be the sum of the elements on the diagonal * The value of the elements in the top right, and bottom left corner should be the sum of the elements in the anti-diagonal. ### Example: ``` A = 1 5 3 3 2 4 2 5 5 Output: 8 6 12 12 7 9 1 5 3 9 9 3 2 4 9 12 2 5 5 12 7 6 12 12 8 ``` **Explanation:** The top left and bottom right elements are the sum of the diagonal \$1+2+5=8\$. The top right and bottom left elements are the sum of the anti-diagonal \$2+2+3=7\$. The top and bottom row (except the corners) are the sum of each of the columns in \$A\$: \$1+3+2=6\$, \$5+2+5=12\$ and \$3+4+5=12\$. Similarly, the left and right column (except the corners) are the sum of each of the rows of \$A\$: \$1+5+3=9\$, \$3+2+4=9\$ and \$2+5+5=12\$. ### Input: * A non-empty square matrix, with non-negative integers. * Optional format ### Output: * The matrix padded as explained above * Optional format, but it must be the same as the input format ## Test cases: Use the submissions in [this challenge](https://codegolf.stackexchange.com/q/129136/31516) if you want to convert the input format to a more suitable one (for instance `[[1, 5],[0, 2]]`). ``` 0 ---------------- 0 0 0 0 0 0 0 0 0 ``` ``` 1 5 0 2 ---------------- 3 1 7 5 6 1 5 6 2 0 2 2 5 1 7 3 ``` ``` 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 ---------------- 65 65 65 65 65 65 65 65 17 24 1 8 15 65 65 23 5 7 14 16 65 65 4 6 13 20 22 65 65 10 12 19 21 3 65 65 11 18 25 2 9 65 65 65 65 65 65 65 65 ``` ``` 15 1 2 12 4 10 9 7 8 6 5 11 3 13 14 0 ---------------- 30 30 30 30 30 30 30 15 1 2 12 30 30 4 10 9 7 30 30 8 6 5 11 30 30 3 13 14 0 30 30 30 30 30 30 30 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution **in each language** wins. Explanations are highly encouraged. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes ``` ,UŒDḢ$S$€,Ṛ$j€SW€jSẋ¥€2$j"$ ``` [Try it online!](https://tio.run/##y0rNyan8/18n9Ogkl4c7FqkEqzxqWqPzcOcslSwgIzgcSGQFP9zVfWgpkGWkkqWk8v///@hoQx0F01gdhWgDHQWj2FgA "Jelly – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 64 bytes Thanks to Tom Carpenter for both saving 4 bytes, *and* correcting an error I had in the original code! ``` @(a)[b=(t=@trace)(a),c=sum(a),d=t(flip(a));z=sum(a,2),a,z;d,c,b] ``` [Try it online!](https://tio.run/##LU1BCoMwELz3FXtMYBGzVq2EgP8QDxoNFFpa2rQHP59OtIdkZ2Z3Zh4@Tt81BVcURerVpIfZqej6@Jr8qsHZu/fnnsHiogq36xNY2@1QWTRPvNmFPc9jCqrUp6AGw1RbKplkPHgLeGaCfsGPnVQ4YYJust5YwmiAoEs2iiWDaQSvA4e1goRhECHwYtP94@s9Op/KHpSdMLU21zV7kzGWqiM/N5ajTj8 "Octave – Try It Online") **Explanation:** ``` @(a) % Anonymous function that takes the matrix 'a' as input [ ... ] % Concatenate everything inside to a single matrix b=(t=@trace)(a), % Clever trick by Tom Carpenter. Save a function handle % for 't=trace', and call it with 'a' as input % Save the result in the variable 'b' c=sum(a) % Sum of all columns of 'a' d=t(flip(a)); % Save the trace of 'a' flipped as a variable 'd', while % concatenating [b,c,d] horizontally at the same time, creating the % first row of the output z=sum(a,2) % The sum of each row of the input, and store it in a variable 'z' ,a,z; % Concatenate it with 'a' and 'z' again, to create the middle part of the output d,c,b] % Add [d,c,b] to complete the bottom row ``` --- Note, I wrote this long after I posted the challenge. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~27~~ 26 bytes ``` ,!tXswyv]GXds5L(PGPXds5L(P ``` [Try it online!](https://tio.run/##y00syfn/X0exJKK4vLIs1j0ipdjURyPAPQDK@P8/2lDBVMHYWsFYwUjBxBpImCqYxgIA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##LY69CsJAEIR7n2KsYmHgZpNLclxrkcIihcVBCChYapUQ8enPObDYZZmfj30/tle@pzGfj1taP999GdNz9dfTNE7/I1d1XVfpcssz4dFENDC0UcvDL4fZaeREOFg5e1gLYgClWaMUelBSF9GiA9VX1CLoQAMDjIVLggPMixwKyIsi20pN0YA@itoJSJYvBBLWLT8). ### Explanation ``` , % Do the following twice ! % Tranpose. Takes input implititly in the first iteration t % Duplicate Xs % Row vector with the sum of each column wy % Push a copy to the bottom of the stack v % Concatenate stack vertically. This attaches the sum of % each row (first iteration) and column (second), leaving % the matrix with the correct orientation (transposed twice) ] % End G % Push input again Xds % Column vector with the diagonal of the matrix. Sum of vector 5L( % Write that into first and last entries of the result matrix % matrix; that is, its upper-left and lower-right corners P % Flip result matrix vertically GP % Push input matrix vertically flipped Xds % Diagonal, sum. Since the input has been vertically flipped, % this gives the sum of the anti-diagonal of the input. 5L( % Write that into the upper-left and lower-right corners of % the verticallly flipped version of the result matrix P % Flip vertically again, to restore initial orientation % Implicitly display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes ``` ŒDµḊṖѵ€1¦ŒḌU S;;S Ç€Zµ⁺ÑÑ ``` [Try it online!](https://tio.run/##y0rNyan8///oJJdDWx/u6Hq4c9rhiYe2PmpaY3ho2dFJD3f0hHIFW1sHcx1uB4pFAWUadx2eeHji////o6MNTXUUgMAQTBqBSEOjWB2uaAUTMNsALG4JJs3B4hZgthmYBOs1NASLG4PZEBKsV8EgNhYA "Jelly – Try It Online") Looks surprisingly different from [Erik's solution](https://codegolf.stackexchange.com/a/129734/30164). I finally managed to understand how `¦` works (by debugging through Jelly's code, lol). Too bad it requires a `€` to work with `Ç` in my case. ### Explanation The code uses three links. The first helper link pads a vector with its sum on both ends, the second helper link fixes two corners of the matrix and the main link calls these appropriately. ``` Ç€Zµ⁺ÑÑ Main link. Argument: M (matrix) Ç Call the first helper link (pad row with sums)... € ...on each row of the matrix. Z Transpose, so that the second invocation uses the columns. µ Begin a new monadic chain. ⁺ Repeat the previous chain (everything up to here). ÑÑ Call the second helper link twice on the whole matrix. S;;S First helper link. Argument: v (1-dimensional list) S Sum the argument list. ; Append the argument list to the sum. ; Append... S ...the sum of the argument list. ŒDµḊṖѵ€1¦ŒḌU Second helper link. Argument: M (matrix) ŒD Get the diagonals of the matrix, starting with the main diagonal. µ Begin a new monadic chain. µ€ Perform the following actions on each diagonal... 1¦ ...and keep the result for the first item (main diagonal): Ḋ Remove the first item (incorrect top corner). Ṗ Remove the last item (incorrect bottom corner). Ñ Call the first helper link on the diagonal to pad it with its sum. ŒḌ Convert the diagonals back to the matrix. U Reverse each row, so that consecutive calls fix the other corners. ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 37 bytes ``` (d,+⌿,d∘⌽)⍪(+/,⊢,+/)⍪d∘⌽,+⌿,d←+/1 1∘⍉ ``` [Try it online!](https://tio.run/##NY0xCsJAEEWv8stdNpLMZDcmxwkEbQLaeoGgkkBKayuxthXBo@xF4l@IxQ4789@8aY/9pju1/WG/LLs4zKbLXBw/WRfPtzi@bZyexuVZvN4zl6duDf7UMLtcIGk4Xaj4PkyJMk4vQQB/UHi@gGDXoLBGoStRQK1hmNot1ENQQwK0ZLiFcFBRUEFoIqyQAsLaQIV24e0aygU01nj4JAq0aKJ8oht6ahpCgsskorWwPw "APL (Dyalog Unicode) – Try It Online") `1 1∘⍉` diagonal (lit. collapse both axes into one) `d←` store that function as *d* and apply it to the argument `+⌿` prepend the column sums `d∘⌽,` prepend *d* applied to the reversed argument `(`…`)⍪` stack the following on top:  `+/,⊢,+/` row sums, the unmodified argument, row sums `(`…`)⍪` stack the following on top:  `d,+⌿,d∘⌽` applied to the argument, column sums, *d* applied to the reversed argument [Answer] # [Python 3](https://docs.python.org/3/), 155 bytes This is the suggestion of @LeakyNun, which saves **54 bytes**. I then golfed it myself a bit. ``` def f(m):l=len(m);r=range(l);s=sum;b=[s(m[i][i]for i in r)];c=[s(m[i][l+~i]for i in r)];d=[*map(s,zip(*m))];return[b+d+c,*[[s(a),*a,s(a)]for a in m],c+d+b] ``` [Try it online!](https://tio.run/##dU65boQwEO3zFS5tmGJtwl6IL7FcmCtBwl5k2CIp8uvkDavdIlIkzIzf6flr/bzFYtu6fhCDDOo61VMfsVSpTj5@9HJS1VIv91A1tV1ksKPDN9ySGMUYRVKual/ElP/84braZsHPcqHvcZZZUMBSv95TtE3e5S1lFmavKPPEc3d7dgdHLRSN2@Y0xlUO0lp9ImHeSWgSZ/xLR9YUJEoSIDQTR0CYR6wgzAHHANJYtMG5AIC7YAxTI8bADurinFJvj67n3DvLvY/NSBKczmkIOvH1vJexRvO1eBTzWw7/BULOUn4bS7Zf "Python 3 – Try It Online") # Initial solution - [Python 3](https://docs.python.org/3/), 216 bytes ``` def f(m):l=len(m);r,s=range(l),sum;a,b,c,d=s(m[i][i]for i in r),s(m[i][l-i-1]for i in r),[s(m[i][j]for j in r)for i in r],[s(m[i][j]for i in r)for j in r];print([[a]+d+[b]]+[[c[i]]+m[i]+[c[i]]for i in r]+[[b]+d+[a]]) ``` [Try it online!](https://tio.run/##ZU/JboMwEL3nK@YI8kSKTclSxJdYPkCA1hE4kUkP@XryBldKFwnj8Vvt2@P@eQ3FsnT9QEM25e9jPfYBQxV5rmMTPvpszHn@mqqGWz5zV8/ZZL3DN1wjefKBIgQJHLd@q38R9pu5rOgloS@B@yPwL0HSuuoWfbhn1jZOdcq2zilrz3A4JT6V5h@JoNtV2jiXLwOc@sBk3pg00xH/EqWmYCqZQGgh9oCw7zGCMDssA0hj0AbrBADuQjDsGjEGdlAnlGzSFfPNWlauReJCBEmsxCDhIMfj2iIaLcciNcoldv@SoBON3Eae8gQ "Python 3 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~268~~ ~~250~~ ~~184~~ 174 bytes 10 thanks to Stewie Griffin ``` from numpy import * a,c,v,s=sum,trace,vstack,matrix(input()) l,r,d,e=a(s,0),a(s,1),c(s),c(fliplr(s)) print hstack((v(([[d]],r,[[e]])),v((l,s,l)),v(([[e]],r,[[d]])))).tolist() ``` [Try it online!](https://tio.run/##JY1LjsMgEET3PkUvISpFgUx@i5wEsUC2o6ABGwG2Jqf3NM6im6d6ojp96nue9La98hxpWmL6kI9pzpUOnUOPFeVZloiaXT9iLdX1v4iuZv8n/JSWKqTsAjIGjE8nCk4S7VESvShtvYJPITPLLmU/VXrvJUKsQhgzWMufjRmtlRIcBRSEL@7pbodmpTzWOfjCJ7fNGHUD6R@QAt15XyzI6DPoAmKjmrm2jOHKzEafeHTLFJPSPA9OuOC8hwyKqzQ3sGNl7T8 "Python 2 – Try It Online") **Some explanations** The input is uploaded as a matrix. First the code computes the sum of each column and each row using numpy.sum. Then it computes the sum of the diagonal by numpy.trace. After this it obtains the other diagonal by making a left-right flip on the matrix. Finally, it uses numpy.vstack and numpy.hstack to glue the pieces together. [Answer] # R, 129 bytes ``` pryr::f(t(matrix(c(d<-sum(diag(m)),c<-colSums(m),a<-sum(diag(m[(n<-nrow(m)):1,])),t(matrix(c(r<-rowSums(m),m,r),n)),a,c,d),n+2))) ``` An anonymous function that takes a square matrix as input. I'll post an explanation if there's interest. [Answer] # [PHP](https://php.net/), 211 bytes ``` <?foreach($_GET as$l=>$r){$y=0;foreach($r as$k=>$c){$y+=$c;$x[$k]+=$c;$l-$k?:$d+=$c;($z=count($_GET))-1-$k-$l?:$h+=$c;}$o[]=[-1=>$y]+$r+[$z=>$y];}$o[]=[-1=>$h]+$x+[$z=>$d];print_r([-1=>[-1=>$d]+$x+[$z=>$h]]+$o); ``` [Try it online!](https://tio.run/##XY5NasMwEIX3OUVQZ2FjGzxOnJ@qalalF@hOiBDsBgWbWKgJJC09uzsjG9N2odEbfW@exlnXP@2cdTPYv768Ka0FilSUdBbCpJpqKgo6y9AVIyuFMXL2MM3k/3pc89iSCqdt@C6HgMWYwAYMhlUALFfchg9zLkUAyBr5Y9zyK06rIUvk8KIct9zyHv2x8@@HykZhnfnhA1r1DD7@grvK5QQ9k4ZIxSRRUEm4aWjMINsMmt0j1KGL4FNV3fV8GTLjOEPCGbTksMHxDZ02SmdIgXeTgE80zbD@gyyh24hqI50/nS97HwU4OOpfDmuo6WLZ9z8 "PHP – Try It Online") Expanded ``` foreach($_GET as$l=>$r){ $y=0; # sum for a row foreach($r as$k=>$c){ $y+=$c; # add to sum for a row $x[$k]+=$c; # add to sum for a column and store in array $l-$k?:$d+=$c; # make the diagonal sum left to right ($z=count($_GET))-1-$k-$l?:$h+=$c; # make the diagonal sum right to left } $o[]=[-1=>$y]+$r+[$z=>$y]; # add to result array the actual row with sum of both sides } $o[]=[-1=>$h]+$x+[$z=>$d]; # add to result array the last array print_r([-1=>[-1=>$d]+$x+[$z=>$h]]+$o); #output after adding the first array to the result array ``` [Answer] # [Python 3](https://docs.python.org/3/), 125 bytes ``` from numpy import* f=lambda m,t=trace,s=sum:c_[r_[t(m),s(m,1),t(m[::-1])],c_[s(m,0),m.T,s(m,0)].T,r_[t(m[::-1]),s(m,1),t(m)]] ``` [Try it online!](https://tio.run/##dVDLboMwELznK3zE0bZiTcgDib/ozbIiNy1qpBiQcQ58PZk1OVRVc8Hj2Z2HGef0M/TVsnRxCKq/h3FW1zAOMW03XXvz4fPLq0CpTdFfvmlqp3toLmcbzzYVQdNUBGJNwLZp3thpR5gKW2oK7x@0Qge0Sp5rv4TauWWM1z4VXeFj9HNhLZOqSVWOlK1IGVI7gSaztXNa681fSfk/LU6iLWHzYuOA0Y4UNo/4YtuaKidhwDLYg8K5B5Q2YmVAMQCjE59AcK5rGSfDxtS59ulFZJ3jRGuknITADD4HuR5zluzw8w9IrlRZH7k8AA "Python 3 – Try It Online") Slightly ungolfed: ``` import numpy as np def f_expanded(m): return np.c_[np.r_[np.trace(m), np.sum(m, 1), np.trace(m[::-1])], np.c_[np.sum(m, 0), m.T, np.sum(m, 0)].T, np.r_[np.trace(m[::-1]), np.sum(m, 1), np.trace(m)]] ``` This takes input formatted as a numpy array, then uses the `np.c_` and `np.r_` indexing tools to build a new array in one go. `np.trace` and `np.sum`are used to calculate the sums along the diagonals and everywhere else, respectively. `T` is used to take the transpose before and after concatenating the sums because it's shorter than making all the arrays 2-dimensional and using `np.r_`. `m[::-1]` saves bytes when compared to `rot90(m)` or `fliplr(m)` for finding the trace for the second diagonal. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 19 bytes ``` ,U$⁺Æṭj€SW€j§,"`j"Ɗ ``` [Try it online!](https://tio.run/##TU8xCsJQDN1zivBxETo0v7baE3gAUQcRXFyKF3CrIhY8g84uuoiD1U1BvEZ7kW8SrXZI8v7j5b38ZDqbzZ3z@o1ycX2si/yYlMtDb8gtue89M0nMc@OK2/meP7PicmJeEI8B1yPrFvnqtS/TbZnuGDYr7NwIjDFAiBhyBRBwt1wtsF8uFIWnMv8PiXkfbY1oy2aLG4obdgSEYMVQfVAEJAKKAFUYyUMTfWkWSCZJMsXCqFMAJJPE0aqTCDCuZYe/WN21H391w1izQQ/SRL2GCDCo4vUq1N/B@A0 "Jelly – Try It Online") I know there's already 2 Jelly answers, but this, I think, is fairly different from them both, and is shorter. The Footer in the TIO link converts the inputs into 2D arrays, runs the above link over them then outputs them similar to the input format. ## How it works ``` ,U$⁺Æṭj€SW€j§,"`j"Ɗ - Main link. Takes a matrix A on the right $ - Collect the previous two links: U - Reverse each row of A rev(A) = A with reversed rows , - Yield the pair [A, rev(A)] ⁺ - Do this again on [A, rev(a)]: [A, rev(A)]U -> [rev(A), A] [A, rev(A)],U$ -> [[A, rev(A)], [rev(A), A]] Æṭ - Take the trace of each. This returns [[Tr(A), Tr(rev(A))], [Tr(rev(A)), Tr(A)]] where Tr(·) returns the trace S - Yield the sums of the columns of A € - Over each pair in l: j - Insert the column sums between their elements W€ - Wrap each in an array Ɗ - Group and run the previous commands on A: § - Yield the row sums of A ,"` - Pair each with itself " - Zip the rows of A with the pairs of row sums j - Insert each row between each pair. j - Insert the rows plus their sums in between the diagonal and column sums ``` [Answer] # JavaScript (ES6), 170 bytes ``` (a,m=g=>a.map((_,i)=>g(i)),s=x=>eval(x.join`+`))=>[[d=s(m(i=>a[i][i])),...c=m(i=>s(m(j=>a[j][i]))),g=s(m(i=>a[i][a.length-i-1]))],...a.map(b=>[r=s(b),...b,r]),[g,...c,d]] ``` Input and output is a 2D array of numbers. ## Explained ``` (a, // input matrix: a m=g=>a.map((_,i)=>g(i)), // helper func m: map by index s=x=>eval(x.join`+`) // helper func s: array sum ) => [ [ d = s(m(i=>a[i][i])), // diagonal sum: d ...c=m(i=>s(m(j=>a[j][i]))), // column sums: c g = s(m(i=>a[i][a.length-i-1])) // antidiagonal sum: g ], ...a.map(b=>[r = s(b), ...b, r]), // all rows with row sums on each end [g, ...c, d] // same as top row, with corners flipped ] ``` ## Test Snippet Input/output has been formatted with newlines and tabs. ``` f= (a,m=g=>a.map((_,i)=>g(i)),s=x=>eval(x.join`+`))=>[[d=s(m(i=>a[i][i])),...c=m(i=>s(m(j=>a[j][i]))),g=s(m(i=>a[i][a.length-i-1]))],...a.map(b=>[r=s(b),...b,r]),[g,...c,d]] let tests=[[[0]],[[1,5],[0,2]],[[17,24,1,8,15],[23,5,7,14,16],[4,6,13,20,22],[10,12,19,21,3],[11,18,25,2,9]],[[15,1,2,12],[4,10,9,7],[8,6,5,11],[3,13,14,0]]]; ``` ``` <select id=S oninput="I.value=S.selectedIndex?tests[S.value-1].map(s=>s.join`\t`).join`\n`:''"><option>Tests<option>1<option>2<option>3<option>4</select> <button onclick="O.innerHTML=I.value.trim()?f(I.value.split`\n`.map(s=>s.trim().split(/\s+/g))).map(s=>s.join`\t`).join`\n`:''">Run</button><br><textarea rows=6 cols=50 id=I></textarea><pre id=O> ``` [Answer] ## [LOGO](https://sourceforge.net/projects/fmslogo/), 198 bytes ``` to g :v[:h reduce "+ :v] op(se :h :v :h) end to f :s[:a reduce "+ map[item # ?]:s][:b reduce "+ map[item # reverse ?]:s][:c apply "map se "sum :s] op `[[,:a ,@:c ,:b],@[map "g :s][,:b ,@:c ,:a]] end ``` The function `f` takes in a matrix as a 2D list, then output the resulting matrix. `g` is helper function. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 38 bytes ``` ODŠζsζ€R€˜IÅ\OUIÅ/OVIÅ|ODXšYªsXªYšŠšsª ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f3@XognPbis9te9S0JgiIT8/xPNwa4x8KJPX9w4Bkjb9LxNGFkYdWFUccWhV5dOHRBUcXFh9a9f9/dLShjmmsTrSBjlFsLAA) ### Input A list of lists as a representation of a matrix. ### Output A list of lists as a representation of a matrix. ### Explanation ``` ODŠζsζ€R€˜IÅ\OUIÅ/OVIÅ|ODXšYªsXªYšŠšsª OD Sum of rows and duplicate Š Triple swap ζ Zip arrays (to append to the rows) sζ Swap and do the same (to prepend to the rows) €R€˜ Reverse each row and deep flat each row, making the new rows. IÅ\OU Get the diagonal of the input, sum it and save in variable X IÅ/OV Get the anti-diagonal of the input, sum it and save in variable Y IÅ|OD Get the columns of the input, sum it and duplicate the sums vector. Xš Prepend variable x Yª Append variable y sXªYš Repeat for the second row, but now the prepend and append values are switched Ššsª Append and Prepend the new rows (first and last) ``` ]
[Question] [ Given Google's recent announcement of official [Kotlin](https://kotlinlang.org/) support for Android development, I thought it might be timely to poll the community for some awesome golfing tips for this relatively new JVM language. Kotlin includes a unique combination of features among it's JVM siblings which makes it potentially attractive for golfing: * [operator overloading](https://kotlinlang.org/docs/reference/operator-overloading.html#operator-overloading) * [local](https://kotlinlang.org/docs/reference/functions.html#local-functions), [infix](https://kotlinlang.org/docs/reference/functions.html#infix-notation), and [static extension functions](https://kotlinlang.org/docs/reference/extensions.html#extensions) * [smart casts](https://kotlinlang.org/docs/reference/typecasts.html#smart-casts) * [Groovy-style type-safe builders](https://kotlinlang.org/docs/reference/type-safe-builders.html#type-safe-builders) * [type aliases](https://kotlinlang.org/docs/reference/type-aliases.html#type-aliases) * [ranges](https://kotlinlang.org/docs/reference/ranges.html#ranges) * an extensive functional [collections package](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index.html) * [scripting support](https://kotlinlang.org/docs/tutorials/command-line.html#using-the-command-line-to-run-scripts) So, how do I squeeze the last few bytes out of my Kotlin program? One tip per answer, please. [Answer] # Use `+` instead of `toString` As one might expect, `String` overloads the `+` operator for string concatenation, like so. ``` print("Hel" + "lo") ``` However, checking [the docs](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/plus.html) tells us that it accepts `Any?`, not just `String`. As stated: > > Returns a string obtained by concatenating this string with the string representation of the given other object. > > > In other words, `String + anything` makes sure to call `.toString()` on the right hand side before concatenating. This allows us to shorten `it.toString()` to `""+it`, a massive 8 byte savings at best and 6 bytes at worst. --- # Use `fold` instead of `joinToString` Related to the above, if you're calling `map` and then `joinToString`, you can shorten that by using `fold` instead. ``` list.map{it.repeat(3)}.joinToString("") list.fold(""){a,v->a+v.repeat(3)} ``` [Answer] Starting from 1.3 you [can omit args in fun main()](https://kotlinlang.org/docs/reference/whatsnew13.html) completely, thus shaving off 18 chars (that is, the length of `args:Array<String>`). [Answer] # Submitting Lambdas: A Guide [According to meta consensus](https://codegolf.meta.stackexchange.com/questions/6915/how-do-we-calculate-the-length-of-lambda) the default for most challenges allows submitting lambdas/anonymous function bodies. Part of this consensus is that the declaration/assignment of the lambda doesn't have to be included. Take the typical lambda: ``` val f={a:Int,b:Int->a+b} ``` We can omit the declaration, that being `val f=` which saves us 6 bytes. ``` val f= // declaration {a:Int,b:Int->a+b} // lambda ``` For the rest of this tip I will write the declaration on one line and the lambda body on the next line to make it clear that it is separate. Know that the declaration line won't count to the score; on TIO you'd include it in the Header and put the lambda as the Code [(see here.)](https://tio.run/##y84vycnM@1@WmKOQZvu/OtHKM69EJwlE6tolaifV/k8rzVPITczM09BUsFUoKMrMK9FI0zDUMdLU/A8A "Kotlin – Try It Online") ## Type Inference and You Kotlin has a fairly robust system of *type inference*. If the compiler can infer the type of something, you can omit the type information. Lambdas themselves are typed; their type signatures are expressed as: ``` (Param1Type, ...ParamNType) -> ReturnType ``` Therefore, the type of the above is `(Int, Int) -> Int`. The type information of a lambda can be inferred from two places: * The lambda body * The declaration/use site (when assigned to a variable with a type annotation, or passed to a function) In the given example above, the types of the parameters are stated *in* the lambda body, and the return type of the lambda can be inferred by the expression in the body because the types of everything is known. This is why the type of the lambda doesn't have to be stated in the declaration; the compiler knows its complete type signature! ...but what if we did? ## A Parlor Trick ``` val f:(Int,Int)->Int= {a,b->a+b} ``` By moving the type information of the lambda into the declaration, it's removed from our actual answer. Thanks to inference, the types of `a` and `b` are known, and the return type is known, so this compiles, and it's free bytes! ## Inferred `it` Parameter for Single-Param Lambdas If a lambda only takes one parameter and its type can be completely inferred, you don't even have to specify a parameter in the lambda body! The inferred parameter will be named `it`. Take the two examples: ``` val shuf:(List<T>)->List<T>= {l->l.shuffled()} // -2 val shuf:(List<T>)->List<T>= {it.shuffled()} ``` The compiler knows that this lambda takes one parameter and it knows what type it is, so if it isn't bound to a name in the lambda body, it is named `it` instead. You can use this to save 2 bytes in the degenerate case above, but if you have to refer to the parameter many times, it will be shorter to simply give it a name as in the former. ``` {it*it*it*it} {n->n*n*n*n} ``` ## Lambdas With Receiver Kotlin allows you to specify a *receiver* parameter for a lambda. Basically, you can rebind `this` inside. You indicate this lambda takes a receiver by writing the receiver type and a dot before the type signature: ``` Recv.(Param1, ...ParamN) -> Ret ``` Where this is useful is highly dependent on your approach. ``` val f:(Int,Int)->Int= {a,b->a+b} // -1 val f:Int.(Int)->Int= {this+it} ``` Of course, what's most useful is that `this` is the implicit receiver of member access. So if your submission consists mostly of a call chain on one of the parameters, or you refer to a field a couple times, this is extremely useful. ``` val shuf:(List<T>)->List<T>= {l->l.shuffled()} // -5 val shuf:List<T>.()->List<T>= {shuffled()} ``` It can be a bad call to use `this` instead of `it` e.g. * If there's only one parameter to the lambda and you don't need to call any methods on it * You need to [destructure the parameter](https://codegolf.stackexchange.com/a/188801/42096) * etc. ## Some Examples Examples can help you learn! * [pleTriwapt Sgpin (Triplet Swapping)](https://codegolf.stackexchange.com/a/201444/42096) * ["Multiply" two strings](https://codegolf.stackexchange.com/a/201037/42096) * [Count sum of all digits](https://codegolf.stackexchange.com/a/172953/42096) [Answer] # Extension Functions Extension functions can really help to reduce the names of built in methods, and chains of them, an example could be: `fun String.c() = this.split("").groupingBy{it}.eachCount()` but this only helps if: A) The call is long enough to cancel out the definition B) The call is repeated # Use of lambdas rather than methods Lambdas can return without using the return keyword, saving bytes # KotlinGolfer A project I have started [here](https://github.com/jrtapsell/kotlinGolfer) which takes pretty Kotlin code and gives posts with tests and TIO links automatically [Answer] # Defining Int's in params This will likely have some pretty specific use cases where it may be worth it, but in recent question I golfed I found I could save a few bytes by defining my variable as optional parameters rather than defining them in the function. Example from my answer to [this](https://codegolf.stackexchange.com/questions/188391/a-scene-of-jimmy-diversity) question: defining variable in the function: `fun String.j()={var b=count{'-'==it}/2;var a=count{'/'==it};listOf(count{'o'==it}-a,a-b,b)}` defining variables as params: `fun String.j(b:Int=count{'-'==it}/2,a:Int=count{'/'==it})=listOf(count{'o'==it}-a,a-b,b)` because `var a=` is the same length as `a:Int=` it will be the same number of bytes to define them (this is only the case for `Int`) however since I now only have 1 line in the function I can drop the `{}` and I also drop a single `;` (the other is replaced with a `,`) So if there are any functions that require defining an Int, and would be a 1 liner if you didn't define the int in the function - then doing it as a parameter will save a couple bytes [Answer] # You don't need to add a `;` after the imports if the last element is `*` for instance, you can do this ``` import java.util.*import kotlin.random.*import kotlin.random.Random ``` even this ``` import java.util.*import kotlin.random.*fun main(){} ``` [Answer] # The `to` infix function There is a standard infix function named `to` that creates `Pair`s of two values. It's commonly used with `mapOf()` for defining `Map`s but it's can potentially be a lot shorter than the `Pair()` constructor. ``` Pair(foo,bar) //constructor foo to bar //best case (foo)to(bar) ((foo)to(bar)) //worst case ``` [Answer] # Destructuring in lambda arguments Say you want to accept a `Pair<*,*>` in a lambda. Normally, handling this would be annoying. As an example, here's a lambda that takes a `Pair` and checks if the two values are equal: ``` {it.first==it.second} ``` This is long-winded and clumsy. Luckily, Kotlin allows you to destructure any destructable type (any type that implements `componentN()` methods, such as `Pair`, `Triple` etc.) as arguments to a lambda. So, we can rewrite this in the following way: ``` {(a,b)->a==b} ``` It looks similar to pattern matching a tuple in something like F#, and it is in many cases. But a wide variety of types in Kotlin support destructuring (`MatchResult` is a useful one.) You can take more arguments, though. Say your lambda had to take a `Pair` and an additional value. You'd simply write the lambda signature like this: ``` (a,b),c-> // pair first a,(b,c)-> // pair second ``` [Answer] # you can assign the functions (most important case is the main however) an unit type function for instance instead of doing `fun main(){println("hello world")}` you can do `fun main()=println("hello world")` which shaves off a mere byte [Answer] # The `repeat` function sometimes can shave off a few bytes in some cases the repeat function basically translates to this, for `repeat(100){something(it)}` it becomes `for(it in 0..100-1){something(it)}` the main problem of this is that the it starts from 0 as always and goes until times-1 which might not be ideal for some cases. I'd suggest, for any for loops, converting for loops to repeat loops and checking the byte count, like you might convert it then name the variable i instead of it etc. This will most certainly save you bytes if you use the variable "it" frequent enough. [Answer] # Get STDIN If you want to read a line, you can do `readln()` instead of `readLine()!!` ]
[Question] [ You and some buddies are going bowling. There are a total of *N* bowlers. However, there are only *N*-1 chairs to sit in. The solution is simple: whoever's turn it currently is doesn't get a chair. Then when their turn is over, they sit in the chair of the person that goes next. Lets take an example. Say You are named *A*, and your four friends are named *B*, *C*, *D*, and *E*. Every player moves in alphabetical order, so you get to go first. Since there are 5 players, there are only 4 seats. Your friends sit in the four seats in this order: > > CEBD > > > You go, and yay you get a strike! It's *B*'s turn next, so you sit in his chair. Now it looks like this: > > CEAD > > > *B* goes. Gutterball! Then he sits in *C*'s spot, and *C* goes next turn. > > BEAD > > > then *C* sits in *D*'s chair. > > BEAC > > > and *D* sits in *E*'s chair > > BDAC > > > and lastly, *E* sits in your chair. > > BDEC > > > You'll notice that now everybody's seat is (pseudo) shuffled. You must find out, after *X* turns, who will be sitting where? # Input Your program must take two inputs from the user, a string and a number. No prompts are needed. The string will be 1-51 alphabetic characters (B-Z and a-z) with no repeats. This represents the order your friends chose to sit. There will be no uppercase *A* because that is you, and you always go first. The number will be the total number of rounds (not games) that you and your friends play. This number will be positive and reasonably sized (less than 1000). # Output Your program must print out the order your friends are sitting in after X turns, and whose turn it is. So for example, if after X turns the order was BEDGCAHF and it was *Z*'s turn, your program must print exactly this: ``` BEDGCAHF It is Z's turn. ``` Here are a few sample input and outputs. ``` input: E, 4 E It is A's turn. input: E, 5 A It is E's turn. input: Bb, 2 AB It is b's turn. input: dgOPZXKDQYioHflFhpqzUsSaeILwckVNEtGTCJBvnruRyWMmjxb, 999 JNuvFDqjwEPVnMSlOWXgAZyGKordIRBtkamziphcUYbxfCsTQeH It is L's turn. ``` # Rules * Everybody goes in alphabetical order, with capital letters taking precedence over lower case. * This is code-golf, so standard loopholes apply, and submissions are scored [in bytes](https://mothereff.in/byte-counter). [Answer] # Pyth, ~~39~~ 38 bytes ``` L@+\ASzbuXGyhHyHQzpyQ"It is ""'s turn. ``` This is based around repeated applications of the find and replace operation, `X`. The first bit defines a lookup function, `y`, which finds the `b`th player in the player order. Then, we repeatedly perform substitutions to find the final seating order, and finally print out whose turn it is. Amusingly, the code to find the final seating order is shorter (18 bytes) than the code to print whose turn it is (21 bytes). The code takes the seating string on the first line of STDIN, and the number of turns on the second. [Demonstration.](https://pyth.herokuapp.com/?code=L%40%2B%5CASzbuXGyhHyHQzpyQ%22It+is+%22%22%27s+turn.&input=dgOPZXKDQYioHflFhpqzUsSaeILwckVNEtGTCJBvnruRyWMmjxb%0A999&debug=0) Explanation: ``` L@+\ASzbuXGyhHyHQzpyQ"It is ""'s turn. Implicit: z = input() Q = eval(input()) L def y(b): return +\ASz "A" + sorted(z) @ b ( )[b] u Qz reduce for H in range(len(Q)), G starts as z. XGyhHyH replace in G y(H+1) with y(H). pyQ"It is ""'s turn. Print out whose turn it is. ``` [Answer] # CJam, ~~49~~ ~~45~~ 43 bytes ``` l_'A+$ri{:L2<(erL(+}*1<" It is "\"'s turn." ``` I think this works. It just runs the algorithm as is. [Try it online.](http://cjam.aditsu.net/#code=l_'A%2B%24ri%7B%3AL2%3C%28erL%28%2B%7D*1%3C%22%0AIt%20is%20%22%5C%22's%20turn.%22&input=dgOPZXKDQYioHflFhpqzUsSaeILwckVNEtGTCJBvnruRyWMmjxb%0A999) ## Explanation ``` l Read line (initial seating order) _'A+$ Copy, add "A" and sort to give bowling order ri{ }* Do <number of turns> times... :L Save bowling order as L 2<( Get next and current bowlers er Replace next with current in seating L(+ Push bowling order again and update (rotate) 1< Get current bowler from start of bowling order " It is "\"'s turn." Output message ``` [Answer] # Python 3, 110 ``` s=input() S=sorted(s+'A')*999 exec("y,*S=S;s=s.replace(S[0],y);"*int(input())) print(s+"\nIt is %s's turn."%y) ``` An optimized version of [Sp3000's solution using `replace`](https://codegolf.stackexchange.com/a/49595/20260). The list `S` cycles though the letters present in order. We perform repeated replacements in the given string of each character of `S` by the previous one. [Answer] # Pyth, 37 bytes ``` uXGK<.<+\ASzH2)QzpeK"It is ""'s turn. ``` Online Demonstration: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=uXGK%3C.%3C%2B%5CASzH2)QzpeK%22It%20is%20%22%22%27s%20turn.&input=dgOPZXKDQYioHflFhpqzUsSaeILwckVNEtGTCJBvnruRyWMmjxb%0A999&debug=0) The algorithm is kinda based on @isaacg's solution. Like him I start with the initial seat-order and repeatedly use the replace-functionality of `X` to replace the next player with the current player. But unlike his implementation, which replaces the char of the next player by the current player in the seating order, I use it in a more broad way. I replace each char of the current player by the next player and each char of the next player by the current player. This is accomplished by passing both players as second arg and omit the third arg (`XG"ab")` instead of `XG"a""b"`). Since the current player is not part of the string (he is playing), the first replacement has no effect at all. But it allows me to generate both players at the same time, while @isaacg has to generate them individually. Another crazy new feature I use is the assignment operator. Until recently `=N1` got translated into `N = 1`, which was executed with Python. But nowadays it compiles to `assign('N',1)`. This function assigns `N` with 1 and returns the value (but doesn't print it). This allows saving intermediate results, which occur for instance in a reduce operation. Using this I was able to store the pair of players, which changed positions last, and print second player. ### Detailed Explanation ``` implicit: z = input string, Q = input number u Qz reduce for H in range(Q), start with G = z update G with: +\ASz "A" + sorted(z) .< H cyclic shifted by H < 2 get the first 2 elements (current + next player) K store the result in K XG ) replace next player by current player in G implicit print peK"It is ""'s turn. print "It is" + K[-1] (current player) + "'s turn." ``` [Answer] # [Clip 10](https://esolangs.org/wiki/Clip), ~~59~~ 56 bytes ``` [t{)k[qa)qglqtg(lqt}wx)nyN"It is "gnyt"'s turn.."`]s,x'A ``` ## Example ``` [t{)k[qa)qglqtg(lqt}wx)nyN"It is "gnyt"'s turn.."`]s,x'A dgOPZXKDQYioHflFhpqzUsSaeILwckVNEtGTCJBvnruRyWMmjxb 999 JNuvFDqjwEPVnMSlOWXgAZyGKordIRBtkamziphcUYbxfCsTQeH It is L's turn. ``` ## Explanation The first input is the list of players, assigned to the variable `x`. The second input is the number of turns, which the program obtains with `ny`. ``` [t ]s,x'A .-t is the sorted list of players including A-. { ` .-Print the following: -. k[q }wx)ny .-In each round (q is all the previous rounds)-. a)q .-Replace -. glqt .-the next player -. g(lqt .-with the previous player -. N .-Also print a newline -. "It is " "'s turn.." gnyt .-The ny'th player in t -. ``` Thanks to Sp3000 for the idea of using "replace". [Answer] # Python 3, 128 bytes ``` L=input() S=sorted(L)+["A"] i=0 exec("L=L.replace(S[i],S[i-1]);i=-~i%len(S);"*int(input())) print(L+"\nIt is %s's turn."%S[i-1]) ``` Takes two lines of input via STDIN — initial seating order then number of turns. This is basically the same search-and-replace idea as my [CJam solution](https://codegolf.stackexchange.com/a/49592/21487). The only tricky part is that we stick `A` at the *back* of the bowling order and make our index `i` the index of the *next* bowler, thus taking advantage of indexing by -1 and avoiding `IndexError`s. This is a few bytes shorter in Python 2, but I'm posting Python 3 for comparison with OP's solution. [Answer] # JavaScript (ES6) 116 116 bytes as program with I/O via popup window. 114 as a testable function. Run code snippet in Firefox to test. ``` // as a program with I/O for(t=[...s=(P=prompt)()].sort(),x=P(),p='A';x--;p=n)t.push(p),s=s.replace(n=t.shift(),p);P(`${s} It is ${p}' turn`) // as a function with 2 parameters, returning output as a 2 lines string f=(s,x)=>{for(t=[...s].sort(),p='A';x--;p=n)t.push(p),s=s.replace(n=t.shift(),p);return(`${s} It is ${p}' turn`)} // Test suite test=[ ['CEBD',5], ['E', 4],['E',5],['Bb', 2], ['dgOPZXKDQYioHflFhpqzUsSaeILwckVNEtGTCJBvnruRyWMmjxb', 999]]; Out=x=>OUT.innerHTML=OUT.innerHTML+x; test.forEach(([p,x])=>Out(p+' '+x+':\n'+f(p,x)+'\n')) ``` ``` Test cases from OP: <pre id=OUT></pre> ``` [Answer] ## PowerShell, 168 bytes ``` function x($s,$t){$p="A"+$s-split''|?{$_}|%{[int][char]$_}|sort|%{[char]$_};$l=$p.count;1..$t|%{$s=$s.replace($p[$_%$l],$p[($_-1)%$l])};$s;"It is $($p[$t%$l])'s turn."} ``` I've decided all my answers on this site will be in PowerShell. One day I'll have an answer that can compete... call the function like this: `x Bb 2` [Answer] This answer isn't going to win, but I'll throw it out there anyway. # Python 3, 167 bytes ``` s=input() n=int(input()) c='A' t=sorted(set(s+c)) F=len(t) f=list(s) for i in range(n): I=f.index(t[(i+1)%F]);c,f[I]=f[I],c print(''.join(f)+'\nIt is '+c+"'s turn.") ``` [Answer] # [Pip](https://github.com/dloscutoff/pip/), 54 bytes Not very competitive, but at least I get to show off Pip's mutable strings and the Swap command. Takes the seating order and number of rounds as command-line arguments (which get assigned to `a` and `b`, respectively). ``` u:'Ao:SN A^u.aLbSu(aa@?C(o++i))Pa"It is ".u."'s turn." ``` **Explanation:** ``` u:'A u = player who's currently up o:SN A^u.a ^u.a Append "A" to the seating order, split into list of characters o:SN A ASCII value of each char, sort the resulting list, assign to o LbSu(aa@?C(o++i)) Lb Repeat b times: Su Swap u with: (a ) The character of a at index: a@? Find in a: C(o++i) chr(ASCII value of next player from o) (Subscripts wrap around, as in CJam, so no need for mod) Pa Print the final lineup "It is ".u."'s turn." Current player (auto-printed) ``` It would have been 49 if I'd bothered to implement `SS` (sort as strings) at the same time I did `SN` (sort numeric)... Ah well, the perils of having a language in development. [Answer] # [Python 2](https://docs.python.org/2/), 105 bytes ``` a,s='A',input() exec"b=a<max(s)and min(e for e in s if e>a)or'A';s=s.replace(b,a);a=b;"*input() print s,b ``` [Try it online!](https://tio.run/##Ncw5EoIwFADQ3lNkaCAOY2HHIM647/tu9wNBopDEJCh4ebTxAO/J0iSCN6sKXB3YHdtlXObGwTVa0NAiAbQyKByNgUcoY9yhKBYKUcQ40ojFiLYBC/WDvg50Q1GZQkgd4gL2ISC@Vf9/UjFukHZJVdnRbbW@nmf9zYWJcZwOE/n8HPQO6GT@Dh/H5cCM9r1p98VVvi1Pi@xeELvmed4X "Python 2 – Try It Online") Golf of: ``` s=input() n=input() a='A' for i in range(n): try: b=min(e for e in s if e>a) except: b='A' s=s.replace(b,a) a=b print s print b ``` [Answer] # [Perl 5](https://www.perl.org/), 102 + 1 (-n) = 103 bytes ``` s/\d+//;$t=$&;@p=sort'A',split//;for$i(1..$t){s/$p[$i%@p]/$p[--$i%@p]/}say"$_ It is $p[$t%@p]'s turn." ``` [Try it online!](https://tio.run/##LYrHCsJAFADvfkWQ1SiaRA8eggTsvfeK2KKrMbvue3b8dVcD3oaZ4VvhJKQEY7aJGEaSoEWCyRS3gAlU02oUuEPxF2wmCA3FdZ1g@AUG4VNCAyk@90jT/vyG5cNPFr4yKhQU70HPq6DgRbi6X8rNrtmajKq59piyku0U9vz87EN3uS3XbuvjoJHHYi9byVxdcek8hvXT4b4yTfPDOFLmgtTqCT0Wj0nN/QI "Perl 5 – Try It Online") **Input** Seating order, followed by number of turns without spaces: ``` SEatingOrder### ``` ]
[Question] [ **The board game** In the board game "[Carcassonne](http://en.wikipedia.org/wiki/Carcassonne_%28board_game%29)" players place tiles by matching their edges and earn the highest scores through creating large contiguous areas of terrain. The following are (roughly) the types and quantities of tiles included in the game: `#01` `x4` ![enter image description here](https://i.stack.imgur.com/5g1pG.png) `#02` `x5` ![enter image description here](https://i.stack.imgur.com/0VqZc.png) `#03` `x8` ![enter image description here](https://i.stack.imgur.com/He40t.png) `#04` `x2` ![enter image description here](https://i.stack.imgur.com/KvYtb.png) `#05` `x9` ![enter image description here](https://i.stack.imgur.com/H2eVu.png) `#06` `x4` ![enter image description here](https://i.stack.imgur.com/BtIIT.png) `#07` `x1` ![enter image description here](https://i.stack.imgur.com/mnKl2.png) `#08` `x3` ![enter image description here](https://i.stack.imgur.com/Lgq4J.png) `#09` `x3` ![enter image description here](https://i.stack.imgur.com/fYaY1.png) `#10` `x3` ![enter image description here](https://i.stack.imgur.com/uoOPz.png) `#11` `x4` ![enter image description here](https://i.stack.imgur.com/TNiUD.png) `#12` `x5` ![enter image description here](https://i.stack.imgur.com/nyHsX.png) `#13` `x3` ![enter image description here](https://i.stack.imgur.com/4vjkv.png) `#14` `x3` ![enter image description here](https://i.stack.imgur.com/d2Epe.png) `#15` `x2` ![enter image description here](https://i.stack.imgur.com/ll8EF.png) `#16` `x5` ![enter image description here](https://i.stack.imgur.com/wJAXf.png) `#17` `x5` ![enter image description here](https://i.stack.imgur.com/C20Iq.png) `#18` `x2` ![enter image description here](https://i.stack.imgur.com/BbUIq.png) `#19` `x3` ![enter image description here](https://i.stack.imgur.com/Z5j1K.png) `#20` `x1` ![enter image description here](https://i.stack.imgur.com/RaMQN.png) `#21` `x5` ![enter image description here](https://i.stack.imgur.com/qxvEz.png) `#22` `x2` ![enter image description here](https://i.stack.imgur.com/nczz9.png) `#23` `x1` ![enter image description here](https://i.stack.imgur.com/bDTp9.png) `#24` `x1` ![enter image description here](https://i.stack.imgur.com/gp6tX.png) `#25` `x1` ![enter image description here](https://i.stack.imgur.com/M0kf6.png) **The Task** You must place a tile by matching edges, while trying to maintain the largest possible contiguous areas of terrain. **Placement** * Tiles can only be placed in one of the (up to 4) blank spaces adjacent to any existing tile (or tiles) in the play area. * Tiles can be rotated 90, 180 or 270 degrees. **Edge-matching** * Edges of a placed tile must match the touching edges of the (up to 4) neighbouring tiles, i.e. touching pixels are the same colour. **Contiguous terrain** * "Closing an area of terrain" refers to placing a tile such that any contiguous area of colour could not then be continued with further tile placements. * If an alternative placement is possible, it must be chosen over any tile placement that would close an area of terrain. * If you have to choose between a number of closing placements, choose any. If you have to choose between a number of non-closing placements, choose any. * Disregard #ff00ff (the corner pixels) when calculating contiguous areas. Also disregard buildings, i.e. areas of colour already fully enclosed within a tile. **Input** * Input is two images: 1. The play area. + The initial play area consists of tile `#11` (a single tile). + The augmented play area created as output must also be supported as input. 2. The tile to be placed. + All of the example tiles must be supported as input. * Determine matching edges/contiguous terrain using this image data alone. No hardcoding. **Output** * Output is an image showing the resultant play area after placing the tile. * The image must be compatible with your own program, i.e. it can be used as play area input. * If it's impossible to place a tile, return an error. **You can assume that** * Tiles are always 55 px by 55 px * Tiles will only ever feature the colours currently used in the example tiles. **Notes** * Your answer must feature example output after at least 2 passes (more is encouraged). * This is a partial and inaccurate rendering of the original board game, you don't need to apply any of the rules or tactics not mentioned here. **Score** * Your score is your submission's byte count. * Image data isn't included in your score. * Lowest score wins. --- ***Playing a full game*** You may wish to write a script that uses your submissison to play a full game, which might consist of: * Placing a tile chosen pseudorandomly from the full set of 85. * Returning the tile to the set if it can't be placed. * Repeating until every tile has been placed - or until two tiles in a row can't be placed. It won't be included in your byte count, or improve your score, but I'll likely offer a bounty to this kind of answer. [Answer] # Common Lisp, 2650 2221 1992 1186 1111 bytes *Update:* "Easy" golfing now done, further gains will require bigger changes. *Update 2:* With the competition getting fiercer, the new version no longer favors positions inside the current playing field rectangle (that would be 57 bytes extra). This option, as well as a simple speed optimization, is by enabled by default in the downloadable version with the simulator, but not in the official answer below. *Update 3:* Minor interface changes for major byte count gains. I created a simple Web UI as well. The full package (a single LISP file and the tile images) can be [downloaded here](http://www.aprikoodi.fi/carcassonne.tar.bz2). To try it, install `hunchentoot`, `zpng` and `png-read` with quiclisp, load in `carcassonne.lisp`, and connect to `localhost:8080`. The code has been tested on CCL/Windows and SBCL/Linux. The above mentioned libraries are only needed for the UI/simulator part; the solution itself is plain ANSI Common Lisp. ``` (defun c(f p &aux b a s z(c 55)) (macrolet((d(v l &body b)`(dotimes(,v,l),@b)) (b(b c)`(d i c(d j c(setf,b,c)))) (r(&rest p)`(aref,@p)) (n(u v i j)`(and(setf l(*(f,u,v)l)) (find(r f(+,u,i)(+,v,j))`(0,(r f,u,v)))))) (labels((p(p w)(d y(ceiling w 2)(d x(- w y y)(rotatef(r p y #6=(+ x y))(r p #6##7=(- w y))(r p #7##8=(- w x y))(r p #8#y))))) (a(y x)(or(if(= 0(r f y x))1 #4=(and(= 1(incf(r s y x)))(=(r f y x)z)(push`(,y,x)a)0))0)) (f(y x)(setf z(r f y x))(if #4#(loop for((y x))= a while(pop a)maximize(+(a(1- y)x)(a y(1- x))(a(1+ y)x)(a y(1+ x))))1))) (d i 8(when(d x #1=(array-dimension f 0)(or(= 0(r f(- #1#52 i)x))(return t)))(setf f(adjust-array f`(#2=,(+ #1#c)#2#))))(p f(1- #1#))) (d i 4(d u #9=(/ #1#c)(d v #9# (let((y(* u c))(x(* v c))(l 9e9)) (when(= 0(r f y x)) (b #10=(r f(+ y i)(+ x j))(r p i j)) (setf s(make-array`(,#1#,#1#))a()) (ignore-errors(if(> #11=(*(loop for d from 1 to 53 sum(+(n y #3=(+ x d)-1 0)(n #5=(+ y d)(+ 54 x)0 1)(n(+ 54 y)#3#1 0)(n #5#x 0 -1))) (1+ l)) (or(car b)0)) (setf b`(,#11#,i,y,x)))) (b #10#0))))) (p p 54)) (when b(d j(cadr b)(p p 54))(b(r f(+(third b)i)(+(nth 3 b)j))(r p i j))) `(,f,b)))) ``` All line feeds and line-starting spacing are for cosmetics only, to ensure legibility, and not counted into the total sum. You should call the function `c` with two arguments: The current play field, and the tile to place. Both should be 2D arrays; the tile 55x55 and the field a multiple of that. Additionally, the field array must be adjustable. The function returns a two-element list with the new field as its first argument. The second element is `NIL` if the tile cannot be placed, or otherwise a list containing the top-left coordinates and rotation of the latest tile on that array and the score for that tile. This information can be used for visualization purposes. Note that in further calls, you must use the new field returned by `c` even if the second list element is `NIL` (the original array may have been `adjust-array`ed and thus invalidated). The code is now a bit on the slow side, byte count optimization resulting in redundant calculations. The example below completed in about three minutes on my system. Example run for all 85 tiles: ![enter image description here](https://i.stack.imgur.com/6JFyn.png) Web UI screenshot: ![enter image description here](https://i.stack.imgur.com/ojDlN.png) [Answer] # DarkBASIC Pro: ~~2078~~ ~~1932~~ 1744 bytes UPDATE: Just more golfing effort UPDATE: Now fully meets the spec, including preferring non-closing choices. I chose DarkBASIC because while it's rather verbose, it provides an extremely straightforward and simple command set for manipulating images. I uploaded an EXE for people who don't have the DarkBASIC compiler ([Windows](http://www.brianmacintosh.com/code/carcassonne/carc04.zip)). ![Sample output](https://i.stack.imgur.com/0ZhyR.png) ``` #constant m memblock #constant f function #constant k endfunction #constant z exitfunction #constant i image #constant e endif #constant t then #constant o or #constant s paste image #constant n next #constant r for set i colorkey 0,20,0:load i "map.png",1:f$="next.png" if file exist(f$)=0 t f$=str$(rnd(24)+1)+".png" load i f$,2:make m from i 1,1:make m from i 2,2 global ts,h,j,u,v,td ts=i width(2):h=i width(1):j=i height(1):u=h/ts:v=j/ts:td=ts*2 create bitmap 2,h+td+1,j+td+1:r b=1 to 4:r xx=0 to u+1:r yy=0 to v+1:x=xx*ts-1:y=yy*ts-1 cls 5120:s 1,ts,ts,1:if (a(x+1,y) o a(x,y+1) o a(x-ts,y) o a(x,y-ts)) and a(x,y)=0 x1=ts*xx:y1=ts*yy:make i from m 2,2:s 2,x1,y1,1 cl=0:r fd=0 to 1:r x2=1 to ts-2:r yt=0 to 1:y2=yt*ts-yt:y3=yt*ts+yt-1 aa=x2:ab=x2:ba=y2:bb=y3:t2=y1:r t3=0 to 1:p=point(x1+aa,y1+ba):q=point(x1+ab,y1+bb) if p<>q and rgbg(q)<>20 and t2+b>0 t goto fa if fd and p<>0xFF0000 if l(x1+aa,y1+ba,p)=0 t cl=1 e aa=y2:ba=x2:bb=x2:ab=y3:t2=x1:n t3:n yt:n x2:n fd:dn=1:c=xx-1:g=yy-1:make i from m 3,2:if cl=0 t goto dm e fa: n y:n x d=ts/2:r x=0 to d:r y=0 to d-1:vx=ts-1-x:vy=ts-1-y:t1=rd(x,y):t2=rd(vy,x):wr(vy,x,t1):t1=rd(vx,vy):wr(vx,vy,t2):t2=rd(y,vx):wr(y,vx,t1):wr(x,y,t2):n x:n y:n b dm: if dn=0 t report error "Not placed" p=c<0:q=g<0:t1=h+ts*(p o c>=u):t2=j+ts*(q o g>=v):cls 5120:p=ts*p:q=ts*q:s 1,p,q,1:s 3,c*ts+p,g*ts+q,1:get i 1,0,0,t1,t2,1:save i "map.png",1 end f l(x,y,w) if x<0 o y<0 o x>=h+td o y>=j+td t z 1 p=point(x,y) if rgbg(p)=20 t z 1 if p<>w t z 0 dot x,y,0xFF0000:rt=l(x+1,y,p) o l(x-1,y,p) o l(x,y+1,p) o l(x,y-1,p) k rt f rd(x,y) w=m dword(2,0):b=m dword(2,12+(y*w+x)*4) k b f wr(x,y,d) w=m dword(2,0):write m dword 2,12+(y*w+x)*4,d k f a(x,y) if x<0 o y<0 o x>=h o y>=j t z 0 b=m byte(1,15+(y*h+x)*4) k b ``` [Answer] # Perl 5 with PerlMagick: 875 789 763 I did not count the line starting with `sub w`, which is used to sort positions on the distance to the center to prefer compact solutions (now working properly). In this version closing is avoided like requested but I find the opposite more interesting and true to the game. To achieve that change the line `$s=$t if!grep...` to `$s=$t if grep...`. ``` use Image::Magick; sub p{/x/;@o=$r->GetPixel(y=>$'+pop,x,$`+pop);"@o"} sub o{$w=&p;"0 0 0"eq$w?3:&p eq$w} sub f{$r->FloodfillPaint(y=>$J+$',x,$I+$&,channel,All,fill,@_)} ($i=Image::Magick->new)->Read(@ARGV);$r=$b=$i->[0]; $h=$b->Get(rows)+112;$:=$b->Get(width)+112; $b->Extent(geometry,"$:x$h-56-56",background,none); @v=grep p()eq"0 0 0",map{map-54+55*$_.x.($'*55-54),//..$:/55}1..$h/55; sub w{$_=pop;/x/;abs($:-2*$`)+abs($h-2*$')}@v=sort{w($b)<=>w($a)}@v; map{map{/x/;$I=$`;$J=$';$r=$b->Clone(); ($t=$r)->Composite(image,$i->[1],x,$I,y=>$J); if((o(27,0,27,-1)&o(0,27,-1,27)&o(27,54,27,55)&o(54,27,55,27))==1){ $s=$t if!grep{/../;$r=$t->Clone();f(none);f(red); !grep{p()eq"1 0 0"}@v} map{/..$/;($_,$&.$`)}map{($_.-1,$_.55)}10,27,45; $o=$r=$t;}$i->[1]->Rotate(degrees,90)}($_)x4}@v; $s||=$o or exit 1;$s->Trim();$s->Write("car.png") ``` Usage: `perl car.pl board.png tile.png`. Result stored in `car.png`. Exit status is 1 if the tile could not be placed. Script to run a complete game. It assumes the code above is in the file `car.pl` and the tiles are stored in `tiles` directory named `01.png` to `25.png`. ``` use List::Util shuffle;$x='00'; @t=shuffle map{($x++)x$_}split'',a4582941333353325523152111; `cp tiles/11.png car.png`; $i++,`perl car.pl car.png tiles/$_.png`,print"placed $i\n"for@t ``` This runs quite slowly now. 8-12 minutes on my machine. With closing preferred: ![Prefer closing example](https://i.stack.imgur.com/7YliN.png) [With closing avoided](https://i.stack.imgur.com/xhMpt.png) (note nothing is closed). ]
[Question] [ # Challenge: Write a program that produces the following output: ``` . E .. I ... S .... H ...- V ..- U ..-. F ..-- .- A .-. R .-.. L .-.- .-- W .--. P .--- J - T -. N -.. D -... B -..- X -.- K -.-. C -.-- Y -- M --. G --.. Z --.- Q --- O ---. ---- ``` This is a formatted table of the Morse codes of the letters from A to Z. Each column is separated by three spaces. There are four missing slots, which are used by international character sets. Your program must write a space there. The output must consist of ASCII spaces, dots, dashes, uppercase letters and newlines (either LF or CRLF) only. Your program accepts no input. The following is a sample Python program that produces the desired output: ``` b = "." out = [] last = 0 ch = "EISHVUF ARL WPJTNDBXKCYMGZQO " cx = 0 while b: if last >= len(b): print(" ".join(out)) out = [" ", " ", " ", " "][0:len(b) - 1] out.append(b + " " + ch[cx]) cx += 1 last = len(b) if len(b) < 4: b += "." elif b[-1] == ".": b = b[0:-1] + "-" else: i = len(b) - 1 while b[i] == "-": i -= 1 if i < 0: break if i < 0: break b = b[0:i] + "-" print(" ".join(out)) ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # Python 3.6, ~~201~~ ~~197~~ ~~193~~ 187 bytes ``` for i in range(16):print(' '.join(i%k and' '*(2+j)or f'{i//k:0{j}b}'.replace(*'0.').replace(*'1-')+' '+'ETIANMSURWDKGOHVF L PJBXCYZQ '[2**j-2+i//k]for j,k in zip((1,2,3,4),(8,4,2,1)))) ``` Uses some formatting, unpacking and [A000918](https://oeis.org/A000918) magic. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 85 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ØQj⁶“_ȦeƤbṅỌU@⁼Cq’œ?;⁶$⁺ṁ®L€€¤ 4R2ṗ©ị⁾.-;€€⁶ż"¢;€€⁶$⁺W€€j"731Dẋ@⁶¤ZµKFṚ;⁶ẋ³¤ḣ29ṫ3Ṛµ€Y ``` A full program printing the cheat sheet. **[Try it online!](https://tio.run/nexus/jelly#@394RmDWo8ZtjxrmxJ9YlnpsSdLDna0Pd/eEOjxq3ONc@Khh5tHJ9tZABSqPGnc93Nl4aJ3Po6Y1QHRoCZdJkNHDndMPrXy4u/tR4z49XWuIDFDx0T1KhxYhuCC94RBelpK5saHLw13dQPO3HVoSdWirt9vDnbNANgAFD20@tOThjsVGlg93rjYGCh/aCtQS@f8/AA)** ### How? *Note:* I do think there may be a way to trim this down by forming a list which formats correctly by use of the grid atom, `G`, but I can't quite work out how. ``` ØQj⁶“_ȦeƤbṅỌU@⁼Cq’œ?;⁶$⁺ṁ®L€€¤ - Link 1: get "letters" lists: no arguments ØQ - Qwerty yield = ["QWERTYUIOP","ASDFGHJKL","ZXCVBNM"] j⁶ - join with spaces = "QWERTYUIOP ASDFGHJKL ZXCVBNM" “_ȦeƤbṅỌU@⁼Cq’ - base 250 number = 23070726812742121430711954614 œ? - lexicographical permutation at index = "ETIANMSURWDKGOHVF L PJBXCYZQ" ⁺ - do this twice: $ - last two links as a monad ;⁶ - concatenate a space = "ETIANMSURWDKGOHVF L PJBXCYZQ " ¤ - nilad followed by link(s) as a nilad: ® - recall from registry (4R2ṗ from the Main link) L€€ - length for €ach for €ach = [[1,1],[2,2,2,2],[3,3,3,3,3,3,3,3],[4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4]] ṁ - mould like = ["ET","IANM","SURWDKGO","HVF L PJBXCYZQ "] 4R2ṗ©ị⁾.-;€€⁶ż"¢;€€⁶$⁺W€€j"731Dẋ@⁶¤ZµKFṚ;⁶ẋ³¤ḣ29ṫ3Ṛµ€Y - Main link: no arguments 4R - range(4) = [1,2,3,4] 2ṗ - Cartesian power with 2 = [[[1],[2]],[[1,1],[1,2],[2,1],[2,2]],...,[...,[2,2,2,2]]] © - copy to register and yield ⁾.- - literal ['.','-'] ị - index into (makes all the codes, in four lists by length like reading the output top-bottom, left-right) ;€€⁶ - concatenate a space to each code ¢ - call last link (1) as a nilad (get the letters reordered as required) ż" - zip left and right with zip dyad ⁺ - do this twice: $ - last two links as a monad: ;€€⁶ - concatenate a space to each code, letter pair W€€ - wrap each code, letter pair in a list ¤ - nilad follwed by link(s) as a nilad: 731 - literal 731 D - to decimal list = [7,3,1] ẋ@⁶ - repeat a space = [" "," "," "] j" - zip with dyad join Z - transpose µ µ€ - for each: K - join with spaces F - flatten Ṛ - reverse ¤ - nilad followed by link(s) as a nilad: ⁶ẋ³ - space repeated 100 times ; - concatenate ḣ29 - head to 29 (make all "lines" the same length) ṫ3 - tail from 3 (trim off two spaces from each line) Ṛ - reverse Y - join with newlines - implicit print ``` [Answer] # [Retina](https://github.com/m-ender/retina), 125 bytes ``` ^ . EISHVUF_ARL_WPJ¶- TNDBXKCYMGZQO__ +m`^((.*?)([-.]+) )(\w)((\w)+?)(((?<-6>)\w)+)$ $2$3 $4 $3. $5¶$.1$* $3- $7 T`\_`p ``` [Try it online!](https://tio.run/nexus/retina#@x/Hpafg6hnsERbqFu8Y5BMfHuB1aJuuQoifi1OEt3Okr3tUoH98PJd2bkKchoaelr2mRrSuXqy2poKmRky5pgaI0AYKamjY2@ia2WmCuJoqXCpGKsYKKiYKCgoqxnoKKqaHtqnoGapoKSiARXQVVMy5QhJi4hMK/v8HAA "Retina – TIO Nexus") Should be 121 bytes but I was too lazy to deal with the whitespace at the start and end. Explanation: ``` [blank line] . EISHVUF_ARL_WPJ¶- TNDBXKCYMGZQO__ ``` The letters whose code begins with `.` and `-` respectively are preloaded. (It is theoretically possible to avoid preloading the `.-` but it saves bytes this way.) `_`s are used instead of spaces as they are considered to be letters which makes them easier to match below. ``` +m`^((.*?)([-.]+) )(\w)((\w)+?)(((?<-6>)\w)+)$ $2$3 $4 $3. $5¶$.1$* $3- $7 ``` Here we split each line up into five pieces: * The letters for prefixes, if any * The current Morse code * The current letter * The first half of the remaining letters (their next character is `.`) * The second half of the remaining letters (their next character is `-`) The pieces are then reassembled onto two lines: * The letters for prefixes, the current Morse code, the current letter, the Morse code with a `.` suffix, the first half of the remaining letters * Spaces replacing the first three pieces, the Morse code with a `-` suffix, the second half of the remaining letters The new lines follow the same format as the existing line, just with an extra Morse prefix and half as many letters remaining to process. This is then repeated until each line has only one letter. ``` _ [single space] ``` The `_`s are then changed back into spaces. [Answer] ## JavaScript (ES6), ~~154~~ ~~147~~ 145 bytes ``` f=(n=r='',d=i=k=0)=>(r+=n&&' '.repeat([d++&&3,21,13,6][i-(i=d-k)])+n+' '+'EISHVUF ARL WPJTNDBXKCYMGZQO '[k++],d<4)?f(n+'.',d)&&f(n+'-',d):r+=` ` o.innerHTML = f() ``` ``` <pre id=o> ``` [Answer] # PHP, 208 Bytes ``` <?=gzinflate(base64_decode("dZDJEQMhDAT/RNEJaHLwfd+38w/EWrRlu6gVnwZpGhWIGSCxqhCXoFgWhpa3jHtpasYtKOaZZwZ9z/OjCnEOim3imX7et2Y8guKYeR5aF+PqB4/tK8Q0KMbDnnWPeZamZmyCYpJ5Pu/V93y7qxCLoHgnXnf5qZnn/iGo9u1/Gf+XDw==")); ``` [Try it online!](https://tio.run/nexus/php#BcHdboIwGADQd/FKw0WniEI2YraCMNCBaPjpjalSCkY@QEsqvjw7Z/zamPxdQXGngk0v9MlWy3POrk3OppOcWJ592JfW9wlFf7ZH3Z0sckXVJbKTR3TvVzwGSVqnTH6dI351JU6bLU/Klqo3V7T0mQk/oIRIYrxRcMNgB1WtVnW6ZmKR6bz3MxZpdKuE3c8SCV8/fPj7iwWQhIzQmtQDzlpPC3sUG@qw7l5417gcUii0jgCgymmMfo6cQkktaZqT2exzHP8B "PHP – TIO Nexus") # PHP, 229 Bytes ``` <?=strtr("3E0.3I053S0.53H12 2.54V1254U05-3F12 25-4 1.4A0.-3R0.-.3L12 2.-.4 12.-4W0.63P12 2.64J 4T0-3N0-.3D0-53B12 2-54X12-.4K0-.-3C12 2-.-4Y1-4M063G06.3Z12 26.4Q1264O0-63 12 2-64 ",[$a=" "," $a$a","$a $a",". ","- ","..","--"]); ``` [Try it online!](https://tio.run/nexus/php#HYvJDgIxDEPv8xVVNQeQSJQ2aS@AEPu@7yAO8wsw/z@kvdjWs930Bv1f/a2/LctTQl5S4DNh4IXzxmOQm/NBrhSAZ4kEEONQhoTAJxXkTR4CKleTO2HkQ2ZRVoVcCHhHupsQBB6lAoI8nNfHWjnwODO9Ph3IliLPKSK/Eo0oR@ej7Akim7yLYmznXVZ9a4wmW5RVWamXlcmOCUISxJTAftrdpvkD "PHP – TIO Nexus") [Answer] # Perl 5, ~~158~~ 156 bytes ``` map{$a=sprintf'%04b',$_;map{$a=~/.{$_}/;print(-$'?' 'x$_:$&=~y/01/.-/r,' ',(' EISHVUF ARL WPJTNDBXKCYMGZQO '=~/./g)[!-$'&&++$i],$_-4?' ':"\n")}1..4}0..15 ``` [Answer] # PHP, ~~184 183~~ 181 bytes ``` for(;$y<16;$y++,print str_pad(ltrim("$r "),28," ",0))for($r="",$c="03231323"[$y&7];$c++<4;)$r.=strtr(sprintf(" %0${c}b ",$y>>4-$c),10,"-.")."EISHVUF ARL WPJTNDBXKCYMGZQO "[$i++]; ``` Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/33329cc677492e58641e53cc81c2065f0603151c). **breakdown** ``` for(;$y<16;$y++, # loop through rows print str_pad(ltrim("$r\n"),28," ",0) # 4. pad to 28 chars and print ) for($r="", # 1. result=empty $c="03231323"[$y&7]; # 2. $c=bits in 1st code -1 $c++<4;) # 3. loop through columns $r.=strtr(sprintf(" %0${c}b ",$y>>4-$c),10,"-.") # append morse code ."EISHVUF ARL WPJTNDBXKCYMGZQO "[$i++]; # append letter ``` --- **-7 bytes with leading spaces**: Replace `ltrim("$r\n")` with `"$r\n"` and `28` with `31`. **171 (= -10) bytes with trailing spaces**: ``` for(;$y<16;$y++)for(print str_pad(" ",[0,7,14,22][$c="03231323"[$y&7]]);$c++<4;)echo strtr(sprintf("%0${c}b %s ",$y>>4-$c,"EISHVUF ARL WPJTNDBXKCYMGZQO"[$i++]),10,"-."); ``` **breakdown** [try it online](http://sandbox.onlinephpfunctions.com/code/a9a000ab526987945b6e1b8fac6f78c00d6f3659) ``` for(;$y<16;$y++) # loop through rows for( print str_pad("\n",[0,7,14,22][ # 2. print left padding $c="03231323"[$y&7] # 1. $c=bits in 1st code -1 ]); $c++<4;) # 3. loop through columns echo # print ... strtr(sprintf("%0${c}b %s ", # 3. delimiting spaces $y>>4-$c, # 1. morse code "EISHVUF ARL WPJTNDBXKCYMGZQO"[$i++] # 2. letter ),10,"-."); ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 92 bytes Needs `⎕IO←0` which is default on many systems. ``` 0 3↓¯1⌽⍕{' ',(16⍴1↑⍨16÷≢⍵)⍀'.-'[⍉2⊥⍣¯1⍳≢⍵],' ',⍪⍵}¨'ET' 'IANM' 'SURWDKGO' 'HVF L PJBXCYZQ ' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862n3zi4pT/xsoGD9qm3xoveGjnr2PeqdWqyuo62gYmj3q3WL4qG3io94VhmaHtz/qXPSod6vmo94GdT1d9ehHvZ1Gj7qWPupdDNLXuxkiHasD0vuodxWQXXtohbprCJDv6ejnC6SCQ4PCXbzd/YFMjzA3BR@FAC@nCOfIqEAFBfX/QLf8BzsGAA "APL (Dyalog Unicode) – Try It Online") `{`…`}¨'`…`'` apply the following anonymous function to each of the strings:  `⍪⍵` make the argument into a column  `' ',` prepend a space (on each row)  `'.-'[`…`],` prepend the string after it has been indexed with:   `≢⍵` the length of the argument   `⍳` the indices of that (0, 1, 2, …, *length*-1)   `2⊥⍣¯1` anti-base-2 (uses as many bits as needed)   `⍉` transpose (from one representation in each column to one in each row)  `(`…`)⍀` expand by (insert blank rows as indicated by zeros in):   `≢⍵` the length of the argument   `16÷` divide sixteen by that   `1↑⍨` (over)take from one (makes a list of a one followed by 1-*n* zeros)   `16⍴` recycle that pattern until it has sixteen elements  `' ',` prepend a space `⍕` format (the list of tables into a single table, padding each with a space on each side) `¯1⌽` rotate one step right (thus moving the trailing space to the front) `0 3↓` drop zero rows and three columns (thus removing the three leading spaces) [Answer] # [SOGL](https://github.com/dzaima/SOGL), ~~106~~ ~~105~~ 102 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ¹θΞk“r²{r³³a:IA2─l4;- 0*;+Ζ0.ŗΖ1-ŗø4∫BƧ| ⁵±+⁷b<?⁄@*}+;j;@3*+}±kkk≥x}¹±č┐"7ŗ◄∑f^│N≥Χ±⅜g,ιƨΛ.⌡׀¹*ΛβΧκ‘čŗ ``` ### If prepending spaces are allowed, ~~102~~ 99 bytes ``` ¹θΞk“r²{r³³a:IA2─l4;- 0*;+Ζ0.ŗΖ1-ŗø4∫BƧ| ⁵±+⁷b<?⁄@*}+;j;@3*+}±≥x}¹±č┐"7ŗ◄∑f^│N≥Χ±⅜g,ιƨΛ.⌡׀¹*ΛβΧκ‘čŗ ``` ### 141 bytes, compression ``` Πa≤χ≥∫RωθΩ≡⅛QΨ═Λ9⁶Ul¹&╔²‘č"‼¼⁸Ƨ,9█ω½└╗«ωΤC¡ιΝ/RL⌡⁄1↑οπ∞b∑#⁵ø⁶‘č"⁵ ?∙«Σf⁾ƨ╤P1φ‛╤Β«╚Δ≡ΟNa1\÷╬5ŗķ§⁷D◄tFhžZ@š⁾¡M<╔↓u┌⁽7¡?v¦#DΘø⌡ ⁹x≡ō¦;⁵W-S¬⁴‘' n ``` just wanted to see how well could SOGL do with just compression (well it's got more than just compression, but it's 97% compressed strings) [Answer] ## JavaScript (205 bytes) ``` for(A='EISHVUF ARL WPJTNDBXKCYMGZQO ',q=0,i=15;30>i++;){for(x=i.toString(2).replace(/(.)/g,a=>1>a?'.':'-'),o='',j=4;j--;)o+=(i%2**j?A.slice(-6+j):x.slice(1,5-j)+' '+A.charAt(q++))+' ';console.log(o)} ``` ``` for(A='EISHVUF ARL WPJTNDBXKCYMGZQO ',q=0,i=15;30>i++;){for(x=i.toString(2).replace(/(.)/g,a=>1>a?'.':'-'),o='',j=4;j--;)o+=(i%2**j?A.slice(-6+j):x.slice(1,5-j)+' '+A.charAt(q++))+' ';console.log(o)} ``` [Answer] # Ruby, ~~144 143~~ 141 bytes ``` k=0 16.times{|i|4.times{|j|$><<("%0#{j+1}b 9 "%(i>>3-j)).tr('109',(i+8&-i-8)>>3-j>0?'-.'+' OQZGMYCKXBDNTJPW LRA FUVHSIE'[k-=1]:" ")} puts} ``` **Ungolfed** ``` k=0 #setup a counter for the letters 16.times{|i| #16 rows 4.times{|j| #4 columns $><<("%0#{j+1}b 9 "%(i>>3-j)). #send to stdout a binary number of j+1 digits, representing i>>3-j, followed by a 9, substituted as follows. tr('109',(i+8&-i-8)>>3-j>0? #(i&-i) clears all but the least significant 1's bit of i. the 8's ensure a positive result even if i=0. '-.'+' OQZGMYCKXBDNTJPW LRA FUVHSIE'[k-=1]: #if the expression righshifted appropriately is positive, substitute 1and0 for -and. Substitute 9 for a letter and update counter. " ")} #else substiture 1,0 and 9 for spaces. puts} #carriage return after each row. ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 106 bytes ``` DhNR.n.e+]++.[\.sllN::.Bk\0\.\1\-\ b*]*\ +2sllNt/16lNNjmj*3\ d.t[h"ET"h"IANM"h"SURWDKGO"h"HVF L PJBXCYZQ ``` [Test it online!](https://pyth.herokuapp.com/?code=DhNR.n.e%2B%5D%2B%2B.%5B%5C.sllN%3A%3A.Bk%5C0%5C.%5C1%5C-%5C%20b%2A%5D%2A%5C%20%2B2sllNt%2F16lNNjmj%2A3%5C%20d.t%5Bh%22ET%22h%22IANM%22h%22SURWDKGO%22h%22HVF%20L%20PJBXCYZQ%20%20&debug=0) **Explanation** In a few words, what I do here is to generate the table column by column and then transpose the table before printing it. We notice that in a column, the morse codes for the letters can be represented as binary strings (replace `.` by `0` and `-` by `1`) when counting from zero to the index of the last letter in the column. The algorithm relies on a function from which I give an example run below (for the second column): ``` 1. Takes "IANM" as input 2. Generates the binary representations of zero up to len("IANM"): ["0", "1", "10", "11"] 3. Replace with dots and hyphens: [".", "-", "-.", "--"] 4. Pad with dots up to floor(log2(len("IANM"))): ["..", ".-", "-.", "--"] 5. Add the corresponding letters: [".. I", ".- A", "-. N", "-- M"] 6. After each element, insert a list of 16 / len("IANM") - 1 (= 3) strings containing only spaces of length floor(log2(len("IANM"))) + 2 (= 4): [".. I", [" ", " ", " "], ".- A", [" ", " ", " "], "-. N", [" ", " ", " "], "-- M", [" ", " ", " "]] 7. Flatten that list: [".. I", " ", " ", " ", ".- A", " ", " ", " ", "-. N", " ", " ", " ", "-- M", " ", " ", " "] 8. That's it, we have our second column! ``` **Code explanation** I cut the code in two. The first part is the function described above, the second part is how I use the function: ``` DhNR.n.e+]++.[\.sllN::.Bk\0\.\1\-\ b*]*\ +2sllNt/16lNN DhNR # Define a function h taking N returning the rest of the code. N will be a string .e N # For each character b in N, let k be its index .Bk # Convert k to binary : \0\. # Replace zeros with dots (0 -> .) : \1\- # Replace ones with hyphens (1 -> -) .[\.sllN # Pad to the left with dots up to floor(log2(len(N))) which is the num of bits required to represent len(N) in binary ++ \ b # Append a space and b ] # Make a list containing only this string. At this point we have something like [". E"] or [".. I"] or ... + *]*\ +2sllNt/16lN # (1) Append as many strings of spaces as there are newlines separating each element vertically in the table .n # At this point the for each is ended. Flatten the resulting list and return it ``` (1): In the morse table, in the first column, there is seven lines after each line containing a letter ("E" and "T"). In the second column, it is three lines. Then one (third column), then zero (last column). That is `16 / n - 1` where `n` is the number of letters in the column (which is `N` in the code above). That what does the code at line (1): ``` *]*\ +2sllNt/16lN sllN # Computes the num of bits required to represent len(N) in binary +2 # To that, add two. We now have the length of a element of the current column *\ # Make a string of spaces of that length (note the trailing space) t/16lN # Computes 16 / len(N) - 1 *] # Make a list of that length with the string of spaces (something like [" ", " ", ...]) ``` Alright, now we have a nice helpful function `h` which basically generates a table's column out of a sequence of characters. Let's use it (note the two trailing spaces in the code below): ``` jmj*3\ d.t[h"ET"h"IANM"h"SURWDKGO"h"HVF L PJBXCYZQ h"ET" # Generate the first column h"IANM" # Generate the second column h"SURWDKGO" # Generate the third column h"HVF L PJBXCYZQ # Generate the last column (note the two trailing spaces) [ # Make a list out of those columns .t # Transpose, because we can print line by line, but not column by column mj*3\ d # For each line, join the elements in that line on " " (that is, concatenate the elements of the lines but insert " " between each one) j # Join all lines on newline ``` The code can still be shortened; maybe I'll come back on it later. [Answer] # C, ~~199~~ 195 bytes ``` #define P putchar m;p(i,v){printf("%*s",i&1|!v?v*(v+11)/2:3,"");for(m=1<<v;m;m/=2)P(45+!(i&m));P(32);P(" ETIANMSURWDKGOHVF L PJBXCYZQ "[i]);v<3?p(2*i,v+1):P(10);++i&1&&p(i,v);}main(){p(2,0);} ``` [Live on coliru](http://coliru.stacked-crooked.com/a/18bd88113a0d7ea9) (with #include to avoid the warning message.) *UPDATE*: Saved four characters by moving the "declaration" of `m` outside the function, as suggested by @zacharyT Uses what seems to be a standard strategy: keep the letters in an array-encoded binary tree, so the children of element `i` are `2*i` and `2*i+1`. This tree is rooted at 2 rather than 1 because the arithmetic worked out a little shorter, I think. All the rest is golfing. Ungolfed: ``` // Golfed version omits the include #include <stdio.h> // Golfed version uses the string rather than a variable. char* tree = " ETIANMSURWDKGOHVF L PJBXCYZQ "; /* i is the index into tree; v is the number of bits to print (-1) */ void p(int i, int v) { /* Golfed version omits all types, so the return type is int. * Nothing is returned, but on most architectures that still works although * it's UB. */ printf("%*s", i&1 || !v ? v*(v+11)/2 : 3, ""); /* v*(v+11)/2 is v*(v+1)/2 + 3*v, which is the number of spaces before the odd * element at level v. For even elements, we just print the three spaces which * separate adjacent elements. (If v is zero, we're at the margin so we * suppress the three spaces; with v == 0, the indent will be 0, too. * * Golfed version uses | instead of || since it makes no semantic difference. */ /* Iterate over the useful bits at this level */ for (int m=1<<v; m; m/=2) { /* Ascii '-' is 45 and '.' is 46, so we invert the tested bit to create the * correct ascii code. */ putchar('-' + !(i&m)); } /* Output the character */ putchar(' '); putchar(tree[i]); /* Either recurse to finish the line or print a newline */ if (v<3) p(2*i,v+1); else putchar('\n'); /* For nodes which have a sibling, recurse to print the sibling */ if (!(i&1)) p(i+1, v); } int main(void) { p(2,0); } ``` [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 133 bytes ``` 000000: e0 01 be 00 7d 5d 00 17 08 05 23 e4 96 22 00 5d │ à.¾.}]....#ä.".] 000010: e5 e9 94 d3 78 24 16 ec c1 c4 ad d8 6e 4d 41 e8 │ åé.Óx$.ìÁÄ.ØnMAè 000020: a3 a1 82 e6 f4 88 d9 85 6f ae 6b 93 aa 44 c8 e3 │ £¡.æô.Ù.o®k.ªDÈã 000030: 29 6f df 65 aa 4a f8 06 f5 63 1a 73 a7 e4 4d 19 │ )oßeªJø.õc.s§äM. 000040: 03 2c 87 59 7b df 27 41 4b b6 12 dd 7c e5 78 27 │ .,.Y{ß'AK¶.Ý|åx' 000050: 9c 9f 99 db f6 8e 42 fd 43 68 48 46 37 da d7 21 │ ...Ûö.BýChHF7Ú×! 000060: a9 ca ea be f4 57 e0 da c1 16 97 ef 7a 0c e9 3c │ ©Êê¾ôWàÚÁ..ïz.é< 000070: 8e c2 b6 22 ca e4 e5 53 57 f0 f4 fb a4 fb c0 a7 │ .¶"ÊäåSWðôû¤ûÀ§ 000080: ec cd 6e 00 00 │ ìÍn.. ``` Compressed as a LZMA stream. [Answer] # C, 291 bytes [**Try Online**](http://ideone.com/Ls8woT) ``` char*i,*t=".aEc..aIc...aSc....aH/u...-aV/m..-aUc..-.aF/u..--/f.-aAc.-.aRc.-..aL/u.-.-/m.--aWc.--.aP/u.---aJ/-aTc-.aNc-..aDc-...aB/u-..-aX/m-.-aKc-.-.aC/u-.--aY/f--aMc--.aGc--..aZ/u--.-aQ/m---aOc---./u----"; s(n){while(n--)putchar(32);}f(){for(i=t;*i;i++)*i<97?putchar(*i-'/'?*i:10):s(*i-96);} ``` **How it works** First I parsed the string in C, counting spaces which are less than 26 so I encoded them in small case letters `a, b, .. z` with [**this little program**](http://ideone.com/nSYC0E) ``` for(char*i=t; *i; i++) { if(*i == ' ') c++; else c = 0; if(i[1] != ' ' && c > 0) putchar('a'+c-1); else if(*i =='\n') putchar('/'); else if(*i != ' ') putchar(*i); } ``` Then I wrote a parser for that encoding, where `/` is a new line, and a small-case letter represent `t[i] - 'a'` spaces ``` int s(int n) { while(n--) putchar(32); } f() { for(char*i=t; *i; i++) if(*i < 'a') if(*i == '/') putchar('\n'); else putchar(*i); else s(*i-'a'+1); } ``` [Answer] # Bash (with utilities), 254 bytes ``` tail -n+2 $0|uudecode|bzip2 -d;exit begin 644 - M0EIH.3%!6293631+'LX``&UV`%`P(`!``S____`@`(@:2!H#:@!ZFU'H@T]( MJ>H`'J``;4L>\%)R2H9TS-4WY[M(`"`@=((AJ")8HR^QFK?8RQO2B+W47&@` M!"@$(!%Q,$'X:#+&>BI<RAC5.J53,S(%FFB!%A-*SM9TY&I8RFZJ9<D0H_B[ )DBG"A(&B6/9P ` end ``` [Answer] # Dyalog APL, 159 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each) (non-competing) ``` ↑{X←⍵-1⋄Y←2*⍳4⋄R←Y+(Y÷16)×⍵-1⋄3↓∊{C←R[⍵]⋄' ',(⍵⍴(1+0=1|C)⊃' '({⍵⊃'.-'}¨1+(4⍴2)⊤X)),' ',((1+0=1|C)⊃' '((C-1|C)⊃' ETIANMSURWDKGOHVF L PJBXCYZQ '))}¨⍳4}¨⍳16 ``` [Answer] # JavaScript (ES7), ~~242~~ ~~240~~ 238 bytes ``` console.log([...'EISH000V00UF000 0ARL000 00WP000JTNDB000X00KC000Y0MGZ000Q00O 000 '].map((a,k)=>(n=>(a!='0'?(2**n+(k>>2)/2**(4-n)).toString(2).slice(-n).replace(/./g,c=>'.-'[c])+' '+a:' '.slice(-n-2))+(n<4?' ':'\n'))(k%4+1)).join``) ``` [Try it online!](https://tio.run/##Pc1Zb4MwDADgv8IeJttNEzzEUzWodh/d3d1dpaYsQpQsQYD291nah1myPsuHvNG/uivaqunlWq@Nlc5/m2EovOu8Ncr6EhdKKTi7ml8y8yvzy3kw4qOnm5389hC8fr47PQ6@M89Ogh98e/EZfGS@j7Z7sFQ/ukHU45qyHF1IvZcBwxST0cgJrPM8oTjUmEpHpHo/79vKlZiQ6mxVGAxt1ZrG6lDHKi7HRZaDkrAoliQgAqEnEO0C/i9kQiTQHabT7Qgm8OWACOv9VByEJxtfudWKhuEP "JavaScript (Babel Node) – Try It Online") –2 bytes thanks to [Zachary](https://codegolf.stackexchange.com/users/55550/zachary-t). [Answer] # Deadfish~, 1329 bytes ``` {iiii}iiiiiic{d}ddddc{iiii}dddc{dddd}iiiccc{i}iiiicc{d}ddddc{iiii}ic{dddd}dccc{i}iiiiccc{d}ddddc{iiiii}ic{ddddd}dccc{i}iiiicccc{d}ddddc{iiii}c{dddddd}ddc{ii}ii{cc}c{i}iiiicccdc{d}dddc{iiiii}iiiic{{d}iii}ddddddc{ii}ii{c}ccc{i}iiiiccdc{d}dddc{iiiii}iiic{ddddd}dddccc{i}iiiiccdcic{d}ddddc{iiii}ddc{dddddd}c{ii}ii{cc}c{i}iiiiccdcc{d}dddcc{dd}ddc{ii}iicccccc{i}iiiicdc{d}dddc{iii}iiic{ddd}dddccc{i}iiiicdcic{d}ddddc{iiiii}c{ddddd}ccc{i}iiiicdcicc{d}ddddc{iiii}iiiic{dddddd}ddddddc{ii}ii{cc}c{i}iiiicdcicdc{d}dddcc{dd}ddc{ii}ii{c}ccc{i}iiiicdcc{d}dddc{iiiii}iiiiic{ddddd}dddddccc{i}iiiicdccic{d}ddddc{iiiii}ddc{{d}iii}c{ii}ii{cc}c{i}iiiicdccc{d}dddc{iiii}iic{dddddd}ddddc{iii}iiiiic{d}dddc{iiiii}iic{ddddd}ddccc{i}iiicic{d}ddddc{iiii}iiiiiic{dddd}ddddddccc{i}iiicicc{d}ddddc{iii}iiiiiic{ddd}ddddddccc{i}iiiciccc{d}ddddc{iii}iiiic{ddddd}ddddddc{ii}ii{cc}c{i}iiiciccdc{d}dddc{iiiii}iiiiiic{{d}ii}iic{ii}ii{c}ccc{i}iiicicdc{d}dddc{iiii}iiic{dddd}dddccc{i}iiicicdcic{d}ddddc{iii}iiiiic{dddddd}iiic{ii}ii{cc}c{i}iiicicdcc{d}dddc{iiiiii}dddc{{d}ii}ic{ii}iicccccc{i}iiicc{d}dddc{iiii}iiiiic{dddd}dddddccc{i}iiiccic{d}ddddc{iiii}dc{dddd}iccc{i}iiiccicc{d}ddddc{iiiiii}ddc{{d}ii}c{ii}ii{cc}c{i}iiiccicdc{d}dddc{iiiii}dc{{d}iii}dc{ii}ii{c}ccc{i}iiiccc{d}dddc{iiiii}dddc{ddddd}iiiccc{i}iiicccic{d}ddddcc{dd}ddc{ii}ii{cc}c{i}iiicccc{d}dddcc{dd}ddc ``` [Try it online!](https://deadfish.surge.sh/#LGvd9WS0r/f/4p1Qv91Cqn+At/4KdUL/eKqcAt/4CnVC/94qqcAt/4Ap1Qv9iqqdC9+gYt/4EKdQv/f+JT/dVQvfoYC3/hCnUL/3+KqnUAt/4RinVC/3QqqmL36Bi3/hAp1AqdC9+AAt/5CnUL9/iqdQC3/kYp1Qv/YqqYC3/kYKdUL/f+Kqp1VC9+gYt/5GQp1AqdC9+hgLf+QKdQv/f/iqp1UAt/5BinVC/90JT/YvfoGLf+QCnUL/fiqqdUL9/+KdQv/fiqp0At/mKdUL/f/4qp1VALf5gp1Qv3/+Kp1VALf5gKdUL9/4qqdVQvfoGLf5hCnUL/3/+JT9+L36GAt/mQp1C/3+KqdQC3+ZGKdUL9/+Kqp/i9+gYt/mQKdQv/3UJT94vfgALf4KdQv9/+KqdVALf4Yp1Qv9wqp4C3+GCnVC//dCU/YvfoGLf4ZCnUL/3CU/3C9+hgLf4CnUL/3UKqn+At/gYp1QKnQvfoGLf4Ap1AqdAA==) [Answer] # Excel, 208 bytes ``` =LET(x,ROW(1:16)-1,d,{1,2,3,4},y,4-d,z,2^y,m,IF(MOD(x,z)=0,SUBSTITUTE(SUBSTITUTE(DEC2BIN(x/z,d),"0","."),"1","-")&" "&MID(" ETIANMSURWDKGOHVF L PJBXCYZQ",2^d+x/z,1),""),CONCAT(m&IF(y,REPT(" ",9-LEN(m))," "))) ``` ## Explanation ``` =LET(x,ROW(1:16)-1, 'x = {0..15} 0-indexed row d,{1,2,3,4}, 'd = {1..4} 1-indexed column length of code y,4-d, 'y = {3..0} z,2^y, 'z = {8,4,2,1} m,IF(MOD(x,z)=0, 'm = if x%z = 0 then DEC2BIN(x/z,y) ' binary representation of x/z length y SUBSTITUTE(SUBSTITUTE( ,"0","."),"1","-") ' change "0" to "." and "1" to "-" &" "&MID(" ETIANMSURWDKGOHVF L PJBXCYZQ",2^d+x/z,1), ' & " " & corresponding letter ""), ' else "" CONCAT(m&IF(y,REPT(" ",9-LEN(m))," 'concatenate the elements of m and pad w/ spaces and line feeds "))) ``` ]