# Question
Title: Running length of the movie in a human readable format
Whenever I search for the running length of a movie in IMDb, it is displayed in minutes. Immediately I would try to convert it into hour(s) and minute(s). It would be better if we could automate this.

Input:

```
150 min

```

Output:

```
2 hours 30 minutes

```

Input:

```
90 min

```

Output:

```
1 hour 30 minutes

```

Input:

```
61 min

```

Output:

```
1 hour 1 minute

```

Input:

```
60 min

```

Output:

```
1 hour 0 minute or 1 hour 0 minutes

```

**Following are the conditions:**

1. Input and Output should be in this exact format.
2. Input minutes will between 0 and 240.
3. Your answer can accept command line arguments or read input from the user or a function.
4. Output should not be enclosed within quotes.
5. Output must be printed, not returned.

**Leaderboard:**

```
    var QUESTION_ID=65106,OVERRIDE_USER=16196;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/65106/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}#answer-list{padding-right: 100px}
```

```
    <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>
```

# Result:

Its a tie between CJam and Pyth. Accepting CJam's answer as it was submitted before Pyth's 35 bytes code. However, please continue encouraging new submissions.

# Answer
> 10 votes
# CJam, ~~39~~ 35 bytes

```
ri60md]"hour minute"S/.{1$1>'s*+}S*

```

Try it online

Latest version includes improvements suggested by @MartinBüttner, particularly using the element-wise vector operator instead of transposing the two lists.

Explanation:

```
ri    Get input and convert to integer.
60md  Split into hours and minutes by calculating moddiv of input.
]     Wrap hours and minutes in a list.
"hour minute"
      String with units.
S/    Split it at spaces, giving ["hour" "minute"]
.{    Apply block element-wise to pair of vectors.
  1$    Copy number to top.
  1>    Check for greater than 1.
  's    Push 's.
  *     Multiply with comparison result, giving 's if greater 1, nothing otherwise.
  +     Concatenate optional 's with rest of string.
}     End block applied to both parts.
S*    Join with spaces.

```

# Answer
> 19 votes
# Python 3, ~~50~~ ~~67~~ ~~119~~ ~~116~~ ~~112~~ ~~111~~ ~~104~~ 94 bytes

~~I'm not fond of going back to `%`-style string formatting, but it saves 6 bytes on `.format`.~~

**Edit:** Forgot to parse input.

**Edit:** Forgot to handle plurals.

~~**Edit:** Yay lambdas!~~

**Edit:** Added ungolfing

**Edit:** Darn it. Lambdas didn't help.

**Edit:** Since the minutes have maximum three digits, and `int()` doesn't mind spaces in the string, I can save a few bytes by using `input()[:3]`.

```
i,j=divmod(int(input()[:3]),60);print(str(i),"hour"+("s"[:i!=1]),str(j),"minute"+("s"[:i!=1]))

```

Ungolfed:

```
string = input()[:3]
hours, minutes = divmod(int(string), 60)
a = string(div)
b = "hour" + ("s" if hours == 1 else "")
c = string(mod)
d = "minute" + ("s" if minutes == 1 else "")
print(a, b, c, d)

```

# Answer
> 9 votes
# JavaScript, 78 bytes

```
n=>(h=(n=parseInt(n))/60|0)+` hour${h-1?"s":""} ${m=n%60} minute`+(m-1?"s":"")
```

```
<!--                               Try the test suite below!                              --><strong id="bytecount" style="display:inline; font-size:32px; font-family:Helvetica"></strong><strong id="bytediff" style="display:inline; margin-left:10px; font-size:32px; font-family:Helvetica; color:lightgray"></strong><br><br><pre style="margin:0">Code:</pre><textarea id="textbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><pre style="margin:0">Input:</pre><textarea id="inputbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><button id="testbtn">Test!</button><button id="resetbtn">Reset</button><br><p><strong id="origheader" style="font-family:Helvetica; display:none">Original Code Output:</strong><p><div id="origoutput" style="margin-left:15px"></div><p><strong id="newheader" style="font-family:Helvetica; display:none">New Code Output:</strong><p><div id="newoutput" style="margin-left:15px"></div><script type="text/javascript" id="golfsnippet">var bytecount=document.getElementById("bytecount");var bytediff=document.getElementById("bytediff");var textbox=document.getElementById("textbox");var inputbox=document.getElementById("inputbox");var testbtn=document.getElementById("testbtn");var resetbtn=document.getElementById("resetbtn");var origheader=document.getElementById("origheader");var newheader=document.getElementById("newheader");var origoutput=document.getElementById("origoutput");var newoutput=document.getElementById("newoutput");textbox.style.width=inputbox.style.width=window.innerWidth-50+"px";var _originalCode=null;function getOriginalCode(){if(_originalCode!=null)return _originalCode;var allScripts=document.getElementsByTagName("script");for(var i=0;i<allScripts.length;i++){var script=allScripts[i];if(script.id!="golfsnippet"){originalCode=script.textContent.trim();return originalCode}}}function getNewCode(){return textbox.value.trim()}function getInput(){try{var inputText=inputbox.value.trim();var input=eval("["+inputText+"]");return input}catch(e){return null}}function setTextbox(s){textbox.value=s;onTextboxChange()}function setOutput(output,s){output.innerHTML=s}function addOutput(output,data){output.innerHTML+='<pre style="background-color:'+(data.type=="err"?"lightcoral":"lightgray")+'">'+escape(data.content)+"</pre>"}function getByteCount(s){return(new Blob([s],{encoding:"UTF-8",type:"text/plain;charset=UTF-8"})).size}function onTextboxChange(){var newLength=getByteCount(getNewCode());var oldLength=getByteCount(getOriginalCode());bytecount.innerHTML=newLength+" bytes";var diff=newLength-oldLength;if(diff>0){bytediff.innerHTML="(+"+diff+")";bytediff.style.color="lightcoral"}else if(diff<0){bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgreen"}else{bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgray"}}function onTestBtn(evt){origheader.style.display="inline";newheader.style.display="inline";setOutput(newoutput,"");setOutput(origoutput,"");var input=getInput();if(input===null){addOutput(origoutput,{type:"err",content:"Input is malformed. Using no input."});addOutput(newoutput,{type:"err",content:"Input is malformed. Using no input."});input=[]}doInterpret(getNewCode(),input,function(data){addOutput(newoutput,data)});doInterpret(getOriginalCode(),input,function(data){addOutput(origoutput,data)});evt.stopPropagation();return false}function onResetBtn(evt){setTextbox(getOriginalCode());origheader.style.display="none";newheader.style.display="none";setOutput(origoutput,"");setOutput(newoutput,"")}function escape(s){return s.toString().replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}window.alert=function(){};window.prompt=function(){};function doInterpret(code,input,cb){var workerCode=interpret.toString()+";function stdout(s){ self.postMessage( {'type': 'out', 'content': s} ); }"+" function stderr(s){ self.postMessage( {'type': 'err', 'content': s} ); }"+" function kill(){ self.close(); }"+" self.addEventListener('message', function(msg){ interpret(msg.data.code, msg.data.input); });";var interpreter=new Worker(URL.createObjectURL(new Blob([workerCode])));interpreter.addEventListener("message",function(msg){cb(msg.data)});interpreter.postMessage({"code":code,"input":input});setTimeout(function(){interpreter.terminate()},1E4)}setTimeout(function(){getOriginalCode();textbox.addEventListener("input",onTextboxChange);testbtn.addEventListener("click",onTestBtn);resetbtn.addEventListener("click",onResetBtn);setTextbox(getOriginalCode())},100);function interpret(code,input){window={};alert=function(s){stdout(s)};window.alert=alert;console.log=alert;prompt=function(s){if(input.length<1)stderr("not enough input");else{var nextInput=input[0];input=input.slice(1);return nextInput.toString()}};window.prompt=prompt;(function(){try{var evalResult=eval(code);if(typeof evalResult=="function"){var callResult=evalResult.apply(this,input);if(typeof callResult!="undefined")stdout(callResult)}}catch(e){stderr(e.message)}})()};</script>
```

For the test suite, enter input like `"61 min"` into the input box.

### Explanation

```
n=>                 //Define anonymous function w/ parameter n
(h=                 //start building the string to return with h, the # of hours
(n=parseInt(n))     //parse input for n
/60|0)+             //set h to floor(n / 60)
` hour              //add ' hour' to the string to return
${h-1?"s":""}       //add 's' to the string to return if h != 1, else add ''
                    //<--(a single space) add ' ' to the string to return
${m=n%60}           //set m, the # of miuntes, to n % 60, and add it to the string to return
 minute`+           //add ' minute' to the string to return
(m-1?"s":"")        //add 's' to the string to return if m != 1, else add ''
                    //implicitly return

```

# Answer
> 6 votes
# Pyth, 39 38 bytes

```
jd.iJ.Dv-zG60+Vc"hour minute")m*\s>d1J

```

# Answer
> 5 votes
# Vitsy, ~~57~~ ~~54~~ 52 bytes

Oh, wow, I don't even have integers in my language. o-o

```
VVa6*Dv/D1M-D1m'ruoh 'Z' 'OVvM1m'etunim 'Z
N1-(['s']

```

```
VV                                      Capture the input as a final global
                                        variable, and push it again.
  a6*Dv/1M-                             Get floor(input/60), capturing 60 as a
                                        temp variable in the process.
           DN                           Duplicate and output it as a number.
             1-(['s']                   If it is only one, push 's'.

            'ruoh '                     Push ' hour'
                   Z                    Output everything.
                    ' 'O                Output a space.
V                                       Push the input.
 v                                      Get the temp variable (60).
  M                                     Modulo.
            N                           Output as a number.
             1-(['s']                   If it is only one, push 's'.

             'ruoh '                    Push ' hour'
                    Z                   Output everything.

```

Try it online!

# Answer
> 4 votes
## Pyth, 46 bytes

```
jKdm++J.v+++hd:z03K60K+td*\s>J1c"/hour %minute

```

Takes input as `x min` and outputs `x hours y minutes`

Try it Here

Explanation:

```
   m~~~~~~~~~~~~~~~~~~~~~~~~~~~c"/hour %minute - map(func, "/hour %minute".split(" "))
            hd                                 - Get the first character of the string (/ or %)
              :z03                             - Get the first 3 characters of input
         +++      K60                          - Join them together and add a space and 60 to the end
      J.v                                      - Evaluate it and set result to J
                       td                      - Get all the characters of the string but the first (hour, minute)
                      +  *\s>J1                - If the result of the evaluated expression is less than 1, add an 's' character to the string
    ++               K                         - Join the results seperated with a space
jKd                                            - Join the 2 halves together with a space

```

# Answer
> 4 votes
# K5, ~~55~~ 51 bytes

```
" "/(" hour";" minute"){y,x,("s";"")1=.y}'$25 60\.*" "\

```

This is more general than it strictly has to be; might still golf it down further.

In action:

```
  f: " "/(" hour";" minute"){y,x,("s";"")1=.y}'$25 60\.*" "\;

  f'("61 min";"120 min";"150 min")
("1 hour 1 minute"
 "2 hours 0 minutes"
 "2 hours 30 minutes")

```

## Edit:

This program went through several very different iterations in the course of development, and I thought that it might be more illuminating to show some of the intermediate steps.

Here was my first stab at the problem, before the pluralization requirement was introduced. There is clear repetition here:

