Running length of the movie in a human readable format

24

1

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.

Vasu Adari

Posted 2015-11-28T17:11:46.390

Reputation: 941

Must the answer be a complete program? – quintopia – 2015-11-28T17:30:10.837

2

@quintopia According to site rules, no. You can use a function if you want to.

– Doorknob – 2015-11-28T17:34:22.033

1Technically, I (and I bet other humans) can read "150 minutes". – PyRulez – 2015-11-28T21:55:27.717

1Why restrict to >59 minutes? Also, I prefer 61 minutes to 1 hour 1 minute and really would hate seeing 1 hour 0 minutes – markshancock – 2015-11-29T00:28:57.630

case sensitivity? – cat – 2015-11-29T05:20:11.840

@markshancock You're right even I kept thinking about that. Check the updated question. – Vasu Adari – 2015-11-29T06:10:20.603

6You changed the input range to be 0-240 but haven't included any test cases less than 60. I recommend sticking with the original range given that 28 answers have already been posted. – Alex A. – 2015-11-29T07:03:59.653

2It appears you also changed the acceptable output for whole hours. Unless a challenge has blaring issues that need to be fixed, please do not make changes to a challenge that invalidate existing answers. – Alex A. – 2015-11-29T07:12:59.240

1@markshancock Please don't suggest edits that break existing answers, re: x hours 0 minutes – Sherlock9 – 2015-11-29T07:28:51.510

@Sherlock, nothing wrong with expressing an opinion – markshancock – 2015-11-29T07:32:00.510

1I have reverted it back so existing answers won't get affected. I just felt all answers would be consistent i.e. one answer outputs 1 hour 0 minute and the other one like 1 hour 0 minutes. – Vasu Adari – 2015-11-29T07:34:14.903

@PyRulez Just to reduce additional effort :) – Vasu Adari – 2015-11-29T07:35:26.903

@sysreq It should be in the exact format as given in the test cases. So only lowercase letters. – Vasu Adari – 2015-11-29T07:37:36.373

@markshancock Ah yes. That's fair. Well, express away but also note if implementing that opinion would break existing answers. Thank you – Sherlock9 – 2015-11-29T07:39:59.327

@Sherlock, Wished my customers always knew exactly what they wanted and so I never had to change my code ... well, maybe not, they keep coming back. ;) – markshancock – 2015-11-29T09:07:47.390

@Sherlock, btw, if your code met the initial requirement. I'm sure people would understand you not making mods. – markshancock – 2015-11-29T09:10:42.233

Answers

10

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.

Reto Koradi

Posted 2015-11-28T17:11:46.390

Reputation: 4 870

135: ri60md]r"utehour"+6/W%.{1$1>'s*+}S* (Looks like this gives you a pretty solid lead on this challenge :)) – Martin Ender – 2015-11-29T19:23:24.040

@MartinBüttner r"utehour"+6/W% is actually the same length as "hour minute"S/, so that part ends up not helping. I think I had seen . used with a block before, but I had forgotten again that it was supported. – Reto Koradi – 2015-11-29T20:12:27.690

Ah, right, I had first posted a 36-byte version where it actually helped (but then deleted the comment and replaced it by the 35-byte version where it doesn't matter any more). – Martin Ender – 2015-11-29T20:14:20.640

19

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)

Sherlock9

Posted 2015-11-28T17:11:46.390

Reputation: 11 664

22Ah! Increasing bytecount! +1 for not giving up ;-) – agtoever – 2015-11-28T17:52:50.093

9

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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}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

jrich

Posted 2015-11-28T17:11:46.390

Reputation: 3 898

Good one. Suggestion: reduce parseInt(n) to +n. – nicael – 2015-11-28T18:39:31.013

@nicael That doesn't work, I tried. :( It returns NaN. You can try to edit the code by using the test snippet I've provided in the answer if you want to see for yourself. – jrich – 2015-11-28T18:41:47.190

Ah, I got it: with parseInt(), you're not only parsing int but also removing 'min' from the string (forgot it also does the latter). Yeah, in this case my suggestion is invalid. – nicael – 2015-11-28T18:46:10.153

1Input will not be just an integer. It fails when i provide input as 150 min. – Vasu Adari – 2015-11-28T19:12:05.093

1@VasuAdari It's working for me, outputs 2 hours 30 minutes. May I ask how you tested it? – jrich – 2015-11-28T19:15:55.950

