text
stringlengths
26
126k
[Question] [ **GolfScript** automatically coerces values, according to the following ‘priority’ sequence: > > integer → array → string → block > > > (listed from lowest to highest.) This means that `"1"7+` leaves the string `"17"` on the stack (and not `8`), because strings have a higher priority than integers. [*To those GolfScript veterans – apologies for insulting your respective intelligences.*] How would it be possible to do this the other way? That is, to **coerce a string into an integer**? [Answer] There's an operator `~` in golfscript, which does the following: `bitwise not, dump, eval`. Therefore, `"1"` will give the string `"1"` while `"1"~` will evaluate that string (into the integer `1`). Then, all you need to do is `"1"~7+`. [Try it online!](http://golfscript.tryitonline.net/#code=IjEifjcr&input=) ]
[Question] [ Output the **current time of day** as [Swatch Internet Time](https://en.wikipedia.org/wiki/Swatch_Internet_Time). Specifically, output a three-digit (zero-padded) number of "[.beats](https://en.wikipedia.org/wiki/Swatch_Internet_Time#Beats)" (1000ths of a day) which represent the current time of day in the Swatch Internet Time time zone of UTC+01:00 ("Biel Meantime"). For example, if the current time in UTC is `23:47`, then it is `00:47` in UTC+1 ("Biel Meantime"), and the output would be `032`. **Examples**: ``` UTC Current Time -> SIT Output 23:47 -> 032 23:00 -> 000 11:00 -> 500 14:37 -> 651 ``` The program should produce this output then immediately exit. Output is to standard output (or equivalent). **Must be a complete, runnable program, not a function.** The program takes no input; it outputs the *current* time. [Answer] # PHP, 12 bytes ``` <?=@date(B); ``` But it can only be so short because PHP has built-in Swatch Internet Time support. So this answer isn't much fun. --- `<?=` exits HTML mode and evaluates an expression, then echoes it. `@` silences an error. `date()` outputs the current time, formatting it with a given format string. `B` is an undefined constant. In PHP, if you reference a constant that doesn't exist, you get back a string containing its name, and it also produces a “notice”-level error. Here, the `@` suppresses that error. `B` is the `date()` format code for Swatch Internet Time. `;` terminates the expression. --- If we assume PHP is being run with the default error-reporting settings, where “notices” are silenced, we could skip the `@`, and it would only be 11 bytes. [Answer] # C, *56 bytes* ``` main(){printf("%03d",(int)((time(0)+3600)%86400/86.4));} ``` Explanation: * **%03d** - tells printf to zero-pad up to 3 digits. * **time(NULL)+3600** - gets amount of seconds (UTC) elapsed since epoch and adds an hour to it (UTC+1). * **%86400** - divides epoch by the amount of seconds in a 24hr day and gets the remainder (representing seconds elapsed, so far, "today"). * **/86.4** - divide remaining seconds by 86.4 to get the ".beat" count since midnight (UTC+1). ### Compile (MSVC): C:> cl swatch.c ### Compile (GCC): $ gcc swatch.c [Answer] # PHP, ~~48~~ 46 bytes ``` <?=sprintf("%03d",((time()+3600)%86400)/86.4); ``` I have another PHP answer above, but this one avoids using PHP's built-in Swatch Internet Time support, so it's more interesting, if longer. This is largely self-explanatory if you're familiar with UNIX time and `sprintf`, ~~though note I'm using `|0` as a short way to truncate a float to an integer~~ (actually I realised this is unnecessary in PHP, oops!) [Answer] # Java 8, 143 bytes ``` import java.time.*;interface A{static void main(String[]a){System.out.format("%03.0f",LocalTime.now(ZoneId.of("UT+1")).toSecondOfDay()/86.4);}} ``` this uses Java 8's java.time package to get current time, convert it to UTC+1, and then get the number of seconds. At the end it divides by the number of 1000s of seconds in a day, which turns out to be 86.4. Funny how the function that actually calculates the time is only about a third of the overall program size. [Answer] # 05AB1E, ~~29~~ 21 bytes ``` ža>60©%®*žb+₄*1440÷Dg3s-Å0š˜J ``` After compressing integers thanks to @KevinCruijssen (-8 bytes) : ``` ža>60©%®*žb+₄*Ž5¦÷₄+¦ ``` Explanation: ``` ža>60©%®*žb+₄*1440÷Dg3s-Å0š˜J ža push current hours in UT > increment 60© push 60 and save in register c % hours mod 60 ®* push from register c and Multiply žb+ add current minutes ₄* multiply by 1000 1440÷ Integer division with 1440 D Duplicate g Length 3s- 3-length Å0 create list of a 0s š Prepand ˜J Flat and joon ``` I didn't find a better idea for prepanding Zeros, so if anyone got a better idea I'll be glad to know :) [Try it online!](https://tio.run/##ATEAzv9vc2FiaWX//8W@YT42MMKpJcKuKsW@YivigoQqMTQ0MMO3RGczcy3DhTDFocucSv//) [Try the 21 bytes online!](https://tio.run/##yy9OTMpM/f//6L5EOzODQytVD63TOrovSftRU4vW0b2mh5Yd3g5kah9a9v8/AA) [Answer] # Javascript, ~~53~~ ~~52~~ 48 bytes ``` alert((new Date/864e5%1+1/24+'0000').slice(2,5)) ``` Explanation: `new Date/864e5%1` is the fraction of a day in UTC. `+1/24` adds 1/24th of a day (1 hour), moving it to UTC+1. `"0000"` is concatenated with this, turning it into a string. Then the 3rd through 5th characters are taken. The reason `"0000"` is concatenated instead of an empty string is for the cases in which there are fewer than 3 decimal places: * `"0.XXX`(any number of digits here)`0000"` Swatch time is XXX * `"0.XX0000"` Swatch time is XX0 * `"0.X0000"` Swatch time is X00 * `"00000"` Swatch time is 000 (the first character is 1 instead of 0 from 23:00 UTC to 24:00 UTC, but the first character is ignored.) [Answer] # JavaScript, 98 bytes ``` d=new Date();t=;console.log(Math.floor((360*d.getHours()+60*d.getMinutes()+d.getSeconds())/86.4)); ``` Definitely could be optimized, I had some problems with the `Date` object so I'm looking into shorter ways to do that. [Answer] # Octave, 64 bytes ``` t=gmtime(time);sprintf("%03.f",(mod(++t.hour,24)*60+t.min)/1.44) ``` Uses [veganaiZe's](https://codegolf.stackexchange.com/a/85107/42892) `printf` formatting. I'm having a bit of difficulty with the time that ideone is returning, so here's a sample run with the time struct returned by `gmtime` for reference. I'll look around and see if I can get any of the other online Octave compilers to give me proper time. ``` t = scalar structure containing the fields: usec = 528182 sec = 17 min = 24 hour = 21 mday = 15 mon = 6 year = 116 wday = 5 yday = 196 isdst = 0 zone = UTC ans = 933 ``` [Answer] # q/k (21 bytes) ``` 7h$1e3*(.z.n+0D01)%1D ``` [Answer] # Python 2.7, ~~131~~ ~~128~~ 121 bytes: ``` from datetime import*;S=lambda f:int(datetime.utcnow().strftime(f));print'%03.0f'%(((S('%H')+1%24)*3600+S('%M')*60)/86.4) ``` A full program that outputs the Swatch Internet Time. Simply uses Python's built in `datetime` module to first get the `UTC+0` time in hours and minutes using `datetime.utfnow().strftime('%H')` and `datetime.utfnow().strftime('%M')`, respectively. Then, the time is converted into `UTC+1` by adding `1` to the hours and then modding the sum by `24` to ensure the result is in the 24-hour range. Finally, the hour is turned into its equivalent in seconds, which is added to the minute's equivalent in seconds, and the resulting sum is divided by `86.4`, as there are `86.4` seconds or `1 min. 24 sec.` in 1 ".beat", after which, using string formatting, the quotient is rounded to the nearest integer and padded with zeroes until the length is `3`. --- However, I am not the one to stop here. In the above solution, I used a more direct method to convert the time to `UTC+1`. However, wanted to add a bit of a bigger challenge for myself and implement this using *only* Python's built in `time` module, which apparently does *not* have any built-in method that I know of to convert local time into `UTC+0` time. So now, without further ado, here is the perfectly working version using *only* the time module, currently standing at **125 bytes**: ``` from time import*;I=lambda g:int(strftime(g));print'%03.0f'%((((I('%H')+1-daylight)%24*3600+timezone)%86400+I('%M')*60)/86.4) ``` This can output the correct Swatch Internet Time for *any and all* time zones, and basically does pretty much everything the same as in the first solution, except this time converts the local time into `UTC+1` by first adding `1` to the hour, and then subtracting `1` if daylight-savings time is currently, locally observed, or `0` otherwise. Then, this difference is modded by `24` to ensure that the result stays within the `24` hour range, after which it is multiplied by `3600` for conversion into seconds. This product is then added to the result from the built-in `timezone` method, which returns the local offset from `UTC+0`. After this, you finally have your hours in `UTC+1`. This then continues on from here as in the first solution. [Answer] # Javascript, 83 bytes ``` a=(((36e5+(+new Date()))%864e5)/864e2).toFixed(),alert("00".slice(Math.log10(a))+a) ``` [Answer] # [CJam](https://sourceforge.net/projects/cjam/), 34 bytes Update: I shouldn't code hungry. My previous answer was shorter, but didn't cast to int or left-pad. These are now fixed, with +8 bytes to left-pad (probably improvable), +1 to int cast, and -2 to optimizations. My old comment no longer applies. ``` r':/~\~)24md60*@~+1.44/i"%03d"e%o; ``` [Try it online](https://tio.run/##S85KzP3/v0jdSr8upk7TyCQ3xcxAy6FO21DPxEQ/U0nVwDhFKVU13/r/fyNjKxNzAA) Explanation: ``` r read input ':/ split on : ~ unwrap array \~ evaluate hour to numbers ) increment hour 24md modulo 24 60* multiply by 60 @~ switch to minute and eval to num + add hour*60 and minute 1.44/ divide by 1.44 to get SIT i cast to int "%03d"e% format as 3 leading 0s o; output and discard spare 0 from modulo ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~27 23 19~~ 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Kj z86400 s t3n ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=S2ogejg2NDAwIHMgdDNu) Javascript port. I hope I've done it correctly. -4 bytes from Shaggy. -4 more bytes from Shaggy. -4 more more bytes from Shaggy. [Answer] # [Python 3](https://docs.python.org/3/), 64 bytes ``` import time t=time.gmtime() print(int(-~t[3]%24/.024+t[4]/1.44)) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEkMzeVq8QWROml54IoDU2ugqLMvBINENatK4k2jlU1MtHXMzAy0S6JNonVN9QzMdHU/P8fAA "Python 3 – Try It Online") [Answer] # C#, 112 bytes ``` class P{static void M(){System.Console.Write((int)((DateTime.UtcNow.TimeOfDay.TotalSeconds%86400+3600)/86.4));}} ``` --- # C#, 68 bytes ``` ()=>(int)((DateTime.UtcNow.TimeOfDay.TotalSeconds%86400+3600)/86.4); ``` A simple port of @veganaiZe's code. Thanks to him :) [Try it online!](https://dotnetfiddle.net/7yE0Lz) [Answer] ## Common Lisp (Lispworks), 144 bytes ``` (defun f(s)(let*((d(split-sequence":"s))(h(parse-integer(first d)))(m(parse-integer(second d))))(round(/(+(*(mod(1+ h) 24)3600)(* m 60))86.4)))) ``` ungolfed: ``` (defun f (s) (let* ((d (split-sequence ":" s)) (h (parse-integer (first d))) (m (parse-integer (second d)))) (round (/ (+ (* (mod (1+ h) 24) 3600) (* m 60)) 86.4)))) ``` usage: ``` CL-USER 2759 > (f "23:47") 33 -0.36111111111111427 ``` ]
[Question] [ Write a program that, given any 'n' number of strings of 'm' length, returns 'm' number of 'n'-length strings, with this condition: **Every new string should contains the letters at the same index of the others strings** For example, the first output string must contain the first letter of all the input strings, the second output string must contain the second letter of all the input strings, and so on. Examples (the numbers under the letters are the indexes of the strings): ``` input: "car", "dog", "man", "yay" 012 012 012 012 output: "cdmy", "aoaa", "rgny" 0000 1111 2222 input: "money", "taken", "trust" 01234 01234 01234 output: "mtt", "oar", "nku", "ees", "ynt" 000 111 222 333 444 ``` Assume that the input is correct everytime Shortest bytes' code wins! **Edit:** Since there are many programming languages, and there could be many possible solutions for each of them, I will post the shortest solution for each programming language and the user who provided it. Keep coding! **Re-Edit:** Thanks to user [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) I inserted a snippet for the leaderboards. ``` var QUESTION_ID=85255,OVERRIDE_USER=56179;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] ## Pyth, 1 byte ``` C ``` [Try it here](http://pyth.herokuapp.com/?code=C&input=%22car%22%2C+%22dog%22%2C+%22man%22%2C+%22yay%22&debug=0) Another transpose builtin [Answer] # Python, ~~36~~ 29 bytes `zip(*s)` returns a list of tuples of each character, transposed. ``` lambda s:map(''.join,zip(*s)) ``` [**Try it online**](https://repl.it/CbMM/1) [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 1 byte ``` Z ``` [Try it online!](http://jelly.tryitonline.net/#code=WgrDh-KCrEc&input=&args=WyJjYXIiLCAiZG9nIiwgIm1hbiIsICJ5YXkiXSwgWyJtb25leSIsICJ0YWtlbiIsICJ0cnVzdCJd) [Answer] # Vim, ~~37~~ 36 keystrokes All the other answers are boring, and using boring single-byte builtins. Here's a hacky answer that does the entire thing manually, in something that isn't even a programming language: ``` Gmaqqgg:s/./&<cr>d<C-v>`aGo<esc>pvGgJ@qq@q`adgg ``` Explanation: ``` G "move to the end of this line ma "And leave mark 'a' here qq "Start recording in register 'q' gg "Move to the beginning :s/./&<cr> "Assert that there is atleast one character on this line d "Delete <C-v> "Blockwise `a "Until mark 'a' G "Move to the end of the buffer o<esc> "Open a newline below us p "And paste what we deleted vG "Visually select everything until the end gJ "And join these without spaces @q "Call macro 'q'. The first time, this will do nothing, "The second time, it will cause recursion. q "Stop recording @q "Call macro 'q' to start it all ``` Now, everything is good, but the buffer has some extra text left over. So we must: ``` `a "Move to mark 'a' dgg "And delete everything until the first line ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 1 byte ``` ! ``` [**Try it online!**](http://matl.tryitonline.net/#code=IQ&input=WydjYXInOyAnZG9nJzsgJ21hbic7ICd5YXknXQ) Takes input implicitly, transposes, displays output implicitly. [Answer] ## PowerShell v2+, ~~66~~ 54 bytes ``` param($n)for($x=0;$n[0][$x];$x++){-join($n|%{$_[$x]})} ``` Yo ... no `map`, no `zip`, no `transpose`, etc., so we get to roll our own. Big props to [@DarthTwon](https://codegolf.stackexchange.com/users/56063/darth-twon) for the 12-byte golf. Takes input `$n`, sets up a `for` loop. Initialization sets `$x` to `0`, the test is whether we still have letters in our word `$n[0][$x]`, and we increment `$x++` each iteration. Inside the loop, we take our array of strings, pipe it to an inner loop that spits out the appropriate character from each word. That is encapsulated in a `-join` to form a string, and that string is left on the pipeline. At end of execution, the strings on the pipeline are implicitly printed. ``` PS C:\Tools\Scripts\golfing> .\convert-n-strings.ps1 "Darth","-Twon","Rocks" D-R aTo rwc tok hns ``` [Answer] ## CJam, ~~6~~ 5 bytes *Saved 1 byte thanks to Luis Mendo.* ``` qS%zp ``` [Try it online!](http://cjam.aditsu.net/#code=q%20%20%20%20%20%20e%23%20Get%20all%20input%0A%20S%25%20%20%20%20e%23%20Split%20it%20on%20spaces%0A%20%20%20z%20%20%20e%23%20Take%20the%20transpose%0A%20%20%20%20p%20%20e%23%20Print%20it%20as%20an%20array&input=car%20man%20dog%20yay) ``` q e# Get all input S% e# Split it on spaces z e# Take the transpose p e# Print it as an array ``` [Answer] ## [Retina](https://github.com/m-ender/retina), ~~45~~ 43 bytes Byte count assumes ISO 8859-1 encoding. ``` O$#`.(?<=(.+))|¶ $.1 !`(?<=(¶)+.*)(?<-1>.)+ ``` The leading linefeed is significant. Input and output are linefeed-terminated lists of printable ASCII strings (note that both have a single trailing linefeed). [Try it online!](http://retina.tryitonline.net/#code=TyQjYC4oPzw9KC4rKSl8wrYKJC4xCiFgKD88PSjCtikrLiopKD88LTE-Likr&input=YWJjZGUKZmdoaWoKa2xtbm8K) I knew for a while that transposing rectangular blocks would be a pain in Retina (whereas transposing squares isn't too bad), but never actually tried. The first solution was indeed a whopping 110 bytes long, but after several substantial changes in the approach, the resulting 45 bytes are by far not as bad as I suspected (but still...). Explanation will follow tomorrow. ### Explanation **Stage 1: Sort** ``` O$#`.(?<=(.+))|¶ $.1 ``` This does the main work of reordering the characters in the input, but it ends up messing up the separation into lines. Interestingly, if we remove the `|¶`, we get the code required to transpose a square input. Sort stages (denoted by the `O`) work like this: they find all matches of the given regex (the thing after the ```), and then sort those matches and reinsert them into the places where the matches were found. As it happens, this regex matches every single character: non-linefeeds via the `.(?<=(.*))` alternative and linefeeds via the `¶`. Hence, it sorts all characters in the input. The more interesting part is what they are sorted *by*. The `$` option activates a "sort-by" mode, where each match is replaced with the substitution pattern on the second line, which is then used for comparing the matches. Furthermore, the `#` tells Retina to convert the result of the substitution to an integer, and compare those integers (instead of treating them as strings). So finally, we need to look at the regex and the substitution. If the first alternative matches (i.e. we have matched any character within one of the lines), then the `(?<=(.*))` captures everything up to that character on that line into group `1`. The `$.1` in the substitution pattern replaces this with the *length* of group `1`. Hence, the first character in each string becomes `1`, the second becomes `2`, the third becomes `3` and so on. It should be clear now how this transposes a square input: all the first characters of the lines come first and all end up in the top-most line, then all the second characters end up in the second line and so on. But for these rectangular inputs, we're also matching the linefeeds. Since group `1` is unused in this case, the substitution is empty, but for the purposes of the `#` option, this is considered `0`. That means, all the linefeeds are sorted to the front. So now we do have the characters in the first order (first character of each string, second character of each string, etc.) and all the linefeeds at the start. **Stage 2: Match** ``` !`(?<=(¶)+.*)(?<-1>.)+ ``` We now need to split up the characters into lines of the correct length. This length corresponds to the number of lines in the original input, which is corresponds to the number of linefeeds we have at the beginning of the string. The splitting is done here with the help of a match stage, which simply finds all matches of the given regex and uses the `!` option to print those matches (the default would be to count them instead). So the goal of the regex is to match one line at a time. We start by "counting" the number with the lookbehind `(?<=(¶)*.*)`. It generates one capture in group `1` for every linefeed at the front. Then, for each of those captures, we match a single character with `(?<-1>.)+`. [Answer] ## Pyke, 1 byte ``` , ``` [Try it here!](http://pyke.catbus.co.uk/?code=%2C&input=%22money%22%2C+%22taken%22%2C+%22trust%22) Transpose. [Answer] # x86 machine code, 19 bytes In hex: ``` fc89d35651a401dee2fb91aa595e464a75f1c3 ``` Input: `ECX`: # of strings (n), `EDX`: individual string length (m), `ESI`: array of input strings, `EDI`: output buffer receiving array of strings. Array is presumed to be defined as `char src[n][m+1]` for input and `char dst[m][n+1]` for output, and all strings are NULL-terminated. ``` 0: fc cld 1: 89 d3 mov ebx,edx ;EDX is the counter for the outer loop _outer: 3: 56 push esi 4: 51 push ecx _inner: 5: a4 movsb ;[EDI++]=[ESI++] 6: 01 de add esi,ebx ;Same char, next string 8: e2 fb loop _inner ;--ECX==0 => break a: 91 xchg eax,ecx ;EAX=0 b: aa stosb ;NULL-terminate just completed string c: 59 pop ecx d: 5e pop esi ;First string, e: 46 inc esi ;...next char f: 4a dec edx 10: 75 f1 jnz _outer 12: c3 ret ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` z:ca. ``` Expects a list of strings as input, e.g. `run_from_atom('z:ca.',["money":"taken":"trust"],Output).` ### Explanation ``` z Zip the strings in the Input list :ca. output is the application of concatenation to each element of the zip ``` [Answer] ## 05AB1E, 3 bytes ``` ø€J ``` **Explained** ``` # implicit input, eg: ['car', 'dog', 'man', 'yay'] ø # zip, producing [['c', 'd', 'm', 'y'], ['a', 'o', 'a', 'a'], ['r', 'g', 'n', 'y']] €J # map join, resulting in ['cdmy', 'aoaa', 'rgny'] ``` [Try it online](http://05ab1e.tryitonline.net/#code=w7jigqxK&input=WydjYXInLCAnZG9nJywgJ21hbicsICd5YXknXQ) [Answer] # [CJam](https://sourceforge.net/projects/cjam/), 3 bytes ``` {z} ``` This is a code block (equivalent to a function; [allowed by default](https://codegolf.meta.stackexchange.com/q/2419/36398)) that expects the input on the stack and leaves the output on the stack. [**Try it online!**](http://cjam.tryitonline.net/#code=cX4gICAgZSMgcmVhZCBpbnB1dCBhcyBhbiBhcnJheQp7en0gICBlIyBhY3R1YWwgY29kZSBibG9jawp-ICAgICBlIyBldmFsdWF0ZSBjb2RlIGJsb2NrCnAgICAgIGUjIGRpc3BsYXkgYXMgYXJyYXk&input=WyJjYXIiICJkb2ciICJtYW4iICJ5YXkiXQ) [Answer] # JavaScript ES6, ~~48~~ 46 bytes ``` a=>[...a[0]].map((n,x)=>a.map(a=>a[x]).join``) ``` I feel left out, we have no built in zip function. Thanks nicael for pointing out my type error. Usage ``` (a=>[...a[0]].map((n,x)=>a.map(a=>a[x])))(["asd","dsa"]); //or whatever is above, might change due to edits ``` returns ``` ["ad","ss","da"] ``` [Answer] # Bash + BSD utilities, 27 ``` sed s/./\&:/g|rs -c: -g0 -T ``` I/O via STDIN/STDOUT newline-separated strings. You may need to install `rs` with `sudo apt install rs` or similar. Works out of the box on OS X. The `-T` option to `rs` does the heavy lifting of the transposition. The rest is just formatting: * The `sed` command simply inserts `:` after every character * `-c:` specifies input columns are `:` separated * `-g0` specifies output columns have zero width separation If my reading of the `rs` manpage is correct, then the following **ought** to work for a score of 12, but unfortunately it doesn't work - see note below: ``` rs -E -g0 -T ``` ### Example output: ``` $ printf "%s\n" car dog man yay |sed s/./\&:/g|rs -c: -g0 -T cdmy aoaa rgny $ ``` If input is expected to be all printable ASCII, then the `:` may be replaced with some unprintable character, e.g. 0x7 `BEL`. --- ### Note I wanted to understand why I couldn't get the `-E` option to work and get rid of the `sed` preprocessing. I found the [`rs` source code here](https://github.com/denghuancong/4.4BSD-Lite/blob/master/usr/src/usr.bin/rs/rs.c). As you can see, giving this option sets the `ONEPERCHAR` flag. However, there is nothing in the code that actually checks the state of this flag. So I think we can say that despite the fact that is option is documented, it is not implemented. In fact, this option is documented in the Linux `rs` manpage: > > -E Consider each character of input as an array entry. > > > but not the OS X version. [Answer] # PHP, 82 bytes ``` function f($a){foreach($a as$s)foreach(str_split($s)as$i=>$c)$y[$i].=$c;return$y;} ``` takes and returns an array of strings **break down** ``` function f($a) { foreach($a as$s) // loop through array $a foreach(str_split($s)as$i=>$c) // split string to array, loop through characters $y[$i].=$c; // append character to $i-th result string return$y; } ``` **examples** ``` $samples=[ ["asd","dsa"], ["ad","ss","da"], ["car", "dog", "man", "yay"], ["cdmy", "aoaa", "rgny"], ["money", "taken", "trust"], ["mtt", "oar", "nku", "ees", "ynt"] ]; echo '<pre>'; while ($samples) { echo '<b>in:</b> '; print_r($x=array_shift($samples)); echo '<b>out:</b> '; print_r(f($x)); echo '<b>expected:</b> '; print_r(array_shift($samples)); echo '<hr>'; } ``` [Answer] ## APL, 3 bytes ``` ↓⍉↑ ``` `↑` takes the input strings and turns them into a char matrix. `⍉` transposes the matrix. `↓` splits back the rows of the resulting matrix into strings. [Answer] # K, 1 [byte](https://codegolf.meta.stackexchange.com/a/9429/43319) ``` + ``` [Try it here!](http://johnearnest.github.io/ok/index.html?run=%2B(%22car%22%3B%22dog%22%3B%22man%22%3B%22yay%22)) Transpose [Answer] # Mathematica, 26 bytes ``` ""<>#&/@(Characters@#)& ``` Anonymous function. Takes a string list as input and returns a string list as output. The Unicode character is U+F3C7, representing `\[Transpose]`. Works by converting to a character matrix, transposing, and converting back to a string list. If the input/output format was stretched, then a simple 5-byte transpose would work: ``` #& ``` [Answer] # MATLAB / Octave, 4 bytes ``` @(x)x' ``` This defines an anonymous function. Input format is `['car'; 'dog'; 'man'; 'yay']`. [**Try it here**](http://ideone.com/7g6VaE). [Answer] # Haskell, 41 bytes ``` f l=zipWith($)[map(!!n)|n<-[0..]]$l<$l!!0 ``` Or with a bit more air: ``` f l = zipWith ($) [map (!! n) | n <- [0..]] $ l <$ (l !! 0) ``` The second list is the list of words repeated “the length of a word” time. On each list of words, we select the n-th letter of each word, giving the result. [Answer] ## Common Lisp, 62 bytes ``` (lambda(s)(apply'map'list(lambda(&rest x)(coerce x'string))s)) ``` The `map` function takes a result type (here `list`), a function *f* to apply and one or more sequences *s1*, ..., *sn*. All sequences are iterated in parallel. For each tuple of elements *(e1,...,en)* taken from those sequences, we call *(f e1 ... en)* and the result is accumulated in a sequence of the desired type. We take a list of strings, say `("car" "dog" "man" "yay")`, and use `apply` to call `map`. We have to do this so that the input list is used as more arguments to `map`. More precisely, this: ``` (apply #'map 'list fn '("car" "dog" "man" "yay")) ``` ... is equivalent to: ``` (map 'list f "car" "dog" "man" "yay") ``` And since strings are sequences, we iterate in parallel over all first characters, then all second characters, etc... For example, the first iteration calls *f* as follows: ``` (f #\c #\d #\m #\y) ``` The anonymous lambda takes the list of arguments given to it and coerces it back to a string. [Answer] ## Perl, 91 bytes So lengthy one.. ``` $l=<>;$p=index($l," ")+1;@i=split//,$l;for$a(0..$p-1){print$i[$a+$_*$p]for(0..$p);print" "} ``` [Try it here!](https://ideone.com/srDzwg) [Answer] # [Ruby](https://www.ruby-lang.org/), 40 bytes ``` ->a{a.map(&:chars).transpose.map &:join} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3NXTtEqsT9XITCzTUrJIzEouKNfVKihLzigvyi1NBwgpqVln5mXm1UPWKBQpu0dFKyYlFSjoKSin56SAqNzEPRFUmVirFxkIULlgAoQE) [Answer] # [J-uby](https://github.com/cyoce/J-uby), 24 bytes Port of [my Ruby answer](https://codegolf.stackexchange.com/a/254848/11261). ``` :*&A|:transpose|:*&:join ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWO6y01BxrrEqKEvOKC_KLU2uAfKus_Mw8iPRNxQIFt-hopeTEIiUdBaWU_HQQlZuYB6IqEyuVYmMhChcsgNAA) ## Explanation ``` :* & A | :transpose | :* & :join :* & A | # Map converting to character arrays, then :transpose | # Transpose, then :* & :join # Map with join ``` [Answer] # [Go](https://go.dev), 111 bytes ``` type S=[]string func f(I S)S{O:=make(S,len(I[0])) for _,s:=range I{for j,r:=range s{O[j]+=string(r)}} return O} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVBLasMwFKRbneLhlU3VULoqAR8gqxS8DKE8FNkoiSQjyQsjdJJuQqGH6FHa0_TJauhn4zFvRvPmzcvrYC_vI4oTDhI0KsOUHq0Lq6rXoXqbQn_3-GHDPEro2t3eB6fMwPrJCOjrDXRNF7frVuNJ1h0_S1Nvdvf7pmG9dfDM_bp1aMh5E_PgyN114ON2d9zftsWwdk1KzMkwOQPbVNZ-3jwse0dUDkg3iQBRcQvXGImVIDl23UBkAr30sG5JkR_F5XNVx0qgqzhUBztk0GgyzDhXif8SHfSc52gRM7rBkCDxf17aGrnoAp2-GFFAH_5Y6RAyYctac5oySOmXtYa0dHPpSeTQpZhyQ2RP5BHOphYrxUGsLKe-6Z-q_WFsZlRhLDGJfVd3uRT8Ag) [Answer] # [Japt](https://github.com/ETHproductions/japt), 1 [byte](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Simply transposes the input. ``` Õ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1Q&input=WyJtb25leSIsICJ0YWtlbiIsICJ0cnVzdCJd) [Answer] # Ruby, 46 bytes Probably the first time that "Ruby strings aren't Enumerables" is actually biting me hard since I had to map the strings into arrays before processing. (Normally having to use `String#chars` isn't enough of a byte loss to matter, but since I need to map them, it stings a lot more) ``` ->s{s.map!(&:chars).shift.zip(*s).map &:join} ``` [Answer] # Clojure, 68 bytes ``` #(map(fn[g](reduce(fn[a b](str a(nth b g)))""%))(range(count(% 0)))) ``` Maps a function which is just `reduce` (goes on elements of the list one by one and joins nth character of the string) on the range from 0 to length of the first string. See it online: <https://ideone.com/pwhZ8e> [Answer] # C#, 53 bytes ``` t=>t[0].Select((_,i)=>t.Aggregate("",(a,b)=>a+b[i])); ``` C# lambda (`Func`) where the output is `IList<string>` and the output is `IEnumerable<string>`. I dont know how work `zip` in other language but I can't find a way to use the [C#'s one](https://msdn.microsoft.com/en-us/library/dd267698(v=vs.110).aspx) here. `Aggregate` fit the need well. No transpose in C#, there is [one](https://stackoverflow.com/a/12839486/1248177) in Excel but I wont use it. [Try it online!](https://dotnetfiddle.net/sDajpJ) ]
[Question] [ The goal here is to simply reverse a string, with one twist: Keep the capitalization in the same places. Example Input 1: `Hello, Midnightas` Example Output 1: `SathginDim ,olleh` Example Input 2: `.Q` Exmaple Output 2: `q.` **Rules**: * Output to STDOUT, input from STDIN * The winner will be picked 13th of July on GMT+3 12:00 (One week) * The input may only consist of ASCII symbols, making it easier for programs that do not use any encoding that contains non-ASCII characters. * Any punctuation ending up in a position where there was an upper-case letter must be ignored. [Answer] ## Python, 71 bytes ``` lambda s:''.join((z*2).title()[c.isupper()-1]for c,z in zip(s,s[::-1])) ``` [Try it online](http://ideone.com/fork/py1Kjj) -3 bytes from Ruud, plus the inspiration for 2 more. -4 more bytes from FryAmTheEggman [Answer] # Python 2, 73 bytes Since the rules specify the input is ascii: ``` lambda s:''.join([z.lower,z.upper]['@'<c<'[']()for c,z in zip(s,s[::-1])) ``` All the credit goes to @Mego though, but I had not the reputation to just comment on his answer. [Answer] ## Perl, 31 + 2 (`-lp`) = 33 bytes *This solution is from [@Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel) (13 bytes shorter thant mine).* ``` s%.%(lc$&gt$&?u:l)."c chop"%eeg ``` But you'll need `l` and `p` switches on. To run it : ``` perl -lpe 's%.%(lc$&gt$&?u:l)."c chop"%eeg' ``` [Answer] # Pyth, ~~13~~ ~~11~~ ~~10~~ 9 bytes *Thanks to @FryAmTheEggman for reminding me about `V` and @LeakyNun for another byte.* ``` srV_Qm!/G ``` [Try it online!](http://pyth.tryitonline.net/#code=c3JWX1F9UnJHMQ&input=IkhlbGxvLCBNaWRuaWdodGFzIg) now on mobile, updating link in a bit [Answer] ## Python, 66 bytes ``` f=lambda s,i=0:s[i:]and(s[~i]*2).title()[~('@'<s[i]<'[')]+f(s,i+1) ``` Recurses through the indices `i`, taking the character `s[~i]` from the back and the case of `s[i]` from the front. Being capital is checked as lying in the contiguous range `@ABC...XYZ[`. Credit to FryAmTheEggman from the `(_*2).title()` trick. [Answer] ## TCC - 4 bytes ``` <>ci ``` [Try it online!](https://www.ccode.gq/projects/tcc.html?code=%3C%3Eci&input=Hello%2C%20Midnightas) Explanation: ``` - output is implicit in TCC <> - reverse string c - preserve capitalization i - get input ``` [Answer] ## [Retina](https://github.com/m-ender/retina), ~~75~~ ~~67~~ 65 bytes Byte count assumes ISO 8859-1 encoding. ``` $ ±·$` O$^`\G[^·] s{T`L`l`±. T01`l`L`±.*·[A-Z] ±· ±(.) $1± ·. · ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYAokCsKxwrckYApPJF5gXEdbXsK3XQoKc3tUYExgbGDCsS4KVDAxYGxgTGDCsS4qwrdbQS1aXQrCscK3CgrCsSguKQokMcKxCsK3LgrCtw&input=SGVsbG8sIE1pZG5pZ2h0YXMKLlEKLnE) (The first line enables a test suite with multiple linefeed-separated test cases.) [Answer] ## JavaScript (ES6), ~~95~~ 83 bytes ``` s=>[...t=s.toLowerCase()].reverse().map((c,i)=>s[i]==t[i]?c:c.toUpperCase()).join`` ``` Edit: Saved a massive 12 bytes thanks to @edc65. [Answer] ## Pyke, ~~11~~ ~~10~~ 9 bytes ``` _FQo@UhAl ``` [Try it here!](http://pyke.catbus.co.uk/?code=_FQo%40UhAl&input=Hello%2C+Midnightas) ``` _ - reversed(input) F - for i in ^ o - o+=1 Q @ - input[^] Uh - ^.is_upper()+1 Al - [len, str.lower, str.upper, ...][^](i) - "".join(^) ``` [Answer] # [J](http://jsoftware.com), 30 bytes ``` (={"_1 toupper@]|.@,.])tolower ``` Doesn't support non-ASCII [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~19~~ ~~16~~ ~~15~~ 13 bytes Thanks to **Emigna** for saving a 3 bytes! Probably gonna get beat by Jelly... Code: ``` Âuvy¹Nè.lil}? ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w4J1dnnCuU7DqC5saWx9Pw&input=SGVsbG8sIE1pZG5pZ2h0YXM). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 28 bytes ``` @lr:?z:1ac. h@u.,@A@um~t?|h. ``` ### Explanation * Main Predicate: ``` @lr Reverse the lowercase version of the Input :?z Zip that reversed string with the Input :1a Apply predicate 1 to each couple [char i of reverse, char i of Input] c. Output is the concatenation of the result ``` * Predicate 1: ``` h@u., Output is the uppercase version of the first char of Input @A@um~t? The second char of Input is an uppercase letter | Or h. Output is the first char of Input ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 13 bytes ``` PktGtk<)Xk5M( ``` [**Try it online!**](http://matl.tryitonline.net/#code=UGt0R3RrPClYazVNKA&input=J0hlbGxvLCBNaWRuaWdodGFzJw) ``` Pk % Implicit inpput. Flip, lowercase t % Duplicate Gtk< % Logical index of uppercase letters in the input string ) % Get letters at those positions in the flipped string Xk % Make them uppercase 5M( % Assign them to the indicated positions. Implicit display ``` [Answer] # TSQL, 175 bytes Golfed: ``` DECLARE @ varchar(99)='Hello, Midnightas' ,@o varchar(99)='',@i INT=0WHILE @i<LEN(@)SELECT @i+=1,@o+=IIF(ascii(x)=ascii(lower(x)),lower(y),upper(y))FROM(SELECT SUBSTRING(@,@i+1,1)x,SUBSTRING(@,len(@)-@i,1)y)z PRINT @o ``` Ungolfed ``` DECLARE @ varchar(99)='Hello, Midnightas' ,@o varchar(99)='' ,@i INT=0 WHILE @i<LEN(@) SELECT @i+=1,@o+=IIF(ascii(x)=ascii(lower(x)),lower(y),upper(y)) FROM (SELECT SUBSTRING(@,@i+1,1)x,SUBSTRING(@,len(@)-@i,1)y)z PRINT @o ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/508510/reverse-a-string-while-maintaining-the-capitalization-in-the-same-places)** [Answer] ## Actually, 25 bytes ``` ;`úíuY"ùû"E£`M@ùRZ`i@ƒ`MΣ ``` [Try it online!](http://actually.tryitonline.net/#code=O2DDusOtdVkiw7nDuyJFwqNgTUDDuVJaYGlAxpJgTc6j&input=ImFiQ2Qi) Explanation: ``` ;`úíuY"ùû"E£`M@ùRZ`i@ƒ`MΣ ; create a copy of the input `úíuY"ùû"E£`M for each character in input: úíuY 0-based index in lowercase English letters, or -1 if not found, increment, boolean negate (1 if uppercase else 0) "ùû"E£ `û` if the character is lowercase else `ù` (str.lower vs str.upper) @ùRZ make the other copy of the input lowercase, reverse it, and zip it with the map result `i@ƒ`M for each (string, function) pair: i@ƒ flatten, swap, apply (apply the function to the string) Σ concatenate the strings ``` [Answer] # Haskell, ~~83~~ ~~80~~ ~~75~~ 71 bytes The most straightforward way I could think of. ``` import Data.Char f a|isUpper a=toUpper|1>0=toLower zipWith f<*>reverse ``` [Answer] # PowerShell, ~~154~~, ~~152~~, ~~99~~, 86 bytes Thank you @TimmyD for saving me a whopping 47 bytes (I also saved an additional 6) Thank you @TessellatingHeckler for saving an additional 13 bytes. Latest: ``` param($a)-join($a[$a.length..0]|%{("$_".ToLower(),"$_".ToUpper())[$a[$i++]-in65..90]}) ``` Original: ``` param($a);$x=0;(($a[-1..-$a.length])|%{$_=$_.tostring().tolower();if([regex]::matches($a,"[A-Z]").index-contains$x){$_.toupper()}else{$_};$x++})-join'' ``` Normal formatting: Latest (looks best as two lines in my opinion): ``` param($a) -join($a[$a.length..0] | %{("$_".ToLower(), "$_".ToUpper())[$a[$i++] -in 65..90]}) ``` Explanation: ``` param($a)-join($a[$a.length..0]|%{("$_".ToLower(),"$_".ToUpper())[$a[$i++]-in65..90]}) param($a) # Sets the first passed parameter to variable $a -join( ) # Converts a char array to a string $a[$a.length..0] # Reverses $a as a char array |%{ } # Shorthand pipe to foreach loop ("$_".ToLower(),"$_".ToUpper()) # Creates an array of the looped char in lower and upper cases [$a[$i++]-in65..90] # Resolves to 1 if the current index of $a is upper, which would output "$_".ToUpper() which is index 1 of the previous array ``` Original: ``` param($a) $x = 0 (($a[-1..-$a.length]) | %{ $_ = $_.tostring().tolower() if([regex]::matches($a,"[A-Z]").index -contains $x){ $_.toupper() }else{ $_ } $x++ } ) -join '' ``` First time poster here, was motivated because I rarely see PowerShell, ~~but at ~~154~~ 152 bytes on this one... I can see why!~~ Any suggestions appreciated. I have learned that I must completely change my way of thinking to golf in code and its fun! [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 12 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` ⌽f¨⍨⊢≠f←819⌶ ``` `819⌶` is the case folding function `f←` because its name is long, we assign it to *f* `⊢≠f` Boolean where text differs from lower-cased text `f¨⍨` use that (1 means uppercase, 0 means lowercase) to fold each letter... `⌽` ... of the reversed text Handles non-ASCII according to the Unicode Consortium's rules. [Answer] ## CJam, 22 bytes ``` q_W%.{el\'[,65>&{eu}&} ``` [Test it here.](http://cjam.aditsu.net/#code=q_W%25.%7Bel%5C'%5B%2C65%3E%26%7Beu%7D%26%7D&input=Hello%2C%20Midnightas) [Answer] # Racket, 146 bytes ``` (λ(s)(build-string(string-length s)(λ(n)((if(char-upper-case?(string-ref s n))char-upcase char-downcase)(list-ref(reverse(string->list s))n))))) ``` Racket is bad at this whole "golfing" thing. *Shrug* As always, any help with shortening this would be much appreciated. [Answer] # Jolf, 21 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=zpxpZD8mzrMuX3BYaVM9cHhISHB4zrPOsw&input=SGVsbG8sIE1pZG5pZ2h0YXMKCi5R) ``` Μid?&γ._pXiS=pxHHpxγγ ``` ## Explanation ``` Μid?&γ._pXiS=pxHHpxγγ Μid (Μ)ap (i)nput with (d)is fucntion: ? =pxHH (H is current element) if H = lowercase(H) &γ._pXiS and set γ to the uppercase entity in the reversed string pxγ lowercase γ γ else, return γ ``` [Answer] # [Perl 6](http://perl6.org), 29 bytes ``` $_=get;put .flip.samecase($_) ``` [Answer] # C#, ~~86~~ 85 bytes ``` s=>string.Concat(s.Reverse().Select((c,i)=>s[i]>96?char.ToLower(c):char.ToUpper(c))); ``` A C# lambda where the input and the output is a string. You can try it on [.NetFiddle](https://dotnetfiddle.net/0NjPq2). --- ~~I am struggling to understand why I cant achieve to convert `char.ToLower(c)` to `c+32`. I hope to fix it!~~ 12 bytes saved thanks to @PeterTaylor (`c|32` to add 32 to the ascii value of `c` and `c&~32` to substract 32). The result would be 72 bytes (but can fail on non alpha char). ``` s=>string.Join("",s.Reverse().Select((c,i)=>(char)(s[i]>96?c|32:c&~32))); ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `r`, ~~9~~ 2 bytes ``` Ṙ• ``` [Try it online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwi4bmY4oCiIiwiIiwiSGVsbG8iXQ==) [Answer] # [Julia 1.0](http://julialang.org/), ~~73, 65~~ 64 bytes ``` !s=prod(titlecase(s[end-i+1]^2)[2-('@'<s[i]<'[')] for i=keys(s)) ``` [Try it online!](https://tio.run/##NcqxDsIgEADQ3a@44gDE1qSd26SDg4uDcSSYEIvl9ATTw6hfj5NvfrcXoWs/pVQ8PJc0qYyZ/MWxV2x8nBrctPbcadM1So6yZ4O2l0ZqC9e0AA53/2XFWpeRQ3pDJfaeKNVwwCniHLJjAWs4uRxmjDt8QJ2IfFj9@/Yoyg8 "Julia 1.0 – Try It Online") -9 MarcMush [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 10 bytes ``` ŒlðUŒuT}¦n ``` [Try it online!](https://tio.run/##y0rNyan8///opJzDG0KPTioNqT20LO////8eQPF8HQXfzJS8zPSMksRiAA "Jelly – Try It Online") Did I say this was extremely golfable by someone who understands `¦`? Turns out it's just understanding anything at all about chaining in general. ``` Œl Lowercase the input, U reverse it, Œu then uppercase it T}¦ at indices where ð n the lowercase input doesn't equal the original input. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 139 bytes ``` #define B v[c+~i] #define C(x,y)isupper(x)?toupper(y):tolower(y) i,t,c;f(char*v){for(c=strlen(v);i<c/2;i++)t=C(B,v[i]),v[i]=C(v[i],B),B=t;} ``` [Try it online!](https://tio.run/##XY7NasMwEITveoqFXKRYbWmPVdyCc8kb9GB8cPXjLCiSkWUlIaSv7spOA6F7mJ35GJaVT52U07RS2qDTUEGqZfGDDbmTLT3xM8Nh7Hsd6Il9Rn@zZ/YevfXHxRLkkUthqNy3YZ3YxfhAZTnEYLWjiQncyJc3gUXBYrmlFU81NmzRHOfFK8arMorrtEIn7ag0bIaoLH4/7z/IIwvouv9MoZ8RugiHFh2dTRs6yWF@CNbZp7ph5EIgz43lS1BCVjX2dCm8NkyQpWFo5vfQj3F4zCZo/ZevME07ba2HLx@s@gU "C (gcc) – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), ~~114~~ ~~92~~ 78 bytes ``` ~x=(b=reverse(lowercase(x));prod(i->b[i]-32('@'<x[i]<'['<b[i]-5<'v'),keys(b))) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/v67CViPJtii1LLWoOFUjJ788tSg5Eciq0NS0LijKT9HI1LVLis6M1TU20lB3ULepALJt1KPVbcCCpjbqZeqaOtmplcUaSZqamv8dijPyyxXqlDxSc3LydRR8M1PyMtMzShKLlbhgUnqBCHZilWMUgucIBA7RCdVK/wE "Julia 1.0 – Try It Online") * -22 bytes thanks to amelies: use `prod` * -10 bytes thanks to MarcMush: avoid `uppercase` and `isuppercase` * -4 bytes thanks to MarcMush: use `keys(b)` instead of `1:length(b)` [Answer] # PHP, 128 bytes ``` $s=$argv[1];$l=strrev($s);for($i=0;$i<strlen($s);++$i){echo(strtolower($s[$i])!==$s[$i]?strtoupper($l[$i]):strtolower($l[$i]));} ``` I may attempt to optimize this further but I'll just leave it as is for now. [Answer] # Octave, ~~51~~ 50 bytes ~~`@(s)merge(isupper(s),b=flip(toupper(s)),tolower(b))`~~ ``` @(s)merge(s>64&s<91,b=flip(toupper(s)),tolower(b)) ``` ]
[Question] [ [Inspiration](https://codegolf.stackexchange.com/q/59299/43319). ### Task Reverse runs of odd numbers in a given list of 2 to 215 non-negative integers. ### Examples `0 1` → `0 1` `1 3` → `3 1` `1 2 3` → `1 2 3` `1 3 2` → `3 1 2` `10 7 9 6 8 9` → `10 9 7 6 8 9` `23 12 32 23 25 27` → `23 12 32 27 25 23` `123 123 345 0 1 9` → `345 123 123 0 9 1` [Answer] # Python 2, ~~75~~ ~~68~~ 63 bytes 5 bytes thanks to Dennis. And I have [outgolfed Dennis](https://codegolf.stackexchange.com/a/84352/48934). Credits to [Byeonggon Lee](https://codegolf.stackexchange.com/a/84350/48934) for the core of the algorithm. ``` o=t=[] for i in input():o+=~i%2*(t+[i]);t=i%2*([i]+t) print o+t ``` [Ideone it!](http://ideone.com/YOj0Hk) Old version: [75 bytes](http://ideone.com/6POOe6) [Answer] # APL, ~~21~~ 20 bytes ``` {∊⌽¨⍵⊂⍨e⍲¯1↓0,e←2|⍵} ``` [Try it](http://tryapl.org/?a=%7B%u220A%u233D%A8%u2375%u2282%u2368e%u2372%AF1%u21930%2Ce%u21902%7C%u2375%7D2%201%203%205%202%204%206%207%205%201&run) || [All test cases](http://tryapl.org/?a=%u236A%20%7B%u220A%u233D%A8%u2375%u2282%u2368e%u2372%AF1%u21930%2Ce%u21902%7C%u2375%7D%A8%280%201%29%281%203%29%281%202%203%29%281%203%202%29%2810%207%209%206%208%209%29%2823%2012%2032%2023%2025%2027%29%28123%20123%20345%200%201%209%29&run) Explanation: ``` 2|⍵ Select all the odd numbers e← Save that to e 0, Append a 0 ¯1↓ Delete the last element e⍲ NAND it with the original list of odd numbers ⍵⊂⍨ Partition the list: (even)(even)(odd odd odd)(even) ⌽¨ Reverse each partition ∊ Flatten the list ``` *Edit: Saved a `~` thanks to De Morgan's laws* [Answer] # Haskell, ~~46~~ 44 bytes ``` h%p|(l,r)<-span(odd.(h*))p=l++h:r foldr(%)[] ``` Thanks to @xnor for recognizing a fold and saving two bytes. [Answer] # Python 2, ~~79~~ ~~75~~ 73 bytes ``` def f(x): i=j=0 for n in x+[0]: if~n%2:x[i:j]=x[i:j][::-1];i=j+1 j+=1 ``` This is a function that modifies its argument in place. Second indentation level is a tabulator. Test it on [Ideone](http://ideone.com/wsu6KO). [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḃ¬ðœpUżx@F ``` [Try it online!](http://jelly.tryitonline.net/#code=4biCwqzDsMWTcFXFvHhARg&input=&args=WzEyMywgMTIzLCAzNDUsIDAsIDEsIDld) or [verify all test cases](http://jelly.tryitonline.net/#code=4biCwqzDsMWTcFXFvHhARgrDh-KCrEc&input=&args=WzAsIDFdLCBbMSwgM10sIFsxLCAyLCAzXSwgWzEsIDMsIDJdLCBbMTAsIDcsIDksIDYsIDgsIDldLCBbMjMsIDEyLCAzMiwgMjMsIDI1LCAyN10sIFsxMjMsIDEyMywgMzQ1LCAwLCAxLCA5XQ). ### How it works ``` Ḃ¬ðœpUżx@F Main link. Argument: A (array) Ḃ Bit; return the parity bit of each integer in A. ¬ Logical NOT; turn even integers into 1's, odds into 0's. ð Begin a new, dyadic link. Left argument: B (array of Booleans). Right argument: A œp Partition; split A at 1's in B. U Upend; reverse each resulting chunk of odd numbers. x@ Repeat (swapped); keep only numbers in A that correspond to a 1 in B. ż Zipwith; interleave the reversed runs of odd integers (result to the left) and the flat array of even integers (result to the right). F Flatten the resulting array of pairs. ``` [Answer] # Python 2, 78 75 bytes ``` def r(l): def k(n):o=~n%2<<99;k.i+=o*2-1;return k.i-o k.i=0;l.sort(key=k) ``` Super hacky :) [Answer] ## Python3, 96 bytes Saved a lot of bytes thanks to Leaky Nun! ``` o=l=[] for c in input().split(): if int(c)%2:l=[c]+l else:o+=l+[c];l=[] print(" ".join(o+l)) ``` [Answer] # C, 107 bytes ``` i;b[65536];f(){for(;i;)printf("%d ",b[--i]);}main(n){for(;~scanf("%d",&n);)n%2||f(),b[i++]=n,n%2||f();f();} ``` [Answer] # Pyth, 14 bytes ``` s_McQshMBx0%R2 %R2Q Take all elements of the input list modulo 2 x0 Get the indices of all 0s hMB Make a list of these indices and a list of these indices plus 1 s Concatenate them cQ Chop the input list at all those positions _M Reverse all resulting sublists s Concatenate them ``` [Test cases](https://pyth.herokuapp.com/?code=s_McQshMBx0%25R2&input=%5B10%2C7%2C9%2C6%2C8%2C9%5D&test_suite=1&test_suite_input=%5B0%2C1%5D%0A%5B1%2C3%5D%0A%5B1%2C2%2C3%5D%0A%5B1%2C3%2C2%5D%0A%5B10%2C7%2C9%2C6%2C8%2C9%5D%0A%5B23%2C12%2C32%2C23%2C25%2C27%5D%0A%5B123%2C123%2C345%2C0%2C1%2C9%5D) [Answer] # [MATL](https://github.com/lmendo/MATL), 20 bytes ``` TiodgvYsG8XQ!"@gto?P ``` Input is a column array, using `;` as separator. [**Try it online!**](http://matl.tryitonline.net/#code=VGlvZGd2WXNHOFhRISJAZ3RvP1A&input=WzEyMzsxMjM7MzQ1OzA7MTs5XQ) ### Explanation Consider as an example the input array `[1;2;3;5;7;4;6;7;9]`. The first part of the code, `Tiodgv`, converts this array into `[1;1;1;0;0;1;0;1;0]`, where `1` indicates a *change of parity*. (Specifically, the code obtains the parity of each entry of the input array, computes consecutive differences, converts nonzero values to `1`, and prepends a `1`.) Then `Ys` computes the *cumulative sum*, giving `[1;2;3;3;3;4;4;5;5]`. Each of these numbers will be used as a *label*, based on which the elements of the input will be *grouped*. This is done by `G8XQ!`, which splits the input array into a cell array containing the groups. In this case it gives `{[1] [2] [3;5;7] [4;6] [7;9]}`. The rest of the code *iterates* (`"`) on the cell array. Each constituent numeric array is pushed with `@g`. `to` makes a copy and *computes its parity*. If (`?`) the result is truthy, i.e. the array contents are odd, the array is *flipped* (`P`). The stack is *implicitly displayed* at the end. Each numeric vertical array is displayed, giving a list of numbers separated by newlines. [Answer] # [Desmos](https://desmos.com/calculator), 167 bytes ``` k=mod(l,2) K=l.length a=[K...1] L=a[k[a]=1] g(q)=∑_{n=1}^{[1...q.length]}q[n] A=g(join(1,sign(L-L[2...]-1))) f(l)=l[\{k>0:\sort(L,A.\max+1-A)[g(k)],k\}+[1...K](1-k)] ``` Hooooly crap, this was pretty challenging to do in Desmos given its limited list functionalities, but after lots of puzzling and scratched ideas, I finally managed to pull together something that actually works. [Try It On Desmos!](https://www.desmos.com/calculator/lcifzpsj5w) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/ouholqommb) [Answer] # [Desmos](https://desmos.com/calculator), ~~94~~ 93 bytes ``` g(M,j)=j-max([1...j]0^{mod(M,2)}) f(L)=L[[i+g(L[n...1],n+1-i)-g(L,i)fori=[1...n]]] n=L.length ``` [Try it on Desmos!](https://www.desmos.com/calculator/qhrwpidzr0) \*-1 byte thanks to [@AidenChow](https://codegolf.stackexchange.com/users/96039/aiden-chow) (remove space after `for`) ## How it works `g(M,j)` gives the difference between `j` and the greatest index less than (or equal to) `j` of an even entry in `M`. For example, `g([0,2,4,1,3,5,7,6,8],6) = 3` because the 6th element in the list is 5, and the last even entry before it is 4, which is 3 elements earlier. `f(L)` is the solution to the challenge. It's of the form `L[[h(i)for i=[1...n]]]`, which is a list indexing: `h(i)` gives the index of the value in `L` that should be at index `i` in the result list. The main difficulty lies in `h(i)`, defined as `h(i) = i+g(L[n...1],n+1-i)-g(L,i)`. Note that `g(M,j) = 0` whenever `M[j]` is even, so `h(i)=i` if `L[i]` is even (this corresponds to even entries not moving) since `L[n...1][n+1-i]=L[i]=even` If `L[i]` is odd then we have a more complicated story: `g(L,i)` gives the distance to the element before the start of the odd run, and `g(L[n...1],n+1-i)` gives the distance to the element after the end of the odd run. Then `g(L[n...1],n+1-i)-g(L,i)` says how much closer the element is to the end of the run than the start of the run. For example, for `L=[0,2,4,1,3,5,7,6,8]` and `i=6`, this difference is `-1`, so `L[6]` has to move 1 element to the left, to where the `3` is currently. In general regarding the difference `g(L[n...1],n+1-i)-g(L,i)`: * if the difference is positive, then the element is closer to the left than the right, and it needs to move right by the value of the difference * if the difference is negative, then the element is closer to the right than the left, and it needs to move left by the negative of the difference * if the difference is zero, then the element is at the center of an odd-length run, so it doesn't need to move at all. [Answer] # Clojure, 86 bytes ``` #(flatten(reduce(fn[a b](if(odd? b)(conj(pop a)(conj[b](last a)))(conj a b[])))[[]]%)) ``` Here is the ungolfed version ``` #(flatten ; removes all empty vectors and flattens odd sequences (reduce (fn[a b] (if(odd? b) ; if we encounter odd number in the seq (conj(pop a)(conj[b](last a))) ; return all elements but last and the element we encountered plus the last element of current result (conj a b[])) ; else just add the even number and the empty vector ) [[]] ; starting vector, we need to have vector inside of vector if the sequence starts with odd number % ; anonymous function arg ) ) ``` Basically it goes through the input sequence and if it encounters even number it adds the number and the empty vector otherwise if it's an odd number it replaces the last element with this number plus what was in the last element. For example for this seq `2 4 6 1 3 7 2` it goes like this: * `[]<=2` * `[2 []]<=4` * `[2 [] 4 []]<=6` * `[2 [] 4 [] 6 []]<=1` * `[2 [] 4 [] 6 [1 []]]<=3` * `[2 [] 4 [] 6 [3 [1 []]]]<=7` * `[2 [] 4 [] 6 [7 [3 [1 []]]]]<=2` * `[2 [] 4 [] 6 [7 [3 [1 []]]] 2 []]` And then flattening this vector gives the correct output. You can see it online here: <https://ideone.com/d2LLEC> [Answer] # [J](http://jsoftware.com), ~~33~~ ~~31~~ 30 bytes ``` [:;]<@(A.~2-@|{.);.1~1,2|2-/\] ``` ## Usage ``` f =: [:;]<@(A.~2-@|{.);.1~1,2|2-/\] f 0 1 0 1 f 1 3 3 1 f 1 2 3 1 2 3 f 1 3 2 3 1 2 f 10 7 9 6 8 9 10 9 7 6 8 9 f 23 12 32 23 25 27 23 12 32 27 25 23 f 123 123 345 0 1 9 345 123 123 0 9 1 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` ṁ↔ġ¤&%2 ``` [Try it online!](https://tio.run/##yygtzv7//@HOxkdtU44sPLRETdXo////0YYGOuY6ljpmOhZA0hTINtYxNIgFAA "Husk – Try It Online") ## Explanation ``` ṁ↔ġ¤&%2 Implicit input, a list of integers. ġ Group by equality predicate: ¤ %2 Arguments modulo 2 & are both truthy. ṁ Map and concatenate ↔ reversing. ``` [Answer] # C#, ~~179~~ ~~178~~ 177 bytes ``` s=>{var o=new List<int>();var l=new Stack<int>();foreach(var n in s.Split(' ').Select(int.Parse)){if(n%2>0)l.Push(n);else{o.AddRange(l);o.Add(n);l.Clear();}}return o.Concat(l);} ``` I use a C# lambda. You can try it on [.NETFiddle](https://dotnetfiddle.net/rCdWDK). The code less minify: ``` s => { var o=new List<int>();var l=new Stack<int>(); foreach (var n in s.Split(' ').Select(int.Parse)) { if (n%2>0) l.Push(n); else { o.AddRange(l); o.Add(n); l.Clear(); } } return o.Concat(l); }; ``` Kudos to [Byeonggon Lee](https://codegolf.stackexchange.com/a/84350/15214) for the original algorithm. [Answer] # JavaScript (ES6) ~~70~~ 66 bytes **Edit** 4 bytes saved thx @Neil ``` a=>[...a,[]].map(x=>x&1?o=[x,...o]:r=r.concat(o,x,o=[]),r=o=[])&&r ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 51 bytes ``` ->l{l.chunk(&:odd?).flat_map{|i,j|i ?j.reverse: j}} ``` [Try it online!](https://tio.run/##jZHdToNAEIXv9ynGmIAmK2mhipJgX8I7JIbCCrviQvhpNKXPjrMslBJ7UZKFyTfnnBmgane/feq/9w@v@SG34qyVX3eGVyTJ9t76zKPm4zsqDx2nouOwFVbF9qyqmQfieOxv4S1jsI8qHjW8kDXxdyzlklyRZRinrK7DrCs8N2oB72T750EsLy698PhMJoQEBCAIVhTWIQX9DOnA1hQcxZwls0c8lWdqJJNBlVMHQ10KLxSeKDxjMbhXA3FnOKpt5VbBeFRtP@JxlWXRccfOPF@38eZssIHxagk9bCCzQI/GdyKhxaI4g6QA/EQgOkwqKy4bMLks28YDvEwF26YGbomCSzA10bK00KIzWRrw8IKS/ZQsbljizUqxkCEh@Ef6Pw "Ruby – Try It Online") Some slight variations: ``` ->l{l.chunk(&:odd?).flat_map{|i,j|i&&j.reverse||j}} ->l{l.chunk(&:odd?).flat_map{|i,j|!i ?j:j.reverse}} ->l{l.chunk(&:even?).flat_map{|i,j|i ?j:j.reverse}} ``` ### Ruby 2.7, 48 bytes ``` ->l{l.chunk{_1%2}.flat_map{_1>0?_2.reverse: _2}} ``` Unsupported by TIO :( [Answer] # Pyth, ~~29~~ 28 bytes ``` JYVQ=+J*%hN2+YN=Y*%N2+NY;+JY ``` [Test suite.](http://pyth.herokuapp.com/?code=JYVQ%3D%2BJ%2a%25hN2%2BYN%3DY%2a%25N2%2BNY%3B%2BJY&test_suite=1&test_suite_input=%5B0%2C1%5D%0A%5B1%2C3%5D%0A%5B1%2C2%2C3%5D%0A%5B1%2C3%2C2%5D%0A%5B10%2C7%2C9%2C6%2C8%2C9%5D%0A%5B23%2C12%2C32%2C23%2C25%2C27%5D%0A%5B123%2C123%2C345%2C0%2C1%2C9%5D&debug=0) Direct translation of [my python answer](https://codegolf.stackexchange.com/a/84353/48934) (when has translating from python to pyth become a good idea?) [Answer] # TSQL 118 bytes ``` DECLARE @ TABLE(i int identity, v int) INSERT @ values(123),(123),(345),(0),(1),(9) SELECT v FROM(SELECT sum((v+1)%2)over(order by i)x,*FROM @)z ORDER BY x,IIF(v%2=1,max(i)over(partition by x),i),i desc ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/507955/reverse-odd-sequences)** [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~15~~ 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437 ``` Çⁿ╜"}☻≥º╚( ``` [Try it online!](https://staxlang.xyz/#c=%C3%87%E2%81%BF%E2%95%9C%22%7D%E2%98%BB%E2%89%A5%C2%BA%E2%95%9A%28&i=%5B0%2C1%5D%0A%5B1%2C3%5D%0A%5B1%2C2%2C3%5D%0A%5B1%2C3%2C2%5D%0A%5B10%2C7%2C9%2C6%2C8%2C9%5D%0A%5B23%2C12%2C32%2C23%2C25%2C27%5D%0A%5B123%2C123%2C345%2C0%2C1%2C9%5D&a=1&m=2) **Tied Jelly!** So sad that packing only saved one byte. Unpacked version with 11 bytes: ``` {|e_^*}/Frm ``` ## Explanation `{|e_^*}` is a block that maps all even numbers `n` to `n+1`, and all odd numbers `n` to `0`. ``` {|e_^*}/Frm { }/ Group array by same value from block |e 1 if the element is even, 0 if odd. _^ Get another copy of the current element and increment by 1 * Multiply them F For each group execute the rest of the program r Reverse the group m Print elements from the group, one element per line. ``` [Answer] ## [Perl 5](https://www.perl.org/) with `-p`, 42 bytes ``` map{$_%2?$\=$_.$\:print$\.$_,$\=""}$_,<>}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saBaJV7VyF4lxlYlXk8lxqqgKDOvRCVGTyVeByimpFQLZNjY1Vb//29oZMwFwsYmplwGXIZcllz/8gtKMvPziv/rFgAA "Perl 5 – Try It Online") [Answer] # [J](http://jsoftware.com/), 27 bytes ``` [:;]<@(|.^:{.);.1~1,2|2-/\] ``` [Try it online!](https://tio.run/##RY6xDsIwDET3fMWJpVRqQ@NQ0qQgISExMbFCGTvwC1T99WAnijrY8rvzWf7GnUY14xJQNegQuFqN2/Nxj68wTufrftGf8NP1qM1qGlqoPbynWEcAMy8bJZXAwCq7ATHmXlyQ@Nyz0MHB44QBXjF4xgzJJl7lMMlAPcipTXFJKYeTbmGPvfzDeZmKKnfNHw "J – Try It Online") A minor improvement over [miles' J answer](https://codegolf.stackexchange.com/a/84357/78410). ### How it works ``` [:;]<@(|.^:{.);.1~1,2|2-/\] NB. Input: an integer vector V 1,2|2-/\] NB. Pairwise difference modulo 2 and prepend 1 NB. giving starting positions for same-parity runs ] ;.1~ NB. Cut V at ones of ^ as the starting point and (|.^:{.) NB. reverse each chunk (head of the chunk) times NB. (effectively, reverse odd chunks only) <@ NB. and enclose it [:; NB. Finally, flatten the result ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 53 bytes ``` a=>a.map((c,k)=>o.splice(n=c&1?+n:k+1,0,c),o=n=[])&&o ``` [Try it online!](https://tio.run/##DcY7DsIwDADQq2SKbNVEzcJPctl6iapDZCJUGuyIIK4feNN7pm9q8t7q56B2z33mnnhK4ZUqgNCOPFlotWySQVl8vA163YdIIwmSsfKyovfWxbRZyaHYA2ZY4kjuRO5C7kju/M@K2H8 "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 54 bytes ``` a=>a.map((c,k)=>o.splice(n=c&1?n:k+1,0,c),o=[],n=0)&&o ``` [Try it online!](https://tio.run/##DcY7DsMgDADQqzAho7oIlv4kp1suEWVALqrSUBuFKtcnfdP7pD013pb6O4u@ch@pJxqS/6YKwLg6GtS3WhbOIMQ2PuWxniIGZIdK04xCwVmrnVWaluyLvmGEKQY0VzR3NBc0t39m5/oB "JavaScript (Node.js) – Try It Online") [Answer] # [R](https://www.r-project.org/), 69 bytes ``` v=scan();ifelse(o<-v%%2,v[rep(2*cumsum(r<-rle(o)$l)-r+1,r)-seq(v)],v) ``` [Try it online!](https://tio.run/##Dck7CoAwDADQPeewkGg7GBEH60nEQaSCUH8p5vq124MnOeuUtvVCGo89xBTw9k6NYauzhAe53r4zfSeKdxLLUhXJSdNaIZfCi0qLVcrcQcvQMRRwDzxA/gE "R – Try It Online") Ungolfed, commented version: ``` o=v%%2 # get the odd numbers in the list r=rle(o)$l # find the run lengths of odd/even numbers # reverse the indices of all the runs: e=cumsum(r) # the indices of the ends of each run ie=rep(e,r) # for each index in v, the index of the end of its run is=rep(e-r+1,r) # for each index in v, the index of the start of its run irev=is+(ie-seq(v)) # reverses all runs # the above 4 steps can be combined as: irev=rep(2*cumsum(r)-r+1,r)-seq(v) # so: use the reversed indices for odd numbers, and leave the even numbers unchanged ifelse(o,v[irev],v) ``` [Answer] # [Clojure](https://clojure.org/), 66 bytes ``` #(mapcat(fn[x](if(some odd? x)(reverse x)x))(partition-by odd? %)) ``` [Try it online!](https://tio.run/##TY9NDoIwEIX3PcVLjMl0YQJFReLCgzQsUNoEoxQLGtyZeFMvggMEcdHk/Xyddk4Xd75701FuLGy3oGtWnbKGbKnblApLtbsauDw/oJXkzcP42rBspaQq803RFK5cHZ8jspSyk4JyV5sbdAstdIAw/bzeez4shQ4RTT4avZqTwQwM1B8FxVmAGAm22CH54QEn8ZgJrZjk6wos1AYqnrC5iIeif2HIIkTrDfhb88g@mMp@eijSFFT5omwuJcjy6rzjFw "Clojure – Try It Online") [Answer] # [Factor](https://factorcode.org) + `grouping.extras`, 62 bytes ``` [ [ odd? ] group-by [ last2 swap [ reverse ] when ] map-flat ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZHBTgIxEIbjdZ_i5wF2A11xQRM9Gi9ejCfCoS6z0Fi2tZ0VCeHuO3jhgu-kT2N3FwgE59CZ-f-vM2n69V3InI3b_F58Pj89PN5fQ3pvco-55BmmzlRWldOEPthJD09vFZU5ebySK0nDOmJeWqdKRm7mVmlyScVKK1aBOkjsiBLrjJVTycqUSS61jqkoKGfcRNEqQogVuuhhjdPo1OrO7yH9x0-PfHFGdFr1aII4I9Ka2RNdZBjiCoNwrg8zuqHLWnUHinArDBZ1IfoQWaA7R2rWqIfFjZEivew3zxw2dN3tnXpDL1pvKy7iwc_tCCOYyeQO4_Yf4pdlULT0LOAX0obG0Ts5T4FYzKgMaS5tXGjJGLdTtkFA0tabTZv_AA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .γÈN>*}í˜ ``` [Try it online](https://tio.run/##yy9OTMpM/f9f79zmwx1@dlq1h9eenvP/f7ShkbEOCBubmOoY6BjpGOpYxgIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/vXObD3f42WnVHl57es5/nf/R0QY6hrE60YY6xmDSCEob6xiBaAMdcx1LHTMdCx1LINfIWMcQqMBIB8gwMtUxMgcpAQsa6xibmOoAjQKqiwUA). **Explanation:** ``` .γ } # Adjacent group the (implicit) input-list by: È # Check if the value is even (1 if even; 0 if odd) N>* # Multiply it by the 1-based index # (adjacent odd values will be grouped together, and every even # value is in its own separated group) í # After the adjacent group-by: reverse each inner list ˜ # Flatten the list of lists # (after which the result is output implicitly) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` λ&›₂¥*;ḊRf ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBUCIsIiIsIs67JuKAuuKCgsKlKjvhuIpSZiIsIiIsIlswLDFdXG5bMSwzXVxuWzEsMiwzXVxuWzEsMywyXVxuWzEwLDcsOSw2LDgsOV1cblsyMywxMiwzMiwyMywyNSwyN11cblsxMjMsMTIzLDM0NSwwLDEsOV0iXQ==) Port of 05AB1E. Another 10-byter that I produced independently: `⁽₂Ḋƛh∷ßṘ;f` ]
[Question] [ **Note: the first half of this challenge comes from Martin Ender's previous challenge, [Visualize Bit Weaving](https://codegolf.stackexchange.com/questions/83899/visualise-bit-weaving).** The esoteric programming language [evil](http://esolangs.org/wiki/Evil) has an interesting operation on byte values which it calls "weaving". It is essentially a permutation of the eight bits of the byte (it doesn't matter which end we start counting from, as the pattern is symmetric): * Bit 0 is moved to bit 2 * Bit 1 is moved to bit 0 * Bit 2 is moved to bit 4 * Bit 3 is moved to bit 1 * Bit 4 is moved to bit 6 * Bit 5 is moved to bit 3 * Bit 6 is moved to bit 7 * Bit 7 is moved to bit 5 For convenience, here are three other representations of the permutation. As a cycle: ``` (02467531) ``` As a mapping: ``` 57361402 -> 76543210 -> 64725031 ``` And as a list of pairs of the mapping: ``` [[0,2], [1,0], [2,4], [3,1], [4,6], [5,3], [6,7], [7,5]] ``` After `8` weavings, the byte is essentially reset. For example, weaving the number `10011101` (which is `157` in base 10) will produce `01110110` (which is `118` in base 10). # Input There are only `256` valid inputs, namely all the integers between `0` and `255` inclusive. That may be taken in any base, but it must be consistent and you must specify it if the base you choose is not base ten. You may **not** zero-pad your inputs. # Output You should output the result of the bit weaving, in any base, which must also be consistent and specified if not base ten. You **may** zero-pad your outputs. --- Related: [Visualize Bit Weaving](https://codegolf.stackexchange.com/q/83899/34718) [Answer] # Python 2.7, 44 -> 36 bytes ``` lambda x:x/4&42|x*2&128|x*4&84|x/2&1 ``` [Answer] # Evil, 3 characters ``` rew ``` [Try it online!](http://evil.tryitonline.net/#code=cmV3&input=Pw) Input is in base 256, (e.g. ASCII), e.g. to enter the digit 63, enter ASCII 63 which is `?`. Explanation: ``` r #Read a character e #Weave it w #Display it ``` This *so* feels like cheating. [Answer] ## CJam, ~~15~~ 12 bytes *Thanks to FryAmTheEggman for saving 3 bytes.* ``` l8Te[m!6532= ``` Input in base 2. Output also in base 2, padded to 8 bits with zeros. [Test it here.](http://cjam.aditsu.net/#code=l8Te%5Bm!6532%3D&input=10011101) ### Explanation ``` l e# Read the input. 8Te[ e# Left-pad it to 8 elements with zeros. m! e# Generate all permutations (with duplicates, i.e. treating equal elements e# in different positions distinctly). 6532= e# Select the 6533rd, which happens to permute the elements like [1 3 0 5 2 7 4 6]. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 14 bytes ``` &8B[2K1B3D5C]) ``` Input is in decimal. Output is zero-padded binary. [**Try it online!**](http://matl.tryitonline.net/#code=JjhCWzJLMUIzRDVDXSk&input=MTU3) ### Explanation ``` &8B % Take input number implicitly. Convert to binary array with 8 digits [2K1B3D5C] % Push array [2 4 1 6 3 8 5 7] ) % Index first array with second array. Implicitly display ``` [Answer] # Jelly, 11 bytes ``` +⁹BḊŒ!6533ị ``` Translation of Martin’s CJam answer. [Try it here.](http://jelly.tryitonline.net/#code=fOKBuULhuIrFkiE2NTMz4buL&input=&args=MTU3) ``` +⁹BḊ Translate (x+256) to binary and chop off the MSB. This essentially zero-pads the list to 8 bits. Œ! Generate all permutations of this list. 6533ị Index the 6533rd one. ``` [Answer] ## JavaScript (ES6), 30 bytes ``` f=n=>n*4&84|n*2&128|n/2&1|n/4&42 ``` [Answer] # C (unsafe macro), 39 bytes ``` #define w(v)v*4&84|v*2&128|v/2&1|v/4&42 ``` # C (function), 41 bytes ``` w(v){return v*4&84|v*2&128|v/2&1|v/4&42;} ``` # C (full program), 59 bytes ``` main(v){scanf("%d",&v);return v*4&84|v*2&128|v/2&1|v/4&42;} ``` (returns via exit code, so invoke with `echo "157" | ./weave;echo $?`) # C (standards-compliant full program), 86 bytes ``` #include<stdio.h> int main(){int v;scanf("%d",&v);return v*4&84|v*2&128|v/2&1|v/4&42;} ``` # C (standards-compliant full program with no compiler warnings), 95 bytes ``` #include<stdio.h> int main(){int v;scanf("%d",&v);return (v*4&84)|(v*2&128)|(v/2&1)|(v/4&42);} ``` # C (standards-compliant full program with no compiler warnings which can read from arguments or stdin and includes error/range checking), 262 bytes ``` #include<stdio.h> #include<stdlib.h> #include<unistd.h> int main(int v,char**p){v=v<2?isatty(0)&&puts("Value?"),scanf("%d",&v)?v:-1:strtol(p[1],p,10);exit(*p==p[1]||v&255^v?fprintf(stderr,"Invalid value\n"):!printf("%d\n",(v*4&84)|(v*2&128)|(v/2&1)|(v/4&42)));} ``` ### Breakdown Pretty much the same as a lot of existing answers: bit-shift all the bits into place by using `<<2` (`*4`), `<<1` (`*2`), `>>1` (`/2`) and `>>2` (`/4`), then `|` it all together. The rest is nothing but different flavours of boiler-plate. [Answer] # x86 machine code, 20 bytes In hex: ``` 89C22455C1E002D0E0D1E880E2AAC0EA0211D0C3 ``` It's a procedure taking input and returning result via AL register ## Disassembly ``` 89 c2 mov edx,eax 24 55 and al,0x55 ;Clear odd bits c1 e0 02 shl eax,0x2 ;Shift left, bit 6 goes to AH... d0 e0 shl al,1 ;...and doesn't affected by this shift d1 e8 shr eax,1 ;Shift bits to their's target positions 80 e2 aa and dl,0xaa ;Clear even bits c0 ea 02 shr dl,0x2 ;Shift right, bit 1 goes to CF 11 d0 adc eax,edx ;EAX=EAX+EDX+CF c3 ret ``` [Answer] # J, 12 bytes ``` 6532 A._8&{. ``` Uses the permute builtin `A.` with permutation index `6532` which corresponds to the bit-weaving operation. ## Usage Input is a list of binary digits. Output is a zero-padded list of 8 binary digits. ``` f =: 6532 A._8&{. f 1 0 0 1 1 1 0 1 0 1 1 1 0 1 1 0 f 1 1 1 0 1 1 0 1 1 0 1 1 0 0 1 ``` ## Explanation ``` 6532 A._8&{. Input: s _8&{. Takes the list 8 values from the list, filling with zeros at the front if the length(s) is less than 8 6532 The permutation index for bit-weaving A. permute the list of digits by that index and return ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 39 bytes ``` +`^(?!.{8}) 0 (.)(.) $2$1 \B(.)(.) $2$1 ``` Input and output in base 2, output is left-padded. [Try it online!](http://retina.tryitonline.net/#code=K2BeKD8hLns4fSkKMAooLikoLikKJDIkMQpcQiguKSguKQokMiQx&input=MTAwMTExMDE) ## Explanation ``` +`^(?!.{8}) 0 ``` This just left-pads the input with zeros. The `+` indicates that this stage is repeated until the string stops changing. It matches the beginning of the string as long as there are less than 8 characters in it, and inserts a `0` in that position. Now for the actual permutation. The straight-forward solution is this: ``` (.)(.)(.)(.)(.)(.)(.)(.) $2$4$1$6$3$8$5$7 ``` However that's painfully long and redundant. I found a different formulation of the permutation that is much easier to implement in Retina (`X` represents a swap of adjacent bits): ``` 1 2 3 4 5 6 7 8 X X X X 2 1 4 3 6 5 8 7 X X X 2 4 1 6 3 8 5 7 ``` Now that's much easier to implement: ``` (.)(.) $2$1 ``` This simply matches two characters and swaps them. Since matches don't overlap, this swaps all four pairs. ``` \B(.)(.) $2$1 ``` Now we want to do the same thing again, but we want to skip the first character. The easiest way to do so is to require that the match *doesn't* start at a word boundary with `\B`. [Answer] # Mathematica, 34 bytes ``` PadLeft[#,8][[{2,4,1,6,3,8,5,7}]]& ``` Anonymous function. Takes a list of binary digits, and outputs a padded list of 8 binary digits. [Answer] ## PowerShell v2+, 34 bytes ``` ("{0:D8}"-f$args)[1,3,0,5,2,7,4,6] ``` Translation of @LegionMammal978's [answer](https://codegolf.stackexchange.com/a/84015/42963). Full program. Takes input via command-line argument as a binary number, outputs as a binary array, zero-padded. The `"{0:D8}"-f` portion uses [standard numeric format strings](https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx) to prepend `0` to the input `$args`. Since the `-f` operator supports taking an array as input, and we've explicitly said to use the first element `{0:`, we don't need to do the usual `$args[0]`. We encapsulate that string in parens, then index into it `[1,3,0,5,2,7,4,6]` with the weaving. The resultant array is left on the pipeline and output is implicit. ### Examples *(the default `.ToString()` for an array has the separator as ``n`, so that's why the output is newline separated here)* ``` PS C:\Tools\Scripts\golfing> .\golf-bit-weaving.ps1 10011101 0 1 1 1 0 1 1 0 PS C:\Tools\Scripts\golfing> .\golf-bit-weaving.ps1 1111 0 0 0 1 0 1 1 1 ``` [Answer] ## Matlab, ~~49~~ ~~48~~ 44 bytes ``` s=sprintf('%08s',input(''));s('24163857'-48) ``` Takes input as string of binary values. Output padded. 4 bytes saved thanks to @Luis Mendo. **Explanation:** ``` input('') -- takes input s=sprintf('%08s',...) -- pads with zeros to obtain 8 digits s('24163857'-48) -- takes positions [2 4 1 6 3 8 5 7] from s (48 is code for '0') ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 17 bytes ``` 8é0$7hd|òxplò2|@q ``` [Try it online!](http://v.tryitonline.net/#code=OMOpMCQ3aGR8w7J4cGzDsjJ8QHE&input=MTAwMTExMDE) This takes input and output in binary. Most of the byte count comes from padding it with 0's. If padding the input was allowed, we could just do: ``` òxplò2|@q ``` Thanks to [Martin's solution](https://codegolf.stackexchange.com/a/84044/31716) for the method of swapping characters, e.g: ``` 1 2 3 4 5 6 7 8 X X X X 2 1 4 3 6 5 8 7 X X X 2 4 1 6 3 8 5 7 ``` Explanation: ``` 8é0 "Insert 8 '0' characters $ "Move to the end of the current line 7h "Move 7 characters back d| "Delete until the first character ò ò "Recursively: xp "Swap 2 characters l "And move to the right 2| "Move to the second column @q "And repeat our last recursive command. ``` [Answer] ## 05AB1E, ~~14~~ 12 bytes ``` žz+b¦œ6532èJ ``` **Explanation** ``` žz+b¦ # convert to binary padded with 0's to 8 digits œ6532è # get the 6532th permutation of the binary number J # join and implicitly print ``` Input is in base 10. Output is in base 2. Borrows the permutation trick from [MartinEnder's CJam answer](https://codegolf.stackexchange.com/a/84011/47066) [Try it online](http://05ab1e.tryitonline.net/#code=xb56K2LCpsWTNjUzMsOoSg&input=MTU3) [Answer] # Pyth, 19 characters ``` s[@z1.it%2tzP%2z@z6 ``` Input and output are base 2. Far from a Pyth expert, but since no one else has answered with it yet I gave it a shot. Explanation: ``` s[ # combine the 3 parts to a collection and then join them @z1 # bit 1 goes to bit 0 .i # interleave the next two collections t%2tz # bits 3,5,7; t is used before z to offset the index by 1 P%2z # bits 0,2,4 @z6 # bit 6 goes to bit 7 ``` [Answer] ## [Labyrinth](https://github.com/m-ender/labyrinth), ~~27~~ 26 bytes ``` _1@ &,)}}}=}}=}}=}!{!!{{!" ``` Input and output in base 2. Output is padded. [Try it online!](http://labyrinth.tryitonline.net/#code=XzFACiYsKX19fT19fT19fT19IXshIXt7ISI&input=MTAwMTExMDE) [Answer] # [UGL](https://github.com/schas002/Unipants-Golfing-Language/blob/gh-pages/README.md), 50 bytes ``` cuuRir/r/r/r/r/r/r/%@@%@@%@@%@@@%@@%@@%@@@oooooooo ``` [Try it online!](http://schas002.github.io/Unipants-Golfing-Language/?code=Y3V1UmlyL3Ivci9yL3Ivci9yLyVAQCVAQCVAQCVAQEAlQEAlQEAlQEBAb29vb29vb28&input=MTU3) Repeatedly div-mod by 2, and then `%` swap and `@` roll to get them in the right order. Input in base-ten, output in base-two. [Answer] ## vi, 27 bytes ``` 8I0<ESC>$7hc0lxp<ESC>l"qd0xp3@q03@q ``` Where `<ESC>` represents the Escape character. I/O is in binary, output is padded. 24 bytes in vim: ``` 8I0<ESC>$7hd0xpqqlxpq2@q03@q ``` [Answer] ## Actually, 27 bytes ``` '08*+7~@tñiWi┐W13052746k♂└Σ ``` [Try it online!](http://actually.tryitonline.net/#code=JzA4Kis3fkB0w7FpV2nilJBXMTMwNTI3NDZr4pmC4pSUzqM&input=JzEn) This program does input and output as a binary string (output is zero-padded to 8 bits). Explanation: ``` '08*+7~@tñiWi┐W13052746k♂└Σ '08*+ prepend 8 zeroes 7~@t last 8 characters (a[:~7]) ñi enumerate, flatten Wi┐W for each (i, v) pair: push v to register i 13052746k push [1,3,0,5,2,7,4,6] (the permutation order, zero-indexed) ♂└ for each value: push the value in that register Σ concatenate the strings ``` [Answer] # JavaScript, 98 Bytes Input is taken in base-2 as a string, output is also base-2 as a string ``` n=>(n.length<8?n="0".repeat(8-n.length)+n:0,a="13052746",t=n,n.split``.map((e,i)=>t[a[i]]).join``) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) I/O as binary strings ``` ùT8 á g6532 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=czI&code=%2bVQ4IOEgZzY1MzI&footer=Vm4y&input=MTU3) - header & footer convert from and to decimal. ]
[Question] [ One of the most common standard tasks (especially when showcasing esoteric programming languages) is to implement a ["cat program"](http://esolangs.org/wiki/Cat): read all of STDIN and print it to STDOUT. While this is named after the Unix shell utility `cat` it is of course much less powerful than the real thing, which is normally used to print (and concatenate) several files read from disc. ### Task You should write a **full program** which reads the contents of the standard input stream and writes them verbatim to the standard output stream. If and only if your language does not support standard input and/or output streams (as understood in most languages), you may instead take these terms to mean their closest equivalent in your language (e.g. JavaScript's `prompt` and `alert`). These are the *only* admissible forms of I/O, as any other interface would largely change the nature of the task and make answers much less comparable. The output should contain exactly the input and *nothing else*. The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. **This also applies to trailing newlines.** If the input does not contain a trailing newline, the output shouldn't include one either! (The only exception being if your language absolutely always prints a trailing newline after execution.) Output to the standard error stream is ignored, so long as the standard output stream contains the expected output. In particular, this means your program can terminate with an error upon hitting the end of the stream (EOF), provided that doesn't pollute the standard output stream. *If you do this, I encourage you to add an error-free version to your answer as well (for reference).* As this is intended as a challenge within each language and not between languages, there are a few language specific rules: * If it is at all possible in your language to distinguish null bytes in the standard input stream from the EOF, your program must support null bytes like any other bytes (that is, they have to be written to the standard output stream as well). * If it is at all possible in your language to support an *arbitrary* infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. As an example `yes | tr -d \\n | ./my_cat` should print an infinite stream of `y`s. It is up to you how often you print and flush the standard output stream, but it must be guaranteed to happen after a finite amount of time, regardless of the stream (this means, in particular, that you cannot wait for a specific character like a linefeed before printing). Please add a note to your answer about the exact behaviour regarding null-bytes, infinite streams, and extraneous output. ### Additional rules * This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in *every* language. Therefore, no answer will be marked as accepted. * Submissions in most languages will be scored in *bytes* in an appropriate preexisting encoding, usually (but not necessarily) UTF-8. Some languages, like [Folders](http://esolangs.org/wiki/Folders), are a bit tricky to score. If in doubt, please ask on [Meta](http://meta.codegolf.stackexchange.com/). * Feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Also note that languages *do* have to fulfil [our usual criteria for programming languages](http://meta.codegolf.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). * If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language. * Unless they have been overruled earlier, all standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply, including the <http://meta.codegolf.stackexchange.com/q/1061>. As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code. ### Catalogue The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. 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 snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution 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> <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> <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><script>var QUESTION_ID = 62230; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 8478; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] # [APL](http://goo.gl/9KrKoM), 6 bytes ``` ⎕←⍞ →1 ``` This has worked in all APLs since the beginning of time. `⍞` wait for input `⎕←` Output that `→1` go to line 1 [Answer] ## [Wat](https://github.com/theksp25/Wat), 6 + 1 = 7 [bytes](https://github.com/theksp25/Wat/wiki/Codepage) ``` åó#ÐÑÅ ``` (This code don't have any rapport with DNA) Explanation: ``` åó#ÐÑÅ å Read a character ó Duplicate the top of the stack # Skip the next character Ð End the program Ñ If the top of the stack is 0, go backward (execute Ð and end the program), otherwise go forward Å Print the character on the top of the stack After, the IP wrap and the line is reexecuted ``` [Answer] # [Omam](https://esolangs.org/wiki/Omam), 137 bytes ``` the screams all sound the same though the truth may vary don't listen to a word i say the screams all sound the same this ship will carry ``` Note that I haven't copied it. In fact, I added this code there today. [Answer] # [Tellurium](https://m654z.github.io/Tellurium), 2 bytes ``` i^ ``` Pretty simple, eh? What it does is get input from the user using the `i` command, and stores it in the tape in the currently selected item (in the code above, it's 0, the default). After that, it prints the currently selected item's value using the `^` command. (whatever the user input). [Answer] # Apps Script + Google Sheets, 29 bytes ### Script ``` function Q(s){return s} ``` ### Sheet ``` =q(B1) ``` Cell B1 is the input. [Answer] # J, 14 bytes ``` stdout]stdin'' ``` Reads the entire input from stdin until EOF is reached and store it as an array of characters. Then output all of it to stdout. This will work when saved as a script to be run using `jconsole`, where scripts are programs for interpreted languages. [Answer] # [Fith](https://github.com/nazek42/fith), 7 bytes ``` read \. ``` `read` gets input from STDIN. The language cannot handle infinite streams. `\.` prints the string on top of the stack without a trailing newline. [Answer] ## [BruhScript](https://github.com/tuxcrafting/BruhScript), 22 bytes Source: ``` ↺₀1Λ₀⍈+⍰' ∇ ``` Encoded version hexdump: ``` 0000000: 0099 009a 003a 0087 009a 008f 0051 008e .....:.......Q.. 0000010: 0061 0000 0069 .a...i ``` Explanation: ``` ↺ While loop. Take two niladic functions as arguments. ₀1Λ A function that always return 1 ₀⍈+⍰'<LF>∇ `'<c>` is a shorthand for «<c>», so this code print (⍈) the input (⍰) + a newline ('<LF>), and return None (∇) ``` [Answer] # Clojure, 18 bytes ``` (print(read-line)) ``` This 30-bytes program runs forever: ``` (while true(print(read-line))) ``` [Answer] # C++ (109 Bytes) Thanks to Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ for reducing 4 bytes. ``` #include <iostream> #include <string> using namespace std;main(){string A,W;while(cin>>A)W+=A;cout<<W<<endl;} ``` [Answer] # Racket, 52 bytes A classical approach. ``` (copy-port(current-input-port)(current-output-port)) ``` In Racket, default settings are stored in parameters which are invoked to obtain their value (or invoked with an argument to set them). This mechanism is also used to access/set the default input and output ports. [Answer] # Python 3, 21 bytes ``` print(input(),end='') ``` [Answer] ## Pyke, 2 bytes ``` zr ``` [Try it here!](http://pyke.catbus.co.uk/?code=zr&input=test%0Atesty) ``` z - read_line() r - if no error: goto_start() ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 5 [bytes](//github.com/DennisMitchell/jelly/wiki/Code-page) ``` ƈȮøL¿ ``` [Try it online!](http://jelly.tryitonline.net/#code=xojIrsO4TMK_&input=c2ludCBtYWFydGVu) This one is valid, unlike the other 1-byte one, which is 100% invalid: ``` ¹ ``` (command-line arg, not STDIN) [Answer] # reticular, 2 bytes ``` ip ``` This exits with an error, but works fine. [Try it online!](http://reticular.tryitonline.net/#code=aXA&input=MDAwMDEyMzEyMzEzMDAxMjAwMApIZWxsbwphc2RmYXNkZgphc2Zk) ``` ip i take a line of input (no newline) p print it with a newline after ``` [Answer] # [ABCR](https://github.com/Steven-Hewitt/ABCR), 4 bytes ``` 5cQx ``` Explanation: ``` 5 while(peek(B)){ //Queue B peeks default to 1, so this infinite-loops c dequeue(c) // Queue C dequeues default to an input character if C is empty Q print(c) /* Prints peek at the queue, and peeks on an empty queue C default to the register value, which was set by `c` */ x } ``` [Answer] ## [QBIC](https://codegolf.stackexchange.com/questions/44680/showcase-your-language-one-vote-at-a-time/86385#86385), 4 bytes ``` _??A ``` Unfortunately, QBasic (and by extension QBIC) doesn't handle input very well. Comma's are only allowed if quotes are used (which then get stripped from the output). Newlines are another no-go. [Answer] ## Emotinomicon, 16 bytes ``` ⏫😎⏪⏬⏩ ``` Explanation: ``` ⏫😎⏪⏬⏩ ⏫ Get input 😎 Reverse Stack ⏪ ⏩ Loop ⏬ Output one char ``` [Answer] ## C#, 79 bytes ``` using x=System.Console;class P{static void Main(){x.Write(x.In.ReadToEnd());}} ``` Thanks Lynn for the hint about using alias vs using static. [Answer] # [pb](//github.com/undergroundmonorail/pb-lang), 20 bytes ``` ^w[B!0]{t[B]vb[T]^>} ``` It will print an input prompt, but I can't do anything about it. This language has no way of supporting infinite input. [Answer] # [Lolo](https://github.com/lvivtotoro/lolo), 2 bytes ``` Lo ``` Not very interesting for a language only made up of Ls and Os. It's basically printing whats in the stack. Since there is nothing, it gets the input. [Answer] # TCL, 28 bytes ``` puts -nonewline [read stdin] ``` [Answer] # Common Lisp (Lispworks), 50 bytes ``` (defun f()(let((x(read-char)))(format t"~A"x)(f))) ``` Usage: ``` CL-USER 165 > (f) aabbccdd 112233 ddeeff ``` [Answer] ## Racket 35 bytes ``` (let l()(displayln(read-line))(l)) ``` Ungolfed: ``` (define (f) (let loop() (displayln (read-line)) (loop))) ``` To run: ``` (f) ``` [Answer] # [Arcyóu](//github.com/Nazek42/arcyou), 2 bytes ``` (q ``` [Try it online!](//arcyou.tryitonline.net#code=KHE&input=SW5wdXQxCklucHV0dHdvCkdVRVNTV0hBVEYqIQpzZWxsCiQkJAorICsgWyBdICsgKw) Strange, a search for `arcyóu inquestion:62230` doesn't seem to turn anything up. Arcyóu has a strange behavior: if there isn't a trailing newline in the output, it will unavoidably append one. If there is a trailing newline, another one will not be appended. `(p(q` will not fix the problem, it will just forcibly append another `\n`. This language cannot possibly handle infinite input. Arcyóu is weird. First Arcyóu answer of mine :D [Answer] # [Actually](https://github.com/Mego/Seriously), 6 bytes ``` ○W◙○WX ``` [Try it online!](https://tio.run/nexus/actually#@/9oenf4o@kzQVTE//9JSUkA "Actually – TIO Nexus") *+2 bytes because I fixed the trailing newline issue.* [Answer] # tcl, 17 ``` puts [read stdin] ``` available to run on <http://www.tutorialspoint.com/execute_tcl_online.php?PID=0Bw_CjBb95KQMeHVzQWNwMjZGZVk> To stop it from running, press Ctrl+D. [Answer] ## Perl 6, 25 bytes ``` .print while $_=$*IN.getc ``` Supports null-bytes, and infinite streams without newlines. If we were allowed to work on a line-by-line basis and always print a trailing newline, it would be only 14 bytes: ``` .say for lines ``` [Answer] # [Del|m|t](https://github.com/MistahFiggins/Delimit), 14 bytes (non-competing) [Try it Online!](https://tio.run/nexus/delimit#@2@uoK@gYKhgrGCnYK9g@f9/SGpxSWZeukJJRqpCcmKJIgA) ``` 7 / 1 3 > ? 9 ``` No command line argument, because is the default Explanation: ``` (7) 23 Gets the next char from input (-1 if its EOF) (/) 15 Duplicate () 0 Pushes 0 (there are no characters -> ASCII sum = 0) (1) 17 Swap top 2 (Stack is [C, 0, C]) (3) 19 Pushes 0 if (C >= 0), 1 Otherwise (i.e. EOF) (>) 30, (?) 31 If the EOF has been reached, exit the program (9) 25 Print the character Repeat ``` [Answer] # SmileBASIC, 13 bytes ``` LINPUT S$?S$; ``` very simple. ]
[Question] [ ### Definition Define the **n**th array of the CURR sequence as follows. 1. Begin with the singleton array **A = [n]**. 2. For each integer **k** in **A**, replace the entry **k** with **k** natural numbers, counting up from **1** to **k**. 3. Repeat the previous step **n - 1** more times. For example, if **n = 3**, we start with the array **[3]**. We replace **3** with **1, 2, 3**, yielding **[1, 2, 3]**. We now replace **1**, **2**, and **3** with **1**; **1, 2** and **1, 2, 3** (resp.), yielding **[1, 1, 2, 1, 2, 3]**. Finally, we perform the same replacements as in the previous step for all six integers in the array, yielding **[1, 1, 1, 2, 1, 1, 2, 1, 2, 3]**. This is the third CURR array. ### Task Write a program of a function that, given a strictly positive integer **n** as input, computes the **n**th CURR array. The output has to be a *flat* list of some kind (and array returned from a function, a string representation of your language's array syntax, whitespace-separated, etc.). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). May the shortest code in bytes win! ### Test cases ``` 1 -> [1] 2 -> [1, 1, 2] 3 -> [1, 1, 1, 2, 1, 1, 2, 1, 2, 3] 4 -> [1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4] 5 -> [1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5] 6 -> [1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6] ``` [Answer] ## Jelly, 3 bytes ``` R¡F ``` [Try it online](http://jelly.tryitonline.net/#code=UsKhRg&input=&args=Mw) ## Explanation ``` R¡F Argument n R Yield range [1..n] ¡ Repeat n times F Flatten the result ``` [Answer] ## Python, 50 bytes ``` lambda i:eval("[i "+"for i in range(1,i+1)"*i+"]") ``` Scope abuse! For example, for `i=3`, the string to be evaluated expands to. ``` [i for i in range(1,i+1)for i in range(1,i+1)for i in range(1,i+1)] ``` Somehow, despite using the function input variable `i` for everything, Python distinguishes each iteration index as belonging to a separate scope as if the expression were ``` [l for j in range(1,i+1)for k in range(1,j+1)for l in range(1,k+1)] ``` with `i` the input to the function. [Answer] ## 05AB1E, ~~6~~ 3 bytes ``` DFL ``` **Explained** ``` D # duplicate input F # input times do L # range(1,N) ``` [Try it online](http://05ab1e.tryitonline.net/#code=REZM&input=Mw) Saved 3 bytes thanks to @Adnan [Answer] ## [Retina](https://github.com/mbuettner/retina), 33 bytes ``` $ $.`$*0 +%(M!&`1.*(?=0)|^.+ O`.+ ``` Input and output in unary. [Try it online!](http://retina.tryitonline.net/#code=JAokLmAkKjAKKyUoTSEmYDEuKig_PTApfF4uKwpPYC4r&input=MTEx) Even though I didn't use the closed form for the related challenge, adapting this answer was surprisingly tricky. [Answer] ## Python 2, 82 bytes ``` lambda n:[1+bin(i)[::-1].find('1')for i in range(1<<2*n-1)if bin(i).count('1')==n] ``` This isn't the shortest solution, but it illustrates an interesting method: * Write down the first `2^(2*n-1)` numbers in binary * Keep those with exactly `n` ones * For each number, count the number of trailing zeroes, and add 1. [Answer] ## Actually, 9 bytes ``` ;#@`♂RΣ`n ``` [Try it online!](http://actually.tryitonline.net/#code=OyNAYOKZglLOo2Bu&input=Mw) Explanation: ``` ;#@`♂RΣ`n ;#@ dupe n, make a singleton list, swap with n `♂RΣ`n call the following function n times: ♂R range(1, k+1) for k in list Σ concatenate the ranges ``` Thanks to Leaky Nun for a byte, and inspiration for another 2 bytes. [Answer] ## C#, 128 Bytes ``` List<int>j(int n){var l=new List<int>(){n};for(;n>0;n--)l=l.Select(p=>Enumerable.Range(1,p)).SelectMany(m=>m).ToList();return l; ``` [Answer] # APL, 11 bytes ``` {∊⍳¨∘∊⍣⍵+⍵} ``` Test: ``` {∊⍳¨∘∊⍣⍵+⍵} 3 1 1 1 2 1 1 2 1 2 3 ``` Explanation: * `+⍵`: starting with `⍵`, * `⍣⍵`: do the following `⍵` times: + `⍳¨∘∊`: flatten the input, and then generate a list [1..N] for each N in the input * `∊`: flatten the result of that [Answer] # J, 18 bytes ``` ([:;<@(1+i.)"0)^:] ``` Straight-forward approach based on the process described in the challenge. ## Usage ``` f =: ([:;<@(1+i.)"0)^:] f 1 1 f 2 1 1 2 f 3 1 1 1 2 1 1 2 1 2 3 f 4 1 1 1 1 2 1 1 1 2 1 1 2 1 2 3 1 1 1 2 1 1 2 1 2 3 1 1 2 1 2 3 1 2 3 4 ``` ## Explanation ``` ([:;<@(1+i.)"0)^:] Input: n ] Identity function, gets the value n ( ... )^: Repeat the following n times with an initial value [n] ( )"0 Means rank 0, or to operate on each atom in the list i. Create a range from 0 to that value, exclusive 1+ Add 1 to each to make the range from 1 to that value <@ Box the value [:; Combine the boxes and unbox them to make a list and return Return the final result after n iterations ``` [Answer] ## CJam, 14 bytes ``` {_a\{:,:~:)}*} ``` [Test it here.](http://cjam.aditsu.net/#code=3%0A%0A%7B_a%5C%7B%3A%2C%3A~%3A)%7D*%7D%0A%0A~p&input=3) ### Explanation ``` _a e# Duplicate N and wrap it in an array. \ e# Swap with other copy of N. { e# Do this N times... :, e# Turn each x into [0 1 ... x-1]. :~ e# Unwrap each of those arrays. :) e# Increment each element. }* ``` [Answer] ## Mathematica, ~~27~~ 26 bytes *1 byte saved with some inspiration from Essari's answer.* ``` Flatten@Nest[Range,{#},#]& ``` Fairly straightforward: for input `x` we start with `{x}` and then apply the `Range` to it `x` times (`Range` is `Listable` which means that it automatically applies to the integers inside arbitrarily nested lists). At the end `Flatten` the result. [Answer] ## Clojure, 59 bytes ``` (fn[n](nth(iterate #(mapcat(fn[x](range 1(inc x)))%)[n])n)) ``` Explanation: Really straight forward way to solve the problem. Working from the inside out: ``` (1) (fn[x](range 1(inc x))) ;; return a list from 1 to x (2) #(mapcat (1) %) ;; map (1) over each item in list and flatten result (3) (iterate (2) [n]) ;; call (2) repeatedly e.g. (f (f (f [n]))) (4) (nth (3) n)) ;; return the nth value of the iteration ``` [Answer] # Python 3, ~~75~~ 74 bytes ``` def f(k):N=[k];exec('A=N;N=[]\nfor i in A:N+=range(1,i+1)\n'*k+'print(N)') ``` This is just a straightforward translation of the problem description to code. Edit: Saved one byte thanks to @Dennis. [Answer] ## R, ~~60~~ 49 bytes Pretty straightforward use of `unlist` and `sapply`. ``` y=x=scan();for(i in 1:x)y=unlist(sapply(y,seq));y ``` Thanks to @MickyT for saving 11 bytes [Answer] ## php 121 Not really very much in the way of tricks behind this one. Flattening an array in php isn't short so it's necessary to build it flat in the first place ``` <?php for($a=[$b=$argv[1]];$b--;)$a=array_reduce($a,function($r,$v){return array_merge($r,range(1,$v));},[]);print_r($a); ``` [Answer] ## Haskell, 33 bytes ``` f n=iterate(>>= \a->[1..a])[n]!!n ``` Thanks to nimi for saving a byte. A pointfree version is longer (35 bytes): ``` (!!)=<<iterate(>>= \a->[1..a]).pure ``` [Answer] ## JavaScript (Firefox 30-57), ~~63~~ 60 bytes ``` f=n=>eval(`[${`for(n of Array(n+1).keys())`.repeat(n--)}n+1]`) ``` Port of @xnor's Python answer. [Answer] # Pyth, 8 bytes ``` usSMGQ]Q ``` [Try it online!](http://pyth.herokuapp.com/?code=usSMGQ%5DQ&test_suite=1&test_suite_input=3&debug=0) ``` usSMGQ]Q input as Q u Q repeat for Q times, ]Q starting as [Q]: SMG convert each number in the array to its range s flatten then implicitly prints the result. ``` [Answer] # Jelly, 7 bytes Quick, before Dennis answers (jk) ``` WR€F$³¡ ``` [Try it online!](http://jelly.tryitonline.net/#code=V1LigqxGJMKzwqE&input=Mw&args=Mw) ``` WR€F$³¡ Main monadic chain. Argument: z W Yield [z]. ³¡ Repeat the following z times: R€ Convert each number in the array to the corresponding range. F Flatten the array. ``` [Answer] ## F# , 63 bytes ``` fun n->Seq.fold(fun A _->List.collect(fun k->[1..k])A)[n]{1..n} ``` Returns an anonymous function taking n as input. Replaces every entry k in A with [1..k], repeats the process n times, starting with A = [n]. [Answer] # Swift 3, 58 Bytes Meant to run directly in the a playground, with n set to the input: ``` var x=[n];for i in 0..<n{x=x.reduce([]){$0+[Int](1...$1)}} ``` Ungolfed, with most short hand notation reverted: ``` let n = 3 //input var x: Array<Int> = [n] for i in 0..<n { x = x.reduce(Array<Int>[], combine: { accumulator, element in accumulator + Array<Int>(1...element) }) } ``` [Answer] # Java, 159 Bytes **Procedure** ``` int[] q(int y){int z[]=new int[]{y};for(int i=0;i<y;i++){int d=0,a=0;for(int c:z)d+=c;int[]r=new int[d];for(int c:z)for(int j=0;j<c;)r[a++]=++j;z=r;}return z;} ``` **Usage** ``` public static void main(String[] args){String out = "["; int [] b = q(6);for(int c:b)out+=c+", ";System.out.println(out+"]");} public static int[] q(int y){int z[]=new int[]{y};for(int i=0;i<y;i++){int d=0,a=0;for(int c:z)d+=c;int[]r=new int[d];for(int c:z)for(int j=0;j<c;)r[a++]=++j;z=r;}return z;} ``` *Sample output:* ``` [1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, ] ``` [Answer] ## Python 2, ~~69~~ ~~68~~ 66 bytes ``` def f(n):a=[n];exec'a=sum([range(1,i+1)for i in a],[]);'*n;print a ``` Edit: Saved 1 byte thanks to @xnor. Saved 2 bytes thanks to @Dennis♦. [Answer] # Bash + GNU utilities, 49 * 1 byte saved thanks to @Dennis. Piped recursive functions FTW! ``` f()((($1))&&xargs -l seq|f $[$1-1]||dd) f $1<<<$1 ``` `n` is passed on the command-line. Output is newline-separated. The use of `dd` causes statistics to be sent to STDERR. I think this is OK, but if not, `dd` can be replaced with `cat` at a cost of 1 extra byte. [Answer] # [Ruby](https://www.ruby-lang.org/), 44 bytes A simple recursive approach. ``` ->n,a=[n]{n>0?F[n-1,a.flat_map{[*1.._1]}]:a} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3dXTt8nQSbaPzYqvz7Azs3aLzdA11EvXSchJL4nMTC6qjtQz19OINY2tjrRJrIXqWFSi4RRvHQjgLFkBoAA) [Answer] # Perl 5, 53 bytes A subroutine: ``` {($i)=@_;for(1..$i){my@c;push@c,1..$_ for@_;@_=@c}@_} ``` See it in action as ``` perl -e'print "$_ " for sub{($i)=@_;for(1..$i){my@c;push@c,1..$_ for@_;@_=@c}@_}->(3)' ``` [Answer] ## Ruby, 61 bytes ``` def f(n);a=[n];n.times{a=a.map{|i|(1..i).to_a}.flatten};a;end ``` [Answer] # PHP, ~~100~~ 98 bytes Run with `php -r '<code>' <n>`. ``` for($a=[$n=$argv[1]];$n--;$a=$b)for($b=[],$k=0;$c=$a[$k++];)for($i=0;$i++<$c;)$b[]=$i;print_r($a); ``` In each iteration create a temporary copy looping from 1..(first value removed) until `$a` is empty. --- These two are still and will probably remain at 100 bytes: ``` for($a=[$n=$argv[1]];$n--;)for($i=count($a);$i--;)array_splice($a,$i,1,range(1,$a[$i]));print_r($a); ``` In each iteration loop backwards through array replacing each number with a range. ``` for($a=[$n=$argv[1]];$n--;)for($i=$c=0;$c=$a[$i+=$c];)array_splice($a,$i,1,range(1,$c));print_r($a); ``` In each iteration loop through array increasing index by previous number and replacing each indexed element with a range [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-mh`](https://codegolf.meta.stackexchange.com/a/14339/), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` N=cõ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1o&code=Tj1j9Q&input=Mw) [Answer] # [Perl 5](https://www.perl.org/) + `-p`, 28 bytes ``` eval's/\d+/@{[1..$&]}/g;'x$_ ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiZXZhbCdzL1xcZCsvQHtbMS4uJCZdfS9nOyd4JF8iLCJhcmdzIjoiLXAiLCJpbnB1dCI6IjFcbjJcbjNcbjRcbjVcbjYifQ==) ]
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []
[Question] []