```
{($_x%60)," hours ",($_60!x)," minutes"}@.*" "\

```

I realized that the general way to handle casting out of places was K5's "decode" form. To slot values into place in the string I used the "dot-apply" primitive, which applies an argument list to a function and unpacks the list into individual parameters:

```
{x," hours ",y," minutes"}.$25 60\.*" "\

```

Not much redundancy left here. When pluralization was added, I decomposed that leading anonymous function into a transformation I could apply to each number, like this:

```
{x,y,("s";"")1=.x}

```

Join `x`, `y`, and either `s` or nothing, depending on whether `x` is equal to "1". Ultimately it worked better to reverse the order of the arguments to this function.

## Edit 2:

```
" "/(" hour";" minute"){y,x,("s";"")1=.y}'$25 60\.*" "\
" "/(" hour";" minute"){y,x,(~1=.y)#"s"}'$5 60\.-4_

```

Several small improvements here. A better way of selecting an "s" or an empty string, a shorter constant for "decode" which reflects the limited range of input, and a simpler way of discarding "min".

# Answer
> 3 votes
# JavaScript (ES6), ~~100~~ ~~94~~ ~~89~~ 81 bytes

```
t=>(h=0|(t=parseInt(t))/60)+' hour'+(h>1?'s ':' ')+t%60+' minute'+(t%60>1?'s':'')

```

De-golfed demo (converted to ES5, as not all the browsers support ES6 yet)

```
function s(t) {
  return (h = 0 | (t = parseInt(t)) / 60) + ' hour' + (h > 1 ? 's ' : ' ') + t % 60 + ' minute' + (t % 60 > 1 ? 's' : '');
}

alert(s(prompt()))
```

# Answer
> 3 votes
## Perl 6, ~~80~~ 73 bytes

80 byte original

```
{my$h=$_ div 60;my$m=$_%60;"$h hour{'s'x?($h-1)}"~" $m minute{'s'x?($m-1)}"x?$m}

```

Usage:

```
.say for (150,90,61,60).map:
  {my$h=$_ div 60;my$m=$_%60;"$h hour{'s'x?($h-1)}"~" $m minute{'s'x?($m-1)}"x?$m}

```

```
2 hours 30 minutes
1 hour 30 minutes
1 hour 1 minute
1 hour

```

Due to a change in the question I can remove `x?$m` from the end of the function, which allows me to reduce it by 3 more bytes.

```
{my$h=$_ div 60;my$m=$_%60;"$h hour{'s'x?($h-1)} $m minute{'s'x?($m-1)}"}

```

```
2 hours 30 minutes
1 hour 30 minutes
1 hour 1 minute
1 hour 0 minutes

```

# Answer
> 3 votes
# C#, 127 bytes

```
var i=int.Parse(Console.ReadLine().Split(' ')[0]);Console.Write(i/60+" hour"+(i/60>1?"s ":" ")+i%60+" minute"+(i%60>1?"s":""));

```

This can be put in a file and run via the C# interactive shell that comes with Mono, using the default configuration.

\[This is my first attempt at code golf. I hope that my contribution is not violating any rules.\]

# Answer
> 3 votes
# C, 89 bytes

```
main(n){scanf("%d",&n);printf("%d hour%s %d minute%s",n/60,"s"+119/n,n%60,"s"+(n%60<2));}

```

# Answer
> 3 votes
# Ruby, 75 bytes

```
a,b=gets.to_i.divmod 60;$><<"#{a} hour#{a>1??s:''} #{b} minute#{b>1??s:''}"

```

# Answer
> 2 votes
# MATLAB, ~~111 108~~ 106 bytes

```
i=sscanf(input(''),'%d');h=fix(i/60);m=i-h*60;fprintf('%d hour%c %d minute%c\n',h,'s'*(h~=1),m,'s'*(m~=1))

```

This also works with **Octave**, and can be tried here. The link is to a workspace already containing the code in a file named `runningLength.m`. So to test it out simply enter `runningLength` at the prompt, then enter the input string, e.g. `'123 mins'` and it will display the output.

Takes the input as a string, e.g. `'123 mins'`, converts it to a number (which implicitly ignores the `mins` bit).

```
i=sscanf(input(''),'%d');

```

Minutes and hours are then calculated

```
h=fix(i/60);m=i-h*60;

```

Then displays the output string

```
fprintf('%d hour%c %d minute%c',h,'s'*(h~=1),m,'s'*(m~=1));

```

The 's' bit of the output is calculated and handled correctly - an 's' is added whenever the number is not 1.

# Answer
> 2 votes
# Haskell, ~~117~~ 109 bytes

```
f x|(d,m)<-divMod(read$take 3 x)60=putStr$u[d#"hour",m#"minute"];u=unwords;1#q=u["1",q];p#q=u[show p,q++"s"]

```

Less golfed version:

```
f :: String -> IO ()
f x = putStr (unwords [(n`div`60)#"hour",(n`mod`60)#"minute"])
  where
  n :: Int
  n = take 3 (read x)

  (#) :: Int -> String -> String
  1#q = unwords ["1",q]
  p#q = unwords [show p,q++"s"]

```

`f` is a function which takes the first 3 characters of its input and converts them to an integer. `p#q` is a function which pluralises `q` if `p` is not equal to 1. In order to return the result without surrounding quotes, I used `putStr` to print the result to STDOUT.

Thanks to nimi for the help!

# Answer
> 2 votes
# Python 2, ~~79~~ 77 bytes

```
m=int(raw_input()[:3])
print m/60,"hours"[:4+m/120],m%60,"minutes"[:6+m/2%30]

```

The first 3 characters of the input are simply parsed as an integer. This only works because the third character in a 2 digit input is a space, which `int` will ignore during conversion.

# Answer
> 2 votes
# R, 112 bytes

**Edit**: Fixed a scoping error and then addressed the quotation output issue.

```
g=function(x){h=floor(x/60);m=x%%60;cat(paste(h,ifelse(h==1,"hour","hours"),m,ifelse(m==1,"minute","minutes")))}

```

### Test cases

```
> g(150)
2 hours 30 minutes
> g(90)
1 hour 30 minutes
> g(61)
1 hour 1 minute
> g(60)
1 hour 0 minutes

```

I tried to save space by trying to find a way to just add or subtract "s" as necessary but I had to mess with the `sep =` argument in the `paste()` function and it didn't really seem like it was going to save me very much space. Any suggestions?

### Ungolfed

```
g=function(x){
    h=floor(x/60);
    m=x%%60;
    cat(paste(h,
              ifelse(h==1,"hour","hours"),
              m,
              ifelse(m==1,"minute","minutes")))
}

```

Rounding down with input/60 or input%%60 (mod) gives the hours and minutes respectively. Chain them together with an `ifelse()` statement that specifies whether or not the units are hour(s) or minute(s).

# Answer
> 2 votes
# Haskell, ~~107~~ 101 bytes

```
g=putStr.f.read.take 3;s!1='1':s;s!n=show n++s++"s";f x|(a,b)<-divMod x 60=" hour"!a++' ':" minute"!b

```

Ungolfed:

```
g :: String -> String
g = putStr . f . read . take 3
  where
    (!) :: String -> Int -> String
    s!1 = '1':s
    s!n = show n++s++"s"

    f :: Int -> String;
    f x
      | (a,b) <- divMod x 60 = " hour"!a ++ ' ':(" minute"!b)

```

`s!n` prepends `n` to `s`, adding a `'s'` to the end if `n /= 1`.

`f x` does the formatting after using `divMod`.

Since we can assume a max input of `240`, `take 3` is sufficient to take only the number.