Sorry i entered wrongly :P. It works :) – Vasu Adari – 2015-11-28T19:17:30.100

Doesn't work... "Input is malformed. Using no input." – ev3commander – 2015-11-28T21:12:28.733

3@ev3commander When using the test snippet, wrap the input in quotes so that it is recognized as a string. e.g. "61 min" or '61 min' – jrich – 2015-11-28T21:40:59.717

@ev3commander JavaScript ;) – Vasu Adari – 2015-11-29T05:51:55.053

1

+1 For JavaScript. Now you just have to make it a bookmarlet ;)

– MayorMonty – 2015-11-30T02:37:26.000

You forgot to specify that this is ES6 – Ismael Miguel – 2015-11-30T14:36:57.863

6

Pyth, 39 38 bytes

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

orlp

Posted 2015-11-28T17:11:46.390

Reputation: 37 067

5

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!

Addison Crump

Posted 2015-11-28T17:11:46.390

Reputation: 10 763

4

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

Blue

Posted 2015-11-28T17:11:46.390

Reputation: 26 661

4

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".

JohnE

Posted 2015-11-28T17:11:46.390

Reputation: 4 632

3

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()))

nicael

Posted 2015-11-28T17:11:46.390

Reputation: 4 585

You could wrap t=parseInt(t) and parenthesis, and then put that where ever you first use t so: (h=0|(t=parseInt(t))/60). This way, you can remove the return and the {} – Downgoat – 2015-11-28T19:41:27.260

@Downgoat I've already tried but it didn't work for some reason. Will try again. – nicael – 2015-11-28T19:42:01.753

1@Downgoat Apparently I've made a mistake previously, now it works properly. Thanks :) – nicael – 2015-11-28T19:45:52.777

USE TEMPLATE STRINGS. ${}!!! – Mama Fun Roll – 2015-12-01T04:21:20.773

3

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

Brad Gilbert b2gills

Posted 2015-11-28T17:11:46.390

Reputation: 12 713

3

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.]

Hilbert

Posted 2015-11-28T17:11:46.390

Reputation: 41

3

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));}

xsot

Posted 2015-11-28T17:11:46.390

Reputation: 5 069

3

Ruby, 75 bytes

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

Peter Lenkefi

Posted 2015-11-28T17:11:46.390

Reputation: 1 577

Sometimes even an empty string is too long. ''p. – manatwork – 2015-12-08T07:55:37.620

2

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

quintopia

Posted 2015-11-28T17:11:46.390

Reputation: 3 899

7This doesn't appear to correctly handle plurals. – Doorknob – 2015-11-28T17:34:29.967

@Doorknob This is what happens when the rules get changed after answers are posted :) – quintopia – 2015-11-28T22:26:07.733

2

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.

Tom Carpenter

Posted 2015-11-28T17:11:46.390

Reputation: 3 990

2

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!

Craig Roy

Posted 2015-11-28T17:11:46.390

Reputation: 790

2

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.

xsot

Posted 2015-11-28T17:11:46.390

Reputation: 5 069

I think you can just do "hour"+m/120*"s" and likewise for minutes. – xnor – 2015-11-29T06:29:52.400

It'll fail for m=240, unfortunately. – xsot – 2015-11-29T06:59:18.647

2

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).

syntonicC

Posted 2015-11-28T17:11:46.390

Reputation: 329

Output should not be enclosed within quotes. – Vasu Adari – 2015-12-04T06:26:37.083

@Vasu Adari Fixed it using the cat() function. – syntonicC – 2015-12-04T15:44:24.330

1You can save bytes by handling plural with just s and by changing your conditions. – Vasu Adari – 2015-12-04T15:51:51.510

2

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...)

Actorclavilis

Posted 2015-11-28T17:11:46.390

Reputation: 161

2

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.

enter image description here

Eumel

Posted 2015-11-28T17:11:46.390

Reputation: 2 487

2

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

Vasu Adari

Posted 2015-11-28T17:11:46.390

Reputation: 941

1

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.

Ashwin Gupta

Posted 2015-11-28T17:11:46.390

Reputation: 471

You don't need the comma or the period. c: – Addison Crump – 2015-11-28T18:05:37.457

Also, I think that round also has a chance of going up, making 239 be 4 hours and 59 minutes. – Addison Crump – 2015-11-28T18:06:08.433

