24
\$\begingroup\$

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.

\$\endgroup\$
  • 2
    \$\begingroup\$ @quintopia According to site rules, no. You can use a function if you want to. \$\endgroup\$ – Doorknob Nov 28 '15 at 17:34
  • 1
    \$\begingroup\$ Technically, I (and I bet other humans) can read "150 minutes". \$\endgroup\$ – PyRulez Nov 28 '15 at 21:55
  • 1
    \$\begingroup\$ Why restrict to >59 minutes? Also, I prefer 61 minutes to 1 hour 1 minute and really would hate seeing 1 hour 0 minutes \$\endgroup\$ – markshancock Nov 29 '15 at 0:28
  • 6
    \$\begingroup\$ You 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. \$\endgroup\$ – Alex A. Nov 29 '15 at 7:03
  • 2
    \$\begingroup\$ It 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. \$\endgroup\$ – Alex A. Nov 29 '15 at 7:12

50 Answers 50

1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Now get rid of all of that unnecessary whitespace around operators and braces. \$\endgroup\$ – Mego Nov 29 '15 at 22:10
  • \$\begingroup\$ And make the class name one character, and replace String[] args with String[]a. \$\endgroup\$ – lirtosiast Nov 29 '15 at 22:10
  • \$\begingroup\$ You can also assign Integer.valueOf(args[0]) to a variable. \$\endgroup\$ – lirtosiast Nov 29 '15 at 22:12
  • 1
    \$\begingroup\$ This 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"). \$\endgroup\$ – Reto Koradi Nov 29 '15 at 22:59
  • 2
    \$\begingroup\$ Absolutely. 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. \$\endgroup\$ – Reto Koradi Nov 29 '15 at 23:17
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ You don't need the comma or the period. c: \$\endgroup\$ – Addison Crump Nov 28 '15 at 18:05
  • \$\begingroup\$ Also, I think that round also has a chance of going up, making 239 be 4 hours and 59 minutes. \$\endgroup\$ – Addison Crump Nov 28 '15 at 18:06
  • \$\begingroup\$ @Mego yeah I noticed that. I will fix this as soon as possible. On mobile right now \$\endgroup\$ – Ashwin Gupta Nov 28 '15 at 21:19
  • \$\begingroup\$ from math import* will save you bytes \$\endgroup\$ – cat Nov 30 '15 at 0:21
  • \$\begingroup\$ Do you really need those spaces in between? \$\endgroup\$ – Vasu Adari Dec 2 '15 at 10:42
1
\$\begingroup\$

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)

\$\endgroup\$
  • \$\begingroup\$ You can save bytes by just having hour and minute string and checking just for s. \$\endgroup\$ – Vasu Adari Nov 30 '15 at 10:56
  • \$\begingroup\$ @VasuAdari saved 10 bytes thanks to you. \$\endgroup\$ – undefined Nov 30 '15 at 10:59
  • \$\begingroup\$ You're welcome. One doubt, can you not do $h,$m=1,2 or [1,2] in php? \$\endgroup\$ – Vasu Adari Nov 30 '15 at 11:04
  • \$\begingroup\$ Unfortunately no. But I'm not aware if there's a similar way. \$\endgroup\$ – undefined Nov 30 '15 at 11:08
1
\$\begingroup\$

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")
}
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ You can save 2 bytes by changing !=1 to >1. \$\endgroup\$ – Vasu Adari Dec 4 '15 at 6:23
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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])
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ It should handle plurals. \$\endgroup\$ – Vasu Adari Dec 2 '15 at 13:52
  • \$\begingroup\$ @VasuAdari Now it does... although some answers around here don't. \$\endgroup\$ – Mathieu Rodic Dec 2 '15 at 14:12
  • \$\begingroup\$ I won't consider those answers :) \$\endgroup\$ – Vasu Adari Dec 4 '15 at 6:31
0
\$\begingroup\$

JavaScript 96

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

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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>
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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])
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.