(Had to try really hard to beat @Craig Roy's score...)

# Answer
> 2 votes
# LabVIEW, 50 Bytes

This is counted according to my suggestion on Meta.

The code is pretty straight forward, take number from input Modulo by 60 and add an s for minutes != 1. Other side of case just puts the string through.

# Answer
> 2 votes
# Scala, 135 bytes

```
var a=(i:String)=>{var (v,b)=(i.split(" ")(0).toInt,(i:Int)=>if(i<2)""else"s");printf(v/60+" hour"+b(v/60)+" "+v%60+" minute"+b(v%60))}

```

**Usage:**

```
a("120 min")
2 hours 0 minute

```

# Answer
> 1 votes
## Python 2, 96 bytes

```
i=int(raw_input().split()[0])
print"%d hour%s %d minute%s"%(i/60,"s"*(i>120),i%60,"s"*(i%60!=1))

```

# Answer
> 1 votes
## Python, 152 bytes

Sorry, fixed the code so it handles the input/output the way the insturctions say.

```
 def t(p):
  import math
  print(str(math.floor(p/60))+" hour" + ("s " if math.floor(p/60>1) else " ") +str(p%60)+" minute" + ("s " if p%60>1 else ""))

```

Edit:  ~~Why is the still -1 with the edited code? It works exactly how the OP asks.~~

# Answer
> 1 votes
# Ruby, ~~97~~ ~~100~~ ~~99~~ 88 bytes

**Edit:** Fixing output.

**Edit:** Removing braces from `divmod`.

**Edit:** Yay string interpolation! Thanks to Vasu Adari. Also, better ungolfing.

```
i,j=gets.split[0].to_i.divmod 60;puts"#{i} hour#{i==1?"":"s"} #{j} minute#{j==1?"":"s"}"

```

Ungolfed:

```
input = gets                            Input
number = input.split[0].to_i            Get number, convert to int
hours, minutes = number.divmod 60       hours == s / 60, minutes == s % 60
result = hours.to_s+" hour"             Start with the hours
result += {hours == 1 ? "" : "s"}       Put in the first "s" if plural
result += minutes.to_s+" minute"        Add the minutes
result += {minutes == 1 ? "" : "s"}     Put in the second "s" if plural
puts result                             Output

```

# Answer
> 1 votes
# Mathematica, 61 bytes

```
Print@ToString[Quantity@#~UnitConvert~MixedRadix["h","min"]]&

```

# Answer
> 1 votes
# Go, 177 Bytes<br>

(It includes only the function and the import statements)

```
import("fmt";c"strconv";t"strings")
func f(s string){p,_:=c.Atoi(t.Split(s," ")[0]);t:=fmt.Printf;h:=p/60;m:=p%60;t("%d Hour",h);if h>1{t("s")};t(" %d Minute",m);if m>1{t("s")}}

```

Pretty solution -

```
func f(s string) {
    p, _ := c.Atoi(t.Split(s, " ")[0])
    t := fmt.Printf
    h := p / 60;m := p % 60
    t("%d Hour", h)
    if h > 1 {
        t("s")
    }
    t(" %d Minute", m)
    if m > 1 {
        t("s")
    }
}

```

Testing it -

```
func main() {
    ip_list := []string{
        "120 min",
        "150 min",
        "60 min",
    }

    for _, ip_val := range ip_list {
        f(ip_val)
        fmt.Println("")
    }
}

/* OUTPUT
2 Hours 0 Minute
2 Hours 30 Minutes
1 Hour 0 Minute
*/

```

# Answer
> 1 votes
## Seriously, 77 bytes

```
ε" min",Æ≈;:60:@\@:60:@%'sε(;)1≥I"%d hour"+(#@%'sε(;)1≥I"%d minute"+(#@%@k' j

```

Seriously is *seriously* not good at string manipulation. Try it online with full explanation (you will need to manually enter the input like `"210 mins"` because permalinks don't like quotes).

Quick and dirty explanation:

```
ε" min",Æ≈            get input, replace " min" with the empty string, convert to int
;:60:@\@:60:@%        calculate divmod
'sε(;)1≥I"%d hour"+   push "%d hour" or "%d hours", depending on whether pluralization is needed
(#@%                  format "%d hour(s)" with the # of hours calculated earlier
'sε(;)1≥I"%d minute"+ same as above, but with minutes
(#@%                  same as above, but with minutes
@k' j                 swap the order and join with a space to get "X hour(s) X minute(s)"

```

# Answer
> 1 votes
# Ruby, ~~74~~ ~~73~~ 71 bytes

```
->i{puts"#{i=i.to_i;h=i/60} hour#{h>1??s:''} #{m=i%60} minute#{m>1??s:''}"}

```

**73 bytes**

```
->i{puts"#{h,m=i.to_i.divmod 60;h} hour#{h>1??s:''} #{m} minute#{m>1??s:''}"}

```

**74 bytes:**

```
->i{h,m=i.to_i.divmod 60;puts "#{h} hour#{h>1??s:''} #{m} minute#{m>1??s:''}"}

```

**Usage:**

```
->i{puts"#{i=i.to_i;h=i/60} hour#{h>1??s:''} #{m=i%60} minute#{m>1??s:''}"}[61]

1 hour 1 minute

```

# Answer
> 1 votes
# PHP, ~~77~~ 76 bytes

```
$m=($i=$argv[1])%60;echo$h=$i/60|0," hour","s"[$h<2]," $m minute","s"[$m<2];

```

horible, horible, horible!
PHP only issues a couple of `Notice`s for `"s"[$h<2]`

To run: `php -r 'CODE' '150 minutes'`
and of course turn error reporting off/away from stdout!

Edit: -1byte assign in assign (credit: insertusernamehere)

It's so ugly I must give a run helper for linux users:

```
php -c /usr/share/php5/php.ini-production.cli -r 'CODE' '61 min'

```

# Answer
> 1 votes
## AutoHotkey, ~~174~~ ~~170~~ 160 bytes

```
x::Send,% !i?"x" i:=SubStr(clipboard,1,(Clipboard~="\s")):"{Backspace "StrLen(i)"}" i//60 " Hour"(i//60!=1?"s ":" ")Mod(i,60)" Minute"(Mod(i,60)!=1?"s":"")i:=""

```

Notes:

1. Input from Clipboard
2. Output prints to any form by pressing `x`
3. Correctly handles plurals
4. Could be smaller but I wanted a provide a One Liner.

# Answer
> 1 votes
# Go, ~~168~~ ~~132~~ ~~127~~ ~~120~~ ~~121~~ ~~120~~ 115 bytes

~~Try it here!~~

Even with minification, I'm ~~still being beaten by Java ):~~ finally beating Java!

*note: there's nothing in the spec about plurals nor excluding `0 minutes`, so my program ignores such cases.*

integer math in Go always returns an integer, thus this is straightforward.

```
package main
import(."fmt"."strconv")
func main(){a:=""
Scanln(&a)
x,_:=Atoi(a)
Printf((x/60),"hrs",(x%60),"mins")}
```

Ungolfed

```
package main

import (
    . "fmt"
    . "strconv"
)

func main() {
    a := ""
    Scanln(&a)
    x, _ := Atoi(a)
    Println((x / 60), "hrs", (x % 60), "mins")
}
```

# Answer
> 1 votes
# Arcyóu (non-competitive), 93 bytes

*This submission uses a version of the language that was created after this challenge.*

```
(: x(#((v(l))0)))(: h(#/ x 60))(: m(% x 60))(% "%d hour%s %d minute%s"(' h(* s([ h))m(* s([ m

```

Yeesh! This language needs better string manipulation.

Explanation:

```
(: x              ; Set x
  (#              ; Cast to int
    ((v (l)) 0))) ; First element of input split on spaces
(: h (#/ x 60))   ; Set h to the hours
(: m (% x 60))    ; Set m to the minutes
(%                ; String format
  "%d hour%s %d minute%s"
  ('              ; List
    h             ; Hours
    (* s([ h))    ; Evaluates to 's' if h is not 1
    m             ; Minutes
    (* s([ m      ; Evaluates to 's' is m is not 1

```

# Answer
> 1 votes
## Kotlin, 132 bytes

```
val m={s:String->val j=s.split(" ")[0].toInt();print("${j/60} hour${if(j/60==1)"" else "s"} ${j%60} minute"+if(j%60==1)"" else "s")}

```

Ungolfed Version:

```
val m = { s: String ->
    val j = s.split(" ")[0].toInt();
    print("${j / 60} hour${if(j / 60 == 1) "" else "s"} ${j % 60} minute" + if(j % 60 == 1) "" else "s")
}

```

Test it with:

```
fun main(args: Array<String>) {
    for(i in arrayOf(150, 90, 61, 60)) {
        m("$i min")
        println()
    }
}

```

Example outputs:

```
2 hours 30 minutes
1 hour 30 minutes
1 hour 1 minute
1 hour 0 minutes

```

# Answer
> 1 votes
## Java 8, 148 Bytes

```
interface S{static void main(String[]b){int a=new Integer(b[0]),h=a/60,m=a%60;System.out.printf(h+" hour%s "+m+" minute%s",h>1?"s":"",m>1?"s":"");}}

```

I chose to post an alternative to @TheAustralianBirdEatingLouse as this is not only shorter by a good deal (~10%) but also more correct in printing hour(s) and minutes(s) instead of abbreviated hrs and mins. Method implementations in Interfaces are new to Java 8 - so this would be needed to compile/run

# Answer
> 1 votes
# PHP, 110 100 96 bytes

```
$t=$argv[1];$h=intval($t/60);$m=$t-$h*60;echo"$h hour".($h>1?"s":"")." $m minute".($m>1?"s":"");

```

You can run it using `php -r`

`GET` parameters are no longer allowed(meta.codegolf.stackexchange.com/a/7591/14732 and meta.codegolf.stackexchange.com/q/7575/14732)

# Answer
> 1 votes
## Java - 143 141 139 bytes

Since functions are allowed, here is my take

```
void a(String a){int b=Integer.valueOf(a.split(" ")[0]),c=b/60,d=b%60;System.out.print(c+" hour"+(c>1?"s ":" ")+d+" minute"+(d>1?"s":""));}

```

---

## Ungolfed

```
void a(String a){
    int b=Integer.valueOf(a.split(" ")[0]),c=b/60,d=b%60;
    System.out.print(
            c+" hour"+(c>1?"s ":" ")+
            d+" minute"+(d>1?"s":"")
            );
}

```

---

## Input

```
a("59 mins");
a("121 mins");
a("239 mins");

```

## Output

```
0 hour 59 minutes
2 hours 1 minute
3 hours 59 minutes

```

# Answer
> 1 votes
# Mumps, 81 Bytes

```
R U S M=+U#60,H=+U\60 W H," hour",$S(H=1:" ",1:"s "),M," minute",$S(M=1:"",1:"s")

```

Ungolfed:

```
R U                 ; (R)ead from standard input
S M=+U#60,H=+U\60   ; S(et) M to integer (mod) Minutes and H to integer Hours
W H," hour",$S(H=1:" ",1:"s "),M," minute",$S(M=1:"",1:"s")
                    ; W(rite) H & hour, if H doesn't equal 1 pluralize;
                    ; same for M & minute(s).

```

Sorry for the initial submission - the formatting on my ungolfed wasn't quite right and I didn't realize at first that hitting 'tab' then 'space' in the editor window equated to "submit." :-)

# Answer
> 1 votes
## Prolog, 134 bytes

**Code:**

```
p(X):-sub_atom(X,0,_,4,S),atom_number(S,N),divmod(N,60,Q,R),(Q>1->I=s;I=""),(R=1->J="";J=s),writef('%w hour%w %w minute%w',[Q,I,R,J]).

```

**Explanation:**

```
p(X):-sub_atom(X,0,_,4,S),                       % Remove last 4 chars from input
      atom_number(S,N),                          % Convert to integer
      divmod(N,60,Q,R),                          % Split minutes into hours/minutes
      (Q>1->I=s;I=""),(R=1->J="";J=s),           % Check if hours/minutes are plural
      writef('%w hour%w %w minute%w',[Q,I,R,J]). % Print

```

**Example:**

```
p('150 min').
2 hours 30 minutes

```

# Answer
> 1 votes
# Pyth, 35 bytes

```
jds.b,N+WtNY\s.Ds-zG60c"hour minute

```

Try it online: Demonstration or Test Suite

### Explanation:

```
jds.b,N+WtNY\s.Ds-zG60c"hour minute  implicit: z = input string
                 -zG                 remove all letters from the string
                s                    and convert it (gives us the number)
              .D    60               gives [quotient, remainder] (division by 60)
                      c"hour minute  split "hour minute"
   .b                                map each pair (number N, string Y) to:
     ,                                  the pair
      N                                 [ N,
       +WtNY\s                               Y + "s" if N-1 ]
  s                                  join the two pairs
jd                                   join strings by spaces

```

# Answer
> 1 votes
# awk, 72 bytes

```
{printf"%d hour%s %d minute%s\n",h=$1/60,h~/^1/?_:"s",m=$1%60,1~m?_:"s"}

```

Basically just a `printf`, taking advantage of awks ability to compare numbers using regexp.

### input/output examples

```
0 min
0 hours 0 minutes
1 min
0 hours 1 minute
60 min
1 hour 0 minutes
61 min
1 hour 1 minute
121 min
2 hours 1 minute
122 min
2 hours 2 minutes

```

# Answer
> 1 votes
# Thunno 2 , 29 bytes

```
OhN60ḋDð‘ƝḢ Ạẋ‘O+ZıẸs1>'s×+;Z

```

Try it online!

#### Explanation

```
O          # Split on spaces
 hN        # Take the first item and convert to integer
   60ḋ     # Divmod by 60
      Dð   # Duplicate and push a space
‘ƝḢ Ạẋ‘    # Push compressed string "hour minute"
       O   # Split it on spaces
        +  # And prepend the space to each one
Z          # Zip it with the divmod list
 ı         # And map over this list of pairs:
  Ẹ        #  Dump onto the stack
   s       #  Swap so the number is on top
    1>     #  Is it greater than 1?
's        '#  Push the character "s"
  ×        #  Multiply by our boolean value
   +       #  Add to the string
    ;Z     # After the map, zip with the divmod list
           # Implicit output, joined by spaces

```

# Answer
> 0 votes
# Julia, ~~110~~ ~~99~~ 93 bytes

```
x->((h,m)=divrem(parse(x[1:end-4]),60);print("$h hour$(h>1?"s":"") $m minute$(m>1?"s":"")"))

```

This is an anonymous function that accepts a string and prints to STDOUT.

Ungolfed:

```
function f(x::AbstractString)
    # Parse the number of minutes out of the input
    y = parse(x[1:end-4])

    # Get the number of hours and minutes
    h, m = divrem(y, 60)

    # Construct the output using string interpolation
    print("$h hour$(h>1?"s":"") $m minute$(m>1?"s":"")")
end

```

# Answer
> 0 votes
# C++, 175 bytes

```
#include<iostream>
using namespace std;main(int argc,char**argv){int a=stoi(argv[1]);cout<<a/60<<" hour";if(a/60!=1)cout<<"s";cout<<" "<<a%60<<" minute";if(a%60!=1)cout<<"s";}

```

Ungolfed:

```
#include <iostream>
using namespace std;
main(int argc, char **argv)
{
   int a = stoi(argv[1]);
   cout << a / 60 << " hour";
   if(a / 60 != 1) cout << "s";
   cout << " " << a % 60 << " minute";
   if(a % 60 != 1) cout << "s";
}

```

Probably the only time that `std::stoi` truncating non-number characters will ever be useful, but it's enough to put C++ ahead of C, I think.

# Answer
> 0 votes
# Java, ~~107~~ ~~192~~ ~~160~~ ~~149~~ ~~129~~ ~~172~~ ~~162~~ 129 bytes

So, here's my solution:

```
void b(String[]a){int a=Integer.valueOf(a[0]);System.out.print(a/60>1?a/60+" hrs ":a/60+" hr "+a%60>1?a%60+" mins":a%60+" min");}

```

It uses command-line input, and works like this:

Java command example: javac MovieTime 108 minutes

Input: `108 minutes`

Output: `1 hr 48 mins`

### Changes:

* Changed the code to full class, adding 85 bytes
* Got rid of unnecessary whitespaces, subtracting 32 bytes
* Made variable/class names shorter, subtracting 11 bytes
* Made `Integer.valueOf(args[0])` into a variable and changed println into print, subtracting 20 bytes
* Added system for changing plurals of times, adding 43 bytes
* Made times shorter, subtracting 10 bytes
* Code is now a function instead of a class, subtracting 33 bytes

Any ideas as to how I can shorten it would be greatly appreciated, as this is my first golf submission.

# Answer
> 0 votes
# VBA, 175 bytes

```
Sub e(f)
f = Val(f)
h = Int(f / 60)
m = f - h * 60
MsgBox IIf(h > 0, h & " hour" & IIf(h > 1, "s", ""), "") & " " & IIf(m > 0, m & " minute" & IIf(m > 1, "s", ""), "")
End Sub

```

# Answer
> 0 votes
# Python 2, 102 bytes

```
a=int(raw_input().split()[0]);h=a/60;m=a%60;l="s\0";print"%s hour%s %s minute%s"%(h,l[h==1],m,l[m==1])

```

# Answer
> 0 votes
# Python 2: 56 bytes

### Golfed code

```
m=int(raw_input()[:3]);print m/60,'hours',m%60,'minutes'

```

### Readable code

```
# get input from STDIN
string_input = raw_input()
# parse number of minutes in the first three characters
minutes_input = string_input[:3]
# compute number of hours and remaining minutes
hours = minutes_input / 60
minutes = minutes_input % 60
# display result
print hours, 'hours', minutes, 'minutes'

```

### Try it online

https://ideone.com/HdTKRt

---

# Python 2: 80 bytes (with plurals handling)

### Golfed code

```
_,m='\0s',int(raw_input()[:3]);print m/60,'hour'+_[m>60],m%60,'minute'+_[m%60>1]

```

### Try it online

https://ideone.com/GuDCq0

# Answer
> 0 votes
# JavaScript 96

```
m=parseInt(prompt()),h=m/60|0,m%=60
alert(h+" hour"+(h!=1?"s ":" ")+m+" minute"+(m!=1?"s ":" "))
```

# Answer
> 0 votes
# Pyth, 41 bytes

```
A.Ds<4z60s[G" hour"?tG\skdH>4z"ute"?tH\s"

```

explanation

```
A                                          -Assign two values, first to `G` then to `H`
 .Ds   60                                  -DivMod on integer by 60
    <4z                                    -slice everything but the last 4 chars of input
         s[                                -print all following statements on one line
           G                               -hour
            " hour"                        -string literal
                   ?tG\sk                  -ternary, if hour is 1, 's' literal, else nothing
                         d                 -space
                          H                -minute
                           >4z             -get the last 4 chars of input (" min") (so sneaky)
                              "ute"        -string literal
                                   ?tH\s"  -ternary, as before but with minutes

```

# Answer
> 0 votes
# Milky Way 1.2.1, 63 bytes

```
'" "\=^A60m>?{1b_" "_"s "}" hour";+<?{1b_""_"s"}" minute";++++!

```

The program is too long to explain in detail here, but you can see the docs for an in-depth look.

---

### Usage

```
python3 milkyway.py <path-to-code> -i <input>

```

# Answer
> 0 votes
# Gema, 64 bytes

```
<N>=@p{@div{$1;60} hour} @p{@mod{$1;60} minute}
*=
p:1 *=$0;*=*s

```

Sample run:

```
bash-4.3$ gema '<N>=@p{@div{$1;60} hour} @p{@mod{$1;60} minute};*=;p:1 *=$0;*=*s' <<< '90 min'
1 hour 30 minutes

```

## Gema, 65 bytes

```
<N> min=@p{@div{$1;60} hour} @p{@mod{$1;60} minute}
p:1 *=$0;*=*s

```

This one replaces all “\d+ min” occurrences in the input string.

Sample run:

```
bash-4.3$ gema '<N> min=@p{@div{$1;60} hour} @p{@mod{$1;60} minute};p:1 *=$0;*=*s' <<< $'150 min\n90 min\n61 min\n60 min'
2 hours 30 minutes
1 hour 30 minutes
1 hour 1 minute
1 hour 0 minutes

```

# Answer
> 0 votes
# Factor, ~~95~~ 88 bytes

```
[ readln " " split first 10 >base [ 60 / floor ] [ 60 mod ] bi "%s hrs %s mins" printf ]

```

Like my Go answer, doesn't handle plurals because it doesn't have to.

# Answer
> 0 votes
## Pyke, 31 bytes, noncompeting

```
dchE60.D]~U1 3:],FDJRh1N\s*+)_J

```

Try it here!

Explanation:

```
dchE                            -     eval(input().split(" ")[0])
    60.D]                       -    [divmod(^, 60)]
               ],               -   zip(*[^,V])
         ~U1 3:                 -    ["minute", "hour"]
                 F          )   -  for _ in ^:
                     h1N        -     _[0] != 1
                        \s*     -    "s"*^
                           +    -    V+^
                   J            -     " ".join(_)
                             _J - " ".join(^[::-1])

```

---
Tags: code-golf, conversion
---


title: Reversing of Words

text:
# Question
Title: Reversing of Words
Sona is in her house with her 10 year old daughter. She needs to go to school to bring back another child from school, as school is over at 2 pm. It's hot outside, so she wants to leave her younger child at home.

She gave a bunch of strings to her child to keep her busy while she is gone. She asked her to reverse the words in the string. There are lot of strings, so you need to help her daughter in solving this huge task.

So, given a string that contains words separated by single space, reverse the words in the string. You can assume that no leading or trailing spaces are there.

The string will only contain `[a-zA-z ]`, so you don't need to handle punctuation.

You will be given a string as an input, and you should output a string.

### Sample Test Cases:

```
Input:
Man bites dog

Output:
dog bites Man

Input:
The quick brown fox jumps over the lazy dog

Output:
dog lazy the over jumps fox brown quick The

Input:
Hello world

Output:
world Hello

```

### Scoring

This is . Shortest answer in bytes wins.

# Answer
## Retina, 7 bytes

```
O$^`\w+

```

Try it online!

Match all words (`\w+`) sort them with sort key empty string (`O$`) which means they won't get sorted at all, and then reverse their order (`^`).
> 11 votes

# Answer
## Haskell, 21 bytes

```
unwords.reverse.words

```

Try it online!
> 10 votes

# Answer
# Python 3, 29 bytes

```
print(*input().split()[::-1])

```

Try it online!
> 10 votes

# Answer
# Bash + common Linux utilities, 21

```
printf "$1 "|tac -s\

```

Leaves a trailing space in the output string - not sure if that's OK or not.
> 8 votes

# Answer
# JavaScript (ES6), 31 bytes

```
s=>s.split` `.reverse().join` `

```

---

## Try it

```
f=
s=>s.split` `.reverse().join` `
o.innerText=f(i.value="Man bites dog")
oninput=_=>o.innerText=f(i.value)
```

```
<input id=i><pre id=o>
```
> 7 votes

# Answer
# Brachylog, 6 bytes

```
ṇ₁↔~ṇ₁

```

Try it online!

### Explanation

```
ṇ₁        Split on spaces
  ↔       Reverse
   ~ṇ₁    Join with spaces

```

Note that both "split on spaces" and "join wth spaces" use the same built-in, that is `ṇ₁`, just used in different "directions".
> 7 votes

# Answer
# Jelly, 3 bytes

```
ḲṚK

```

Try it online!

Explanation:

```
Ḳ     Splits the input at spaces
Ṛ     Reverses the array
K     Joins the array, using spaces

```
> 6 votes

# Answer
# R, 19 bytes

```
cat(rev(scan(,'')))

```

reads the string from stdin. By default, `scan` reads tokens separated by spaces/newlines, so it reads the words in as a vector. `rev` reverses, and `cat` prints the elements with spaces.

Try it online!
> 6 votes

# Answer
# C#, 58 bytes

```
using System.Linq;s=>string.Join(" ",s.Split().Reverse());

```
> 4 votes

# Answer
# C, ~~54~~ 48 bytes

**Using arguments as input, 48 bytes**

```
main(c,v)char**v;{while(--c)printf("%s ",v[c]);}

```

*Try Online*

```
> ./a.out man bites dog

```

**Using pointers, 84 bytes**

```
f(char*s){char*t=s;while(*t)t++;while(t-s){while(*t>32)t--;*t=0;printf("%s ",t+1);}}

```

*Use*

```
main(){ f("man bites dog"); }

```
> 4 votes

# Answer
# 05AB1E, 4 bytes

```
#Rðý

```

Note: Will only work for 2 or more words. +1 byte if this is not OK.

Try it online!
> 3 votes

# Answer
# GNU Make, 62 bytes

```
$(if $1,$(call $0,$(wordlist 2,$(words $1),$1)) $(word 1,$1),)

```
> 3 votes

# Answer
# brainfuck, 74 bytes

```
,[>++++[<-------->-],]<[>++++[->--------<]+>[[<]>[+>]<]<-[<]>[.>]<[[-]<]<]

```

Try it online!

This code creates the number -32 in two different places, but that seems to be fewer bytes than trying to maintain a single -32.

### Explanation

```
,[                        input first character
  >++++[<-------->-]      subtract 32 from current character (so space becomes zero)
,]                        repeat for all characters in input
<                         go to last character of last word
[                         while there are more words to display:
 >++++[->--------<]       create -32 two cells right of last letter
 +>                       increment trailing space cell (1 right of last letter) so the next loop works
 [[<]>[+>]<]              add 32 to all cells in word and trailing space cell
 <-                       subtract the previously added 1 from the trailing space
 [<]>                     move pointer to beginning of word
 [.>]<                    output word (with trailing space)
 [[-]<]                   erase word
 <                        move to last character of previous word
]

```
> 3 votes

# Answer
# Cubix, 48 bytes

Almost gave up on this one, but finally got there.

```
oU_;SW;@?ABu>):tS-?;\0$q^s.$;;<$|1osU!(;;...<#(1

```

Try it online!

This maps onto a cube with a side length of three as follows

```
      o U _
      ; S W
      ; @ ?
A B u > ) : t S - ? ; \
0 $ q ^ s . $ ; ; < $ |
1 o s U ! ( ; ; . . . <
      # ( 1
      . . .
      . . .

```

The general steps are:

* Get all input `A` and reverse `B` stack
* Move the negative `q` to the bottom, add a counter `0` to the stack. bit of jumping around in here.
* Find space/end loop, also puts stack in correct print order.
    + Increment counter `)` and fetch the counter item from the stack `t`
    + Is it a space or EOI `S-?`
    + Repeat if not
* Print word loop
    + Decrement counter `(`
    + Exit loop if counter `!U` is 0
    + Swap `s` counter with character on stack
    + Print `o` character and pop it from the stack `;`
    + Repeat loop
* Get the length of the stack `#` and decrement `(`
* Check `?` if 0 and exit `@` if it is 0
* Otherwise print a space `So` clean up `;;` and go back to the first loop.

I've skipped a number of superfluous steps, but you can see it Step By Step
> 3 votes

# Answer
# Japt, ~~11~~ ~~10~~ ~~7~~ 4 bytes

My first attempt at Japt.

```
¸w ¸

```

Try it online

---

## Explanation

```
    :Implicit input of string U
¸   :Split on <space>
w   :Reverse
¸   :Join with <space>

```

---

Please share your Japt tips here.
> 3 votes

# Answer
# Python 2, 34 bytes

```
lambda s:' '.join(s.split()[::-1])

```

Try it online!
> 2 votes

# Answer
# Pyth, 4 bytes

```
jd_c

```

Try it online!
> 2 votes

# Answer
# PHP, 47 Bytes

```
<?=join(" ",array_reverse(explode(" ",$argn)));

```

Try it online!
> 2 votes

# Answer
# Röda, ~~27~~ 25 bytes

*2 bytes saved thanks to @fergusq*

```
{[[split()|reverse]&" "]}

```

Try it online!

This function takes input from the input stream.

### Explanation (outdated)

```
{[[(_/" ")()|reverse]&" "]}           /* Anonymous function */
   (_/" ")                            /* Pull a value from the stream and split it on spaces */
          ()                          /* Push all the values in the resulting array to the stream */
            |reverse                  /* And reverse it */
  [                 ]                 /* Wrap the result into an array*/
                     &" "             /* Concatenate each of the strings in the array with a space */
 [                       ]            /* And push this result to the output stream */

```
> 2 votes

# Answer
# k, 9 bytes

```
" "/|" "\

```

Try it in your browser of the web variety!

```
     " "\ /split on spaces
    |     /reverse
" "/      /join with spaces

```
> 2 votes

# Answer
## Mathematica, 35 bytes

```
StringRiffle@Reverse@StringSplit@#&

```

Try it online!
> 2 votes

# Answer
# J-uby, 23 bytes

```
:split|:reverse|~:*&' '

```

### Explanation

```
:split   # split by spaces
|        # then
:reverse # reverse
|        # then
~:*&' '  # join with spaces

```
> 2 votes

# Answer
# Vim, 20 bytes

```
:s/ /\r/g|g/^/m0<cr>vGJ

```

This is shorter than the other vim answer.

Try it online!
> 2 votes

# Answer
# Pyth, 3 bytes

```
_cw

```

My first Pyth answer, one byte shorter than @notjagan's answer!

Explained:

```
 cw # Split the input by space (same as Python's string.split())
_   # Reverses the array
    # Pyth prints implicitly.

```
> 2 votes

# Answer
# Zsh, 13 bytes

```
echo ${(Oa)@}

```

Try it online!
> 2 votes

# Answer
# TAESGL, 7 bytes

```
ĴS)Ř)ĴS

```

**Interpreter**

**Explanation**

```
 ĴS)Ř)ĴS
AĴS)        implicit input "A" split at " "
    Ř)      reversed
      ĴS    joined with " "

```
> 1 votes

# Answer
# CJam, 7 bytes

```
qS/W%S*

```

Try it online!

**Explanation**

```
q        e# Read input
 S/      e# Split on spaces
   W%    e# Reverse
     S*  e# Join with spaces

```
> 1 votes

# Answer
# Ohm, 4 bytes

```
z]Qù

```

Try it online!

**Explanation**

```
z     Split the input on spaces.
 ]    Dump it onto the stack.
  Q   Reverse the stack.
   ù  Join the stack with spaces. Implicit output.

```
> 1 votes

# Answer
# , 6 bytes

```
|.&.;:

```

Try it online! This is reverse (`|.`) under (`&.`) words (`;:`). That is, split sentence into words, reverse it, and join the sentence again.
> 1 votes

# Answer
# Java 8, 62 bytes

```
s->{String r="";for(String x:s.split(" "))r=x+" "+r;return r;}

```

Try it here.

# Java 7, 77 bytes

```
String c(String s){String r="";for(String x:s.split(" "))r=x+" "+r;return r;}

```

Try it here.
> 1 votes

# Answer
# Gema, 29 characters

```
<W><s>=@set{o;$1 ${o;}}
\Z=$o

```

Sample run:

```
bash-4.4$ gema '<W><s>=@set{o;$1 ${o;}};\Z=$o' <<< 'Man bites dog'
dog bites Man

```
> 1 votes

# Answer
# jq, 27 characters

(23 characters code + 4 characters command line options)

```
./" "|reverse|join(" ")

```

Sample run:

```
bash-4.4$ jq -Rr './" "|reverse|join(" ")' <<< 'Man bites dog'
dog bites Man

```

On-line test
> 1 votes

# Answer
# Java 8, 53 ~~57~~ bytes

Lambda + Stream API

```
s->Stream.of(s.split(" ")).reduce("",(a,b)->b+" "+a)

```

Following Selim suggestion, we just dropped 4 bytes
> 1 votes

# Answer
# Perl 6, 14 bytes

```
{~[R,] .words}

```

Try it

## Expanded:

```
{              # lambda with implicit param $_

  ~            # stringify following (joins a list using spaces)

   [R,]        # reduce the following using the Reverse meta operator

        .words # call the words method on $_
}

```
> 1 votes

# Answer
# Wren, 40 bytes

```
Fn.new{|a|a.split(" ")[-1..0].join(" ")}

```

Try it online!

## Explanation

```
Fn.new{|a|                             } // Anonymous function with the parameter a
          a.split(" ")                   // Split on spaces
                      [-1..0]            // Reverse the array
                             .join(" ")  // Join the array with spaces

```
> 1 votes

# Answer
# GNU sed 4.2.2, 34 bytes

Score includes +1 for `-r` passed to GNU sed.

```
:
s/(\w*) ([^:]*)/\2:\1/
t
y/:/ /

```

Try it online!

Another answer, 38 bytes:

```
s/^/:/
:
s/:(.*) (.*)/\2 :\1/
t
s/://

```

Try it online!
> 1 votes

# Answer
# Vyxal, 3 bytes

```
⌈ṘṄ

```

Try it Online!
> 1 votes

# Answer
# Thunno 2 , 2 bytes

```
Or

```

Try it online!

#### Explanation

```
    # Implicit input
O   # Split on spaces
 r  # Reverse
    # Join on spaces
    # Implicit output

```
> 1 votes

# Answer
# Cheddar, 26 bytes

3 bytes thanks to Conor O'Brien

```
@.split(" ").rev.join(" ")

```

Try it online!
> 0 votes

# Answer
# AWK, ~~30~~ 28 bytes

```
{for(;++i<=NF;)s=$i" "s}$0=s

```

Try it online!

Thanks, manatwork, for catching my needless fluff. :)
> 0 votes