@Mego yeah I noticed that. I will fix this as soon as possible. On mobile right now – Ashwin Gupta – 2015-11-28T21:19:54.060

from math import* will save you bytes – cat – 2015-11-30T00:21:08.980

Do you really need those spaces in between? – Vasu Adari – 2015-12-02T10:42:18.320

@VasuAdari no I don't. I thought I fixed that but it looks like the edit never saved. Thanks. – Ashwin Gupta – 2015-12-02T14:57:24.640

You still have some space before and after +. Is that really needed? – Vasu Adari – 2015-12-04T06:28:46.700

@VasuAdari yeah I know thanks. Sorry, when I went back and did it I was in a rush. Honestly, don't have much time for golfing during weekdays, on the weekend il go back and fix it. – Ashwin Gupta – 2015-12-04T15:04:53.363

1

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

Sherlock9

Posted 2015-11-28T17:11:46.390

Reputation: 11 664

o/p should not be enclosed within quotes. – Vasu Adari – 2015-11-28T18:47:12.797

@VasuAdari Fixed – Sherlock9 – 2015-11-28T18:54:33.930

You can lose the braces for divmod method. Also by using string interpolation you can save few bytes. – Vasu Adari – 2015-11-28T19:03:59.900

@VasuAdari I am aware of that string iterpolation is a thing, but I'm not sure what it is or how it works. Thanks for the help – Sherlock9 – 2015-11-28T19:31:58.807

@VasuAdari Oop, wait. Google has taught me what I need to know. Let me get editing. – Sherlock9 – 2015-11-28T19:34:39.687

1

Mathematica, 61 bytes

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

LegionMammal978

Posted 2015-11-28T17:11:46.390

Reputation: 15 731

1

Go, 177 Bytes

(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
*/

Kamehameha

Posted 2015-11-28T17:11:46.390

Reputation: 553

1

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)"

Mego

Posted 2015-11-28T17:11:46.390

Reputation: 32 998

Your link does not work – TanMath – 2016-01-02T15:07:47.837

1

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

Vasu Adari

Posted 2015-11-28T17:11:46.390

Reputation: 941

1

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 Notices 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'

CSᵠ

Posted 2015-11-28T17:11:46.390

Reputation: 484

1 byte less: $m=($i=$argv[1])%60;echo$h=$i/60|0," hour","s"[$h<2]," $m minute","s"[$m<2];. – insertusernamehere – 2015-11-29T01:27:12.087

@insertusernamehere nice, thanks! crazy – CSᵠ – 2015-11-29T02:07:39.003

You're welcome. Even 4 bytes lesser (was too tired to notice yesterday): $m=($i=$argv[1])%60;echo$h=$i/60|0," hour",s[$h<2]," $m minute",s[$m<2];. – insertusernamehere – 2015-11-29T08:49:03.580

@insertusernamehere that's a really nasty old one, but can't believe it works for php 5.6-7 and not for 5.3-5.5 – CSᵠ – 2015-11-29T09:06:01.300

I've tested it with PHP 5.6.10 (OS X) and it works here. :) – insertusernamehere – 2015-11-29T09:50:51.803

1

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.

errorseven

Posted 2015-11-28T17:11:46.390

Reputation: 220

1

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")
}

cat

Posted 2015-11-28T17:11:46.390

Reputation: 4 989

1

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

jqblz

Posted 2015-11-28T17:11:46.390

Reputation: 2 062

1

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

succcubbus

Posted 2015-11-28T17:11:46.390

Reputation: 181

1Welcome to PPCG.SE! I have edited your post to make is look more aesthetically pleasing. Have fun! – GamrCorps – 2015-11-29T18:22:10.410

1

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.

TheAustralianBirdEatingLouse

Posted 2015-11-28T17:11:46.390

Reputation: 11

Now get rid of all of that unnecessary whitespace around operators and braces. – Mego – 2015-11-29T22:10:13.917

And make the class name one character, and replace String[] args with String[]a. – lirtosiast – 2015-11-29T22:10:31.987

You can also assign Integer.valueOf(args[0]) to a variable. – lirtosiast – 2015-11-29T22:12:25.093

@ThomasKwa wouldn't that increase the size due to declaration? – TheAustralianBirdEatingLouse – 2015-11-29T22:45:04.787