# Answer
# Lua, ~~66~~ 42 bytes

```
for i=#...,1,-1 do
io.write(arg[i],' ')end

```

Try it online!
> 0 votes

# Answer
# Ruby, 23+1 = 24 bytes bytes

Uses the `-p` flag.

```
$_=$_.split.reverse*' '

```

Try it online!
> 0 votes

# Answer
# Stacked, 17 bytes

```
' 'split rev' '#`

```

Try it online!

`#`` is "join".
> 0 votes

# Answer
# MATL, 5 bytes

```
YbPZc

```

Try it at MATL Online!

**Explanation**

```
    % Implicitly grab input as a string
Yb  % Split it on all of the spaces, yielding a cell array of words
P   % Flip this array
Zc  % Join these words back together with spaces
    % Implicitly display the result

```
> 0 votes

# Answer
# Scala, 37 bytes

```
s=>s.split(" ").reverse.mkString(" ")

```

Try it here.
> 0 votes

# Answer
# Vim, 49 42 bytes

```
:s/.*/\=join(reverse(split(submatch(0))))/

```

Thank you to @manatwork for feedback
> 0 votes

# Answer
# **Ruby, ~~27~~ 24 bytes**

*thanks to @manatwork*

```
->a{a.split.reverse*" "}

```
> 0 votes

# Answer
# Swift, 116 bytes

```
var r:(String)->String={return $0.characters.split(separator:" ").map(String.init).reversed().joined(separator:" ")}

```

You can try it here
> 0 votes

# Answer
# Clojure(script), 57 bytes

```
#(apply str(interpose" "(reverse(re-seq #"[a-zA-Z]+"%))))

```
> 0 votes

# Answer
# tcl, 18

```
puts [lreverse $S]

```

# demo
> 0 votes

# Answer
# tcl, 11

```
lreverse ""
          ^
          |
          Put the string you want to test here between the ""

```

Can be tested on http://www.tutorialspoint.com/execute\_tcl\_online.php starting the tcl interpreter by typing `tclsh`. Then type

```
lreverse "Man bites dog"

```

%

```
lreverse "The quick brown fox jumps over the lazy dog"

```

%

```
lreverse "Hello world"

```
> 0 votes

# Answer
# PowerShell Core, ~~45~~ 29 bytes

```
$args|%{$r=,$_+$r}
$r-join' '

```

Try it online!

*-16 bytes thanks to mazzy!*
> 0 votes

---
Tags: code-golf, string, whitespace
---


title: Run Length Decoding

text:
# Question
Title: Run Length Decoding
Write the shortest code in the language of your choice to perform run length decoding of the given string.

The string will be supplied as **input on stdin** in the form

```
CNCNCNCNCNCNCNCN

```

where each `C` could be any printable ASCII character and each `N` is a digit `1` to `9` (inclusive).

Sample input:

```
:144,1'1

```

Corresponding output:

```
:4444,'

```

# Answer
# Brainfuck, 34 characters

```
,[>,>++++++[<-------->-]<[<.>-]<,]

```
> 30 votes

# Answer
# Shakespeare Programming Language, 406 bytes

```
.
Ajax,.
Ford,.
Act I:.
Scene I:.
[Enter Ajax and Ford]
Scene II:.
Ford:
Open your mind.Is sky nicer than you?If so, let us return to scene IV.
Ajax:
Open your mind.You is sum you and sum big big big big big big pig and big big big big cat!
Scene III:.
Ford:
Speak thy mind.
Ajax:
You is sum you and pig!Is you as big as zero?If so, let us return to scene II.Let us return to scene III.
Scene IV:.
[Exeunt]

```

Ungolfed version:

```
The Decoding of the Lengths of Veronan Runs - A Drama of PPCG.

Romeo, quite a character.
Juliet, Romeo's lover and multiplicand.

Act I: In which the lengths of runs are decoded.

Scene I: A silent entrance.

[Enter Romeo and Juliet]

Scene II: In which neither Romeo nor Juliet believes the other open-minded.

Juliet:
  Open your mind. Is my mother jollier than thou? If so,
  we must proceed to scene IV.

Romeo:
  Open your mind. Thou art the sum of thyself and the sum of my good aunt and
  the difference between nothing and the quotient of the square of twice the sum
  of thy foul fat-kidneyed goat and thy death and thy evil variable!

Scene III: In which Romeo snaps and brutally insults Juliet.

Juliet:
  Speak thy mind.

Romeo:
  Thou art the sum of thyself and a hog! Art thou as rotten as nothing? If so,
  let us return to scene II. Let us return to scene III.

Scene IV: Finale.

[Exeunt]

```

I'm using drsam94's Python SPL compiler, which has a few bugs (which is why, for instance, I use `Open your mind` instead of `Open thy mind` in the golfed version).

To run this program, use:

```
$ python splc.py rld.spl > rld.c
$ gcc rld.c -o rld.exe
$ echo -n ":144,1'1" | ./rld
:4444,'

```

## How it works

SPL is an esoteric programming language designed to make programs look like Shakespeare plays. It does this by using characters as variables, and processing is performed by having the characters say things to one another.

```
The Decoding of the Lengths of Veronan Runs - A Drama of PPCG.

```

This is the title of the play; it's ignored by the compiler.

```
Romeo, quite a character.
Juliet, Romeo's lover and multiplicand.

```

Here we're declaring the variables used in the rest of the program. Everything betwen `,` and `.` is ignored by the compiler. In this case, we declare `Romeo`, used to hold the character being decoded, and `Juliet`, used to hold the run length of the character.

```
Act I: In which the lengths of runs are decoded.

```

Here we declare the first and only act in the program. Acts and scenes are like labels; they can be jumped to at any time by using `let us return to scene II` or some variant of that. We only use one act, because it's sufficient for our needs. Again, anything between `:` and `.` is ignored by the compiler.

```
Scene I: A silent entrance.

```

Here we declare the first scene. Scenes are numbered in Roman numerals: the first is `Scene I`, the second `Scene II`, and so on.

```
[Enter Romeo and Juliet]

```

This is a stage direction; in it, we tell the `Romeo` and `Juliet` variables to come onto the "stage". Only two variables can be on the "stage" at once; the stage is used so that the compiler can figure out which variable is addressing which when they speak. Because we have only two variables, Romeo and Juliet will stay onstage for the length of the program.

```
Scene II: In which neither Romeo nor Juliet believes the other open-minded.

```

Another scene declaration. Scene II will be jumped to in order to decode another run-length.

```
Juliet:

```

This form of declaration means that Juliet is going to start speaking. Everything until the next `Romeo:`, stage direction, or scene/act declaration will be a line spoken by Juliet, and thus "me" will refer to Juliet, "you"/"thou" to Romeo, etc.

```
Open your mind.

```

This command stores the ordinal value of single character from STDIN in `Romeo`.

```
Is my mother jollier than thou?

```

In SPL, nouns translate to either 1 or -1 depending on whether they are positive or negative. In this case, `my mother` translates to 1. Adjectives (positive or negative) multiply their noun by 2.

This is a question; in it, Juliet asks if `my mother` (AKA 1) is "jollier" than Romeo. Comparatives either translate to `less than` (if they are negative, like `worse`) or `greater than` (if they are positive, like `jollier`). Therefore, this question boils down to `Is 1 greater than you?`.

The reason we ask this question is to detect the end of the input. Since the value of `EOF` varies by platform, but is usually less than 1, we use this to detect it.

```
If so, we must proceed to scene IV.

```

If the preceding question evaluated to `true`, we jump to scene IV—which is simply the end of the program. In short, if we detect an EOF, we end the program.

```
Romeo:

```

It's now Romeo's line: "me" and "you" refer to Romeo and Juliet, respectively.

```
Open your mind.

```

Again, this statement puts the ordinal value of a single character from STDIN into Juliet, which in this case is the run-length of the character stored in `Romeo`.

```
Thou art the sum of thyself and the sum of my good aunt and the difference
between nothing and the quotient of the square of twice the sum of thy foul
fat-kidneyed goat and thy death and thy evil variable!

```

This one's too long to go over in great detail, but just trust me in that it translates to `Juliet -= 48`. We do this because Juliet holds the ASCII value of a numeral, and `ord('0') == 48`; in subtracting 48, we translate from the ASCII value of a number to the number itself.

```
Scene III: In which Romeo snaps and brutally insults Juliet.

```

Another scene declaration. This one is for the loop in which we repeatedly print the character value of `Romeo`, `Juliet` times.

```
Juliet:
  Speak thy mind.

```

This statement causes Romeo to print his value as a character; that is, whatever character value was previously stored in Romeo is now output.

```
Romeo:
  Thou art the sum of thyself and a hog!

```

A hog is a negative noun, so `a hog` translates to -1; therefore, this statement evaluates to `Juliet -= 1`.

```
Art thou as rotten as nothing?

```

Romeo here asks if Juliet is "as rotten as", or equal to, 0.

```
If so, let us return to scene II.

```

If Juliet's value is 0, we loop back to scene II to decode another character's run-length.

```
Let us return to scene III.

```

Else, we loop back to scene III to output Romeo's character again.

```
Scene IV: Finale.

[Exeunt]

```

This final scene declaration is just a marker for the end of the program. The `[Exeunt]` stage direction is necessary to get the compiler to actually generate the final scene.
> 14 votes

# Answer
### GolfScript, 10 characters

```
2/{1/~~*}/

```
> 6 votes

# Answer
# perl, 27 characters

```
print<>=~s/(.)(.)/$1x$2/ger

```
> 5 votes

# Answer
## Python 3, 52

Python 3 allows me to merge the approaches of my two python2 solutions.

```
s=input()
t=''
while s:a,b,*s=s;t+=a*int(b)
print(t)

```
> 5 votes

# Answer
## R 67

```
x=strsplit(readline(),"")[[1]];cat(rep(x[c(T,F)],x[c(F,T)]),sep="")

```
> 4 votes

# Answer
# Malbolge Unshackled (20-trit rotation variant), 4,494e6 bytes

Size of this answer exceeds maximum postable program size (eh), so the code is located in my GitHub repository.

## How to run this?

This might be a tricky part, because naive Haskell interpreter will take ages upon ages to run this. TIO has decent Malbogle Unshackled interpreter, but sadly I won't be able to use it (limitations).

The best one I could find is the fixed 20-trit rotation width variant, that performs very well, **decompressing 360 bytes per hour**.

To make the interpreter a bit faster, I've removed all the checks from Matthias Lutter's Malbolge Unshackled interpreter.

My modified version can run around 6,3% faster.

```
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char* translation = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72Fh"
        "OA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@";

typedef struct Word {
    unsigned int area;
    unsigned int high;
    unsigned int low;
} Word;

void word2string(Word w, char* s, int min_length) {
    if (!s) return;
    if (min_length < 1) min_length = 1;
    if (min_length > 20) min_length = 20;
    s[0] = (w.area%3) + '0';
    s[1] = 't';
    char tmp[20];
    int i;
    for (i=0;i<10;i++) {
        tmp[19-i] = (w.low % 3) + '0';
        w.low /= 3;
    }
    for (i=0;i<10;i++) {
        tmp[9-i] = (w.high % 3) + '0';
        w.high /= 3;
    }
    i = 0;
    while (tmp[i] == s[0] && i < 20 - min_length) i++;
    int j = 2;
    while (i < 20) {
        s[j] = tmp[i];
        i++;
        j++;
    }
    s[j] = 0;
}

unsigned int crazy_low(unsigned int a, unsigned int d){
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    int position = 0;
    unsigned int output = 0;
    while (position < 10){
        unsigned int i = a%3;
        unsigned int j = d%3;
        unsigned int out = crz[i+3*j];
        unsigned int multiple = 1;
        int k;
        for (k=0;k<position;k++)
            multiple *= 3;
        output += multiple*out;
        a /= 3;
        d /= 3;
        position++;
    }
    return output;
}

Word zero() {
    Word result = {0, 0, 0};
    return result;
}

Word increment(Word d) {
    d.low++;
    if (d.low >= 59049) {
        d.low = 0;
        d.high++;
        if (d.high >= 59049) {
            fprintf(stderr,"error: overflow\n");
            exit(1);
        }
    }
    return d;
}

Word decrement(Word d) {
    if (d.low == 0) {
        d.low = 59048;
        d.high--;
    }else{
        d.low--;
    }
    return d;
}

Word crazy(Word a, Word d){
    Word output;
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    output.area = crz[a.area+3*d.area];
    output.high = crazy_low(a.high, d.high);
    output.low = crazy_low(a.low, d.low);
    return output;
}

Word rotate_r(Word d){
    unsigned int carry_h = d.high%3;
    unsigned int carry_l = d.low%3;
    d.high = 19683 * carry_l + d.high / 3;
    d.low = 19683 * carry_h + d.low / 3;
    return d;
}

// last_initialized: if set, use to fill newly generated memory with preinitial values...
Word* ptr_to(Word** mem[], Word d, unsigned int last_initialized) {
    if ((mem[d.area])[d.high]) {
        return &(((mem[d.area])[d.high])[d.low]);
    }
    (mem[d.area])[d.high] = (Word*)malloc(59049 * sizeof(Word));
    if (!(mem[d.area])[d.high]) {
        fprintf(stderr,"error: out of memory.\n");
        exit(1);
    }
    if (last_initialized) {
        Word repitition[6];
        repitition[(last_initialized-1) % 6] =
                ((mem[0])[(last_initialized-1) / 59049])
                    [(last_initialized-1) % 59049];
        repitition[(last_initialized) % 6] =
                ((mem[0])[last_initialized / 59049])
                    [last_initialized % 59049];
        unsigned int i;
        for (i=0;i<6;i++) {
            repitition[(last_initialized+1+i) % 6] =
                    crazy(repitition[(last_initialized+i) % 6],
                        repitition[(last_initialized-1+i) % 6]);
        }
        unsigned int offset = (59049*d.high) % 6;
        i = 0;
        while (1){
            ((mem[d.area])[d.high])[i] = repitition[(i+offset)%6];
            if (i == 59048) {
                break;
            }
            i++;
        }
    }
    return &(((mem[d.area])[d.high])[d.low]);
}

unsigned int get_instruction(Word** mem[], Word c,
        unsigned int last_initialized,
        int ignore_invalid) {
    Word* instr = ptr_to(mem, c, last_initialized);
    unsigned int instruction = instr->low;
    instruction = (instruction+c.low + 59049 * c.high
            + (c.area==1?52:(c.area==2?10:0)))%94;
    return instruction;
}

int main(int argc, char* argv[]) {
    Word** memory[3];
    int i,j;
    for (i=0; i<3; i++) {
        memory[i] = (Word**)malloc(59049 * sizeof(Word*));
        if (!memory) {
            fprintf(stderr,"not enough memory.\n");
            return 1;
        }
        for (j=0; j<59049; j++) {
            (memory[i])[j] = 0;
        }
    }
    Word a, c, d;
    unsigned int result;
    FILE* file;
    if (argc < 2) {
        // read program code from STDIN
        file = stdin;
    }else{
        file = fopen(argv[1],"rb");
    }
    if (file == NULL) {
        fprintf(stderr, "File not found: %s\n",argv[1]);
        return 1;
    }
    a = zero();
    c = zero();
    d = zero();
    result = 0;
    while (!feof(file)){
        unsigned int instr;
        Word* cell = ptr_to(memory, d, 0);
        (*cell) = zero();
        result = fread(&cell->low,1,1,file);
        if (result > 1)
            return 1;
        if (result == 0 || cell->low == 0x1a || cell->low == 0x04)
            break;
        instr = (cell->low + d.low + 59049*d.high)%94;
        if (cell->low == ' ' || cell->low == '\t' || cell->low == '\r'
                || cell->low == '\n');
        else if (cell->low >= 33 && cell->low < 127 &&
                (instr == 4 || instr == 5 || instr == 23 || instr == 39
                    || instr == 40 || instr == 62 || instr == 68
                    || instr == 81)) {
            d = increment(d);
        }
    }
    if (file != stdin) {
        fclose(file);
    }
    unsigned int last_initialized = 0;
    while (1){
        *ptr_to(memory, d, 0) = crazy(*ptr_to(memory, decrement(d), 0),
                *ptr_to(memory, decrement(decrement(d)), 0));
        last_initialized = d.low + 59049*d.high;
        if (d.low == 59048) {
            break;
        }
        d = increment(d);
    }
    d = zero();

    unsigned int step = 0;
    while (1) {
        unsigned int instruction = get_instruction(memory, c,
                last_initialized, 0);
        step++;
        switch (instruction){
            case 4:
                c = *ptr_to(memory,d,last_initialized);
                break;
            case 5:
                if (!a.area) {
                    printf("%c",(char)(a.low + 59049*a.high));
                }else if (a.area == 2 && a.low == 59047
                        && a.high == 59048) {
                    printf("\n");
                }
                break;
            case 23:
                a = zero();
                a.low = getchar();
                if (a.low == EOF) {
                    a.low = 59048;
                    a.high = 59048;
                    a.area = 2;
                }else if (a.low == '\n'){
                    a.low = 59047;
                    a.high = 59048;
                    a.area = 2;
                }
                break;
            case 39:
                a = (*ptr_to(memory,d,last_initialized)
                        = rotate_r(*ptr_to(memory,d,last_initialized)));
                break;
            case 40:
                d = *ptr_to(memory,d,last_initialized);
                break;
            case 62:
                a = (*ptr_to(memory,d,last_initialized)
                        = crazy(a, *ptr_to(memory,d,last_initialized)));
                break;
            case 81:
                return 0;
            case 68:
            default:
                break;
        }

        Word* mem_c = ptr_to(memory, c, last_initialized);
        mem_c->low = translation[mem_c->low - 33];

        c = increment(c);
        d = increment(d);
    }
    return 0;
}

```