no; int a= and ; takes 7 bytes, and you use it twice for a total of 9 bytes. Integer.valueOf(args[0]) takes 26 bytes. Unless there's a shorter way to convert to int; I don't golf in Java. – lirtosiast – 2015-11-29T22:51:40.473

You can also change println to print. – lirtosiast – 2015-11-29T22:56:13.347

1This doesn't use the singular/plural form of "hour(s)" and "minute(s)" depending on the number. Your test example should output 1 hour 48 minutes (singular "hour"). – Reto Koradi – 2015-11-29T22:59:05.693

@RetoKoradi Is that part necessary? – TheAustralianBirdEatingLouse – 2015-11-29T23:04:32.757

2Absolutely. Handling that with as little code as possible is the most interesting part of this challenge. You can see that if you look at the other solutions. – Reto Koradi – 2015-11-29T23:17:55.437

Got it. Thanks. – TheAustralianBirdEatingLouse – 2015-11-29T23:19:09.297

I've added that in, so I believe I've got a final byte count of 162 – TheAustralianBirdEatingLouse – 2015-11-30T00:24:13.403

You can make it a function, not necessarely a program... – Yassin Hajaj – 2015-11-30T11:02:25.150

@YassinHajaj Thank you, I did not realize that – TheAustralianBirdEatingLouse – 2015-11-30T23:57:25.960

Where does it say you can use "hrs" and "mins" instead of the actually specified "hours" and "minutes"? – cat – 2015-12-01T02:53:50.820

If you can, then so shall I. – cat – 2015-12-01T02:54:04.420

I don't think it matters, no one's told me anything and it does't specify in the OP you can't. – TheAustralianBirdEatingLouse – 2015-12-02T23:55:07.263

1

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

janschweizer

Posted 2015-11-28T17:11:46.390

Reputation: 151

1

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)

undefined

Posted 2015-11-28T17:11:46.390

Reputation: 211

You can save bytes by just having hour and minute string and checking just for s. – Vasu Adari – 2015-11-30T10:56:15.133

@VasuAdari saved 10 bytes thanks to you. – undefined – 2015-11-30T10:59:59.923

You're welcome. One doubt, can you not do $h,$m=1,2 or [1,2] in php? – Vasu Adari – 2015-11-30T11:04:44.267

Unfortunately no. But I'm not aware if there's a similar way. – undefined – 2015-11-30T11:08:02.033

1

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

Yassin Hajaj

Posted 2015-11-28T17:11:46.390

Reputation: 453

1

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." :-)

zmerch

Posted 2015-11-28T17:11:46.390

Reputation: 541

1

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

Emigna

Posted 2015-11-28T17:11:46.390

Reputation: 50 798

1

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

Jakube

Posted 2015-11-28T17:11:46.390

Reputation: 21 462

1

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

Cabbie407

Posted 2015-11-28T17:11:46.390

Reputation: 1 158

0

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

Alex A.

Posted 2015-11-28T17:11:46.390

Reputation: 23 761

0

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.

Gamerdog

Posted 2015-11-28T17:11:46.390

Reputation: 51

You can save 2 bytes by changing !=1 to >1. – Vasu Adari – 2015-12-04T06:23:27.700

0

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

user3819867

Posted 2015-11-28T17:11:46.390

Reputation: 439

0

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])

Kieran Hunt

Posted 2015-11-28T17:11:46.390

Reputation: 478

0

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

Mathieu Rodic

Posted 2015-11-28T17:11:46.390

Reputation: 1 170

It should handle plurals. – Vasu Adari – 2015-12-02T13:52:45.267

@VasuAdari Now it does... although some answers around here don't. – Mathieu Rodic – 2015-12-02T14:12:14.033

I won't consider those answers :) – Vasu Adari – 2015-12-04T06:31:14.610

0

JavaScript 96

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

wolfhammer

Posted 2015-11-28T17:11:46.390

Reputation: 1 219

0

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

Cameron McCluskie

Posted 2015-11-28T17:11:46.390

Reputation: 346

0

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>

Zach Gates

Posted 2015-11-28T17:11:46.390

Reputation: 6 152

0

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

manatwork

Posted 2015-11-28T17:11:46.390

Reputation: 17 865

0

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.

cat

Posted 2015-11-28T17:11:46.390

Reputation: 4 989

0

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])

Blue

Posted 2015-11-28T17:11:46.390

Reputation: 26 661