## It's working!
> 4 votes

# Answer
## APL (22)

```
,/{⍺/⍨⍎⍵}/↑T⊂⍨~⎕D∊⍨T←⍞

```

Explanation:

* `T←⍞`: store input in `T`
* `T⊂⍨~⎕D∊⍨T`: split `T` on those characters that aren't digits
* : turn it into a `2`-by-`N/2` matrix
* `{⍺/⍨⍎⍵}/`: on each row of the matrix (`/`), replicate (`/`) the first character () by the eval () of the second character ()
* `,/`: concatenate the output of each row
> 3 votes

# Answer
# Ruby, 30 bytes

```
gsub!(/(.)(.)/){$1*$2.to_i}

```

27 bytes code + 3 bytes to run it with the `-p` flag:

```
$ ruby -p rld.rb <<< ":144,1'1"
:4444,'

```
> 3 votes

# Answer
**8086 assembly, 106 98 characters**

```
l:
mov ah,8
int 21h
mov bl,al
int 21h
sub al,48
mov cl,al
xor ch,ch
mov al,bl
mov ah,14
p:
int 10h
loop p
jmp l

```

If the numbers were before the characters in the input stream, two lines (18 characters) could be shaved off of this.
> 2 votes

# Answer
## GNU SED, 122 + 2 (-r)

```
#n
s/.*/\n&\a987654321\v\v\v\v\v\v\v\v\v/
:a
s/\n(.)(.)(.*\a.*\2.{9}(.*))/\1\n\4\3/
tb
bc
:b
s/(.)\n\v/\1\1\n/
tb
ba
:c
P

```

Needs to be run with the `-r` flag
May be reduced to 110 + 2 by replacing `\v` with the unprintable `0x0B` and `\a` with `0x07`
> 2 votes

# Answer
## C, 65 chars

Gets the input as a parameter.

```
main(p,v)char*p,**v;{
    for(p=v[1];*p;--p[1]<49?p+=2:0)putchar(*p);
}

```
> 2 votes

# Answer
## Perl, ~~19~~ 18 characters

```
perl -pe 's/(.)(.)/$1x$2/ge'

```

The rules for counting switches on the command-line are here.
> 2 votes

# Answer
# Haskell, ~~58~~ 56 characters

```
f[]=[]
f(x:y:s)=replicate(read[y])x++f s
main=interact$f

```

My first real attempt at golfing anything, so there's probably some improvement to be made here.
> 2 votes

# Answer
# Forth, 45 characters

```
BEGIN KEY KEY 48 - 0 DO DUP EMIT LOOP 0 UNTIL

```

Tested with pforth on OS X.
> 2 votes

# Answer
# C, 68 characters

@ugoren's answer in C is slightly shorter, but this answer complies with the requirement that "the string will be supplied as input on **stdin**."

```
n;main(c){for(;;){c=getchar(),n=getchar()-48;while(n--)putchar(c);}}

```
> 2 votes

# Answer
# Python, ~~63~~ 62 characters

```
print''.join([c*int(n)for c,n in zip(*[iter(raw_input())]*2)])

```
> 2 votes

# Answer
## Windows PowerShell, 55 chars

```
-join((read-host)-split'(..)'|%{(""+$_[0])*(""+$_[1])})

```

I get the feeling that this can be golfed down more, specifically with the casts from char to string and int, but I don't have the time to keep working on it right now.
> 2 votes

# Answer
# 05AB1E, ~~6~~ 5 bytes

```
2ι`ÅΓ

```

-1 byte thanks to *@Grimy*.

Outputs as a list of characters.

Try it online.

**Old 6 bytes answer without run-length decode builtin:**

```
2ôε`×?

```

Try it online.

**Explanation:**

```
2ι      # Uninterleave the (implicit) input-string in two parts
        #  i.e. ":144,1'3" → [":4,'","1413"]
  `     # Push both separated to the stack
   ÅΓ   # Run-length decode
        #  i.e. ":4,'" and "1413" → [":","4","4","4","4",",","'","'","'"]
        # (after which the result is output implicitly)

2ô      # Split the (implicit) input-string into parts of size 2
        #  i.e. ":144,1'3" → [":1","44",",1","'3"]
  ε     # Loop over each of these pairs:
   `    #  Push both characters separated to the stack
    ×   #  Repeat the first character the digit amount of times as string
        #   i.e. "'" and "3" → "'''"
     ?  #  And print it without trailing newline

```
> 2 votes

# Answer
# Japt `-P`, 8 bytes

Input as an array of characters, output as a string.

```
ò crÈpY°

```

Try it

```
ò crÈpYn     :Implicit input of character array
ò            :Groups of 2
   r         :Reduce each pair
    È        :By passing them through the following function as [X,Y]
     p       :  Repeat X
      Yn     :    Y, converted to an integer, times
             :Implicitly join and output

```
> 2 votes

# Answer
# Thunno 2 `J`, 4 bytes

```
d^N×

```

Try it online!

#### Explanation

```
d^N×  # Implicit input      ->  ":144,1'1"
d     # Cast to characters  ->  [":","1","4","4",",","1","'","1"]
 ^    # Uninterleave        ->  [":","4",",","'"]  ["1","4","1","1"]
  N   # Cast to integer     ->  [":","4",",","'"]  [1,4,1,1]
   ×  # Multiply together   ->  [":","4444",",","'"]
      # Implicit output     ->  :4444,'

```
> 2 votes

# Answer
**Python, 78 72 66 char**

```
d=raw_input()
print"".join([x*int(d[i+1])for i,x in enumerate(d)if~i&1])

```

```
s=raw_input()
print"".join(i*int(j)for i,j in zip(s[::2],s[1::2]))

```
> 1 votes

# Answer
### GolfScript (10 chars)

```
2/{)15&*}/

```
> 1 votes

# Answer
# J - 24

```
;@(_2(<@#~".)/\])@1!:1 3

```

The point of this submission is to use the infix adverb.
> 1 votes

# Answer
## Python 2, 58

This is inspired by Darren Stone's python solution -- iterator abuse!

```
x=iter(raw_input())
print''.join(a*int(next(x))for a in x)

```

This is my original solution (60 chars)

```
s=raw_input()
t=''
while s:t+=s[0]*int(s[1]);s=s[2:]
print t

```

A different approach is 3 chars longer:

```
f=lambda a,b,*x:a*int(b)+(x and f(*x)or'')
print f(raw_input())

```
> 1 votes

# Answer
## Befunge, 49 chars

```
>~:25*-      v
$>\1-:v:-*68~_@
$^ ,:\_v
^      <

```
> 1 votes

# Answer
# K, 35

```
{,/(#).'|:'"*I"$/:(2*!-_-(#x)%2)_x}

```
> 1 votes

# Answer
Java: 285 charas

```
import java.util.Scanner;public class A{public static void main(String args[]){Scanner s = new Scanner(System.in);while(s.hasNext()){String t=s.next();for(int i=0;i<t.length();i++) {for(int j=0; j<(Byte.valueOf(t.substring(i+1,i+2)));j++){System.out.print(t.substring(i,i+1));}i++;}}}}

```
> 1 votes

# Answer
## Befunge-98, 22 chars

```
>#@~~"0"-v
^#:\,:\-1<_

```
> 1 votes

# Answer
## Whitespace, 135

```
LSSSLSSSSLSLSTLTSTTTSLSSSSTSSSSLTSSTLTTTTLSSSSLSLSTLTSTTTSSSTTSSSSLTSSTLSSSSLSLSLTSTLSSSTLTSSTSTSSTLTLSSLSLSSLLSSTLSLLSLLLSLSLLSSTTLLLL

```

(Replace S,T,L with Space,Tab,Linefeed characters.)

Try it online \[here\].

Explanation:

```
"assembly"      whitespace                                      stack
----------      ----------                                      -----
s:              LSS SL      ;input loop                         []
    push 0      SS SSL                                          [0]
    dup         SLS                                             [0,0]
    getc        TLTS        ;input & store char c               [0]
    rcl         TTT         ;recall c                           [c]
    dup         SLS                                             [c,c]
    push 16     SS STSSSSL                                      [c,c,16]
    sub         TSST                                            [c,c-16]
    jlt  tt     LTT TTL     ;exit if ord(c) < 16                [c]
    push 0      SS SSL                                          [c,0]
    dup         SLS                                             [c,0,0]
    getc        TLTS        ;input & store char n               [c,0]
    rcl         TTT         ;recall n                           [c,n]
    push 48     SS STTSSSSL ;convert n to m = ord(n)-ord('0')   [c,n,48]
    sub         TSST                                            [c,m]

ss:             LSS SSL     ;inner loop outputs c, m times      [c,m]
    dup         SLS                                             [c,m,m]
    jeq  t      LTS TL      ;if m==0, stop outputting this c    [c,m]
    push 1      SS STL      ;otherwise decr m                   [c,m,1]
    sub         TSST                                            [c,m-1]
    copy 1      STS STL     ;copy c to tos                      [c,m-1,c]
    putc        TLSS        ;output this c                      [c,m-1]
    jmp  ss     LSL SSL     ;loop back to output this c again   [c,m-1]

t:              LSS TL                                          [c,m]
    pop         SLL                                             [c]
    pop         SLL                                             []
    jmp  s      LSL SL      ;loop back to get the next c,n      []

tt:             LSS TTL                                         [c]
    end         LLL         ;exit

```
> 1 votes

# Answer
**Clojure (107)**

```
(pr(apply str(map #(apply str(repeat(Integer/parseInt(str(second %)))(first %)))(partition 2(read-line)))))

```

This feels exceptionally long for being Clojure, if someone can do better, please post it.
> 1 votes

# Answer
## C# - 108 105 bytes

```
void f(){var s=Console.ReadLine();for(int i=0;i<s.Length;i+=2)Console.Write(new string(s[i],s[i+1]-48));}

```

Explanation:

```
void f()
{
    var s = Console.ReadLine(); // Read the input from STDIN.

    // Loop until the end of the string, and increment our index counter by 2 at each iteration.
    for (int i = 0; i < s.Length; i += 2)

        Console.Write(new string(s[i], s[i + 1] - 48)); // Create (s[i + 1] - 48) copies of the current character, and print it.
        // s[i + 1] - 48 implicitly casts the character at s[i + 1] to its integer digit form.
}

```
> 1 votes

# Answer
# JavaScript (ES6), 40 bytes

```
s=>s.replace(/../g,v=>v[0].repeat(v[1]))

```

```
f=
  s=>s.replace(/../g,v=>v[0].repeat(v[1]))
;
console.log(f(":144,1'1"))
```
> 1 votes

# Answer
# PHP, 51 bytes

```
for(;--$z?:($c=$argn[$i++]).$z=$argn[$i++];)echo$c;

```

Try it online!

# PHP, 54 bytes

```
for(;~$c=$argn[$i++];)echo str_repeat($c,$argn[$i++]);

```

Try it online!

# PHP, 54 bytes

```
for(;~$c=$argn[$i++];)echo str_pad($c,$argn[$i++],$c);

```

Try it online!
> 1 votes

# Answer
# RProgN, 55 Bytes

```
S y = '' x = y L ¿ y pop y pop \ rep x . 'x' = y L } x

```

## Explained

```
S y =               # Convert the input to a backwards stack, assign it to y.
'' x =              # Assign a blank string to x
y L                 # Push the length of y
¿                   # While the top of the stack is truthy, popping.
    y pop           # Push the top value of y to the stack.
    y pop           # Twice.
    \               # Swap them around, so we get C 1 instead of 1 C
    rep             # Repeat the string. (C 1 times in the above example)
    x . 'x' =       # Append it to the back of x, and re-assign it. We use the back because we're starting at the END of the string.
    y L             # Push the length of y for the next itteration of the loop.
}                   #
x                   # Push x, and implicitly print it.

```

Try it Online!
> 1 votes

# Answer
# Jelly, 10 bytes

```
s2µṪV$€x@Ẏ

```

Try it online!

GOLFSCRIPT TIE JELLY DAT IMPOSSIBLE WAAAAAT!?

# Jelly, 10 bytes

```
Ḋm2V€x@m2$

```

Try it online!
> 1 votes

# Answer
# K (oK), 17 bytes

**Solution:**

```
,/{(.y)#x}.'0N 2#

```

Try it online!

**Explanation:**

```
,/{(.y)#x}.'0N 2# / the solution
            0N 2# / reshape input into Nx2 grid
  {      }.'      / apply lambda to each pair of inputs
       #x         / take from x
   (  )           / do this together
    .y            / value y (ie "5" => 5)
,/                / flatten

```
> 1 votes

# Answer
# \>\<\>, ~~28~~ 24 bytes

*Saved 4 bytes thanks to Jo King!*

```
/1-:?v
\$o:$<-*c4i;?(0:i

```

Try it online!

This was very interesting to golf the form. You can see my process below.

## Alternatives

```
i:0(?;i4c*->:    ?v
           ^$o:$-1<

/?      <:-*c4i;?(0:i
\1-$:o$:^0

/?    :<-*c4i;?(0:i
\1-$:o$^.00

/?    :<-*c4ip1c;?(0:i
\1-c1go^.00

/?    :<-*c4ip1c;?(0:i
\1-c1go^.00

/?}-1<:-*c4i;?(0:i[0
\:o}:^.00

/?}-1<:-*c4i;?(0:i[0
\:o}:^00

0/?}-1<:-*c4i;?(0:i[
0\:o}:^

```
> 1 votes

# Answer
# Perl 6, 20 bytes

```
{S:g{(.)(.)}=$0 x$1}

```

Try it online!

Anonymous codeblock containing a regex that replaces each pair of characters in the input with the first one repeated by the second.
> 1 votes

# Answer
# 8088 Assembly, IBM PC DOS, 24 bytes

Binary `xxd` dump:

```
00000000: d1ee add0 e88a c8ad 80ec 308a dcb4 0ecd  ..........0.....
00000010: 10fe cb75 f8e2 f0c3                      ...u....

```

Unassembled listing:

```
D1 EE       SHR  SI, 1          ; point SI to DOS PSP (080H)
AD          LODSW               ; load input length into AL
D0 E8       SHR  AL, 1          ; half input length to get number of CN pairs
8A C8       MOV  CL, AL         ; move into counter
        C_LOOP:
AD          LODSW               ; Load pair: C = AL, N = AH
80 EC 30    SUB  AH, '0'        ; ASCII convert N to binary
8A DC       MOV  BL, AH         ; BL is counter for number of reps of C
        N_LOOP:
B4 0E       MOV  AH, 0EH        ; BIOS teletype output function
CD 10       INT  10H            ; call BIOS, display C
FE CB       DEC  BL             ; decrement loop counter
75 F8       JNZ  N_LOOP         ; if end of N loop, move to next C
E2 F0       LOOP C_LOOP         ; loop through all C's
C3          RET                 ; return to DOS

```

Standalone DOS executable program. Input via command line, output to console.
> 1 votes

# Answer
# Brachylog, 11 bytes

```
ġ₂{ẹịᵗj₎}ᵐc

```

Try it online!

```
          c    The output is the concatenation of
  {     }ᵐ     the result of mapping
   ẹịᵗj₎       repeating the first element by the second converted to an integer
ġ₂             over the length-2 chunks of the input.

```
> 1 votes

# Answer
# Senva, 33 bytes

I was first making a big answer with a large code into the back-memory, but finally I made that :

```
1'(`>0.>{@}0'{v}1'0,>48-0,-<~>$>$

```

Here is an explanation :

```
1'  // Go to the second cell, the first will be used to store an information
(   // Input a string
`   // Go to the last cell (at the last character of the string)
>   // Make a new cell after the string
0.  // Store a 0 to mark the end of the string
>   // Make a new cell
{@} // Store this adress into the back-memory
0'  // Go to the 1st cell
{v} // Paste the adress, now the 1st cell contains the adress which points after the '0' which marks the end of the string
1'  // Go to the 2nd cell (the beginning of the string)
0,  // While we do NOT encounter a zero (while the string is not terminated)
  >   // Go to the next cell (the repeat number)
  48- // Substract 48 to get the number (the string was stored as an ASCII chain)
  0,  // While this cell is not equal to 0 (higher than 0)
    - // Decrease the cell
    < // Go to the cell which contains the character to repeat
    ~ // Display it
    > // Go to the number
  $ // End of the loop
  > // Go to the next number
$ // End of the loop

```

So we make a loop across the string, and a second loop into which display the `C` character \`\` times.
> 0 votes

# Answer
# Gema, ~~17~~ 16 characters

```
??=@repeat{$2;?}

```

Sample run:

```
bash-4.3$ gema '??=@repeat{$2;?}' <<< ":144,1'1"
:4444,'

```

Try it online!
> 0 votes

# Answer
## C++ - 151 144 142 bytes

```
#include <iostream>
#include <string>
void f(){std::string p;std::cin>>p;for(int i=0,j;i<p.size();i+=2)for(j=48;j<p[i+1];j++)std::cout<<p[i];}

```

Way too long. I should probably just use an character pointer instead and forget the whole string thing.

2 bytes saved by @PeterTaylor!

Explanation:

```
void f()
{
    std::string p; // A string to hold the input.
    std::cin >> p; // Read the input from STDIN, and source to <p>.

    // Loop until the end of the string <p>, withs index jumps of 2 at each iteration.
    for(int i = 0, j; i < p.size(); i += 2)

        // Loop (p[i + 1] - 48) times, and print the current character each time.
        /* p[i + 1] - 48 is a neat way to convert the next character in the string
           to its integer digit from. */
        for(j = 48; j < p[i + 1]; j++)
            std::cout << p[i]; // Print the character we are at.
}

```
> 0 votes

# Answer
# \>\<\> \- 36 Bytes

```
i:01-=?; l2=?v
v?=*68:ro:r-1<
>~~d0.

```

This solution can be run without using the input flag or preloading the stack, although both of those methods could cut down on bytes. If there is any interest, I can describe how it works to anyone who is curious.

Try it here!
> 0 votes

# Answer
# JavaScript, 40 bytes

```
f=v=>v&&v[0].repeat(v[1])+f(v.slice(2))

```

Recursive. Expand first 2 characters and call self with remainder of string.
> 0 votes

# Answer
# Ahead, 12 bytes

```
~W:k-1'ii@j~

```

## Explained

Single line Ahead boards are nice because you can explain them without some kind of diagram.

```
(Program effectively loops in reverse by floating)

~            float to next ~ (to end of line)
          ~  stop floating (end of line, turn around)
         j   jump next
       i     read char from input
        @    bounce here and die if input is empty, else continue west
      i      read digit char from input
   -1'       subtract '1 (49) from input char to get digit value
  :          dup first char that many times
 W           Write stack to output as chars
~            (repeat until head dies from empty input)

```

Try it online!
> 0 votes

# Answer
## Clojure, 60 bytes

```
#(apply str(for[[c n](partition 2 %)_(range(-(int n)48))]c))

```

I assume we can take the input as an argument and return the string. If not this grows to **73 bytes**:

```
#(pr(apply str(for[[c n](partition 2(read-line))_(range(-(int n)48))]c))

```
> 0 votes

# Answer
# SmileBASIC, 54 bytes

```
LINPUT S$WHILE I<LEN(S$)?S$[I]*VAL(S$[I+1]);
I=I+2WEND

```

Alternative (same size):

```
LINPUT S$WHILE""<S$?SHIFT(S$)*VAL(S$[1]);
S$[0]="
WEND

```

Really wanted to write `?SHIFT(S$)*VAL(SHIFT(S$))` but expressions are evaluated right to left, so the shifts would happen in the wrong order...
> 0 votes

# Answer
# Python 2, 40 bytes

```
f=lambda s:s and s[0]*int(s[1])+f(s[2:])

```

Try it online!
> 0 votes

# Answer
# Husk, <sup>~~9~~</sup> 7 bytes

```
ṁΓ·RrC2

```

Try it online!
> 0 votes

---
Tags: code-golf, string
---