还剩多少时间?


31

该程序

现在给你两个字符串,一个A是计时器所在的当前位置,B是计时器将停止的位置。两个字符串的格式均为m:ss。您必须编写一个确定剩余时间的程序,该时间也应设置为m:ssmm:ss格式。

0:00 0:01 -> 0:01
0:55 1:00 -> 0:05
1:45 3:15 -> 1:30

1
在dc中,由于:是一条命令(数据作为代码原理),因此无法正确读取输入。我可以使用空格代替吗?还是需要寻找其他语言来回答这个问题?
seshoumara

1
01:30有效的输出吗?(领先零)
Luis Mendo

2
是的,我将其视为有效。我将编辑说明。
乔什(Josh)

1
@seshoumara输入必须包含一个冒号。
乔什(Josh)

m的最大值是多少?
Digital Trauma

Answers:


92

Excel,6个字节

=B1-A1

假设A在单元格中,A1而B在单元格中B1


37
不,不,我不会让胜利。+1您的vious回个人。
魔术八爪鱼缸

2
取消该操作,|vy':¡在05AB1E中启动,我无能为力...我认为Excel可能会诚实地赢得这项大奖,没有其他事情可以自动解析我所知道的格式。
Magic Octopus Urn

7
怎么样?怎么样?Excel如何获胜?我的大脑现在必须爆炸……
caird coinheringaahing

2
如果m大于23,则格式化似乎无效。例如,如果I型45:45在A1和22:22B1中,则结果是23:23:00 编辑没关系-为最大期望值是9
数字创伤

4
@EngineerToast不管使用哪种默认格式,对我来说都是如此。我只输入了输入,移到另一个单元格,输入了公式,然后按Enter。
莱利

15

MATL17 7字节

YOd15XO

输入是字符串的单元格数组,形式为{'1:45' '3:15'}{'1:45', '3:15'}

在线尝试!

说明

YO     % Input cell array of strings (implicit). Convert to serial date numbers
d      % Difference
15XO   % Convert to format 15, i.e. 'HH:MM'. Display (implicit)

不错哦!继续!
Suever

8

Bash + coreutils,44个 39字节

tr : \ |dc -e?r60*+r-r60*-60~rn58PA~rnn

在线尝试!

说明:使用“ 1:45 3:15”作为测试用例(最后一个示例)。我在报价中显示了中介步骤。

tr : \ |         # replace colons with spaces: "1 45 3 15"
dc -e?           # start dc script, push input to LIFO stack: "15 3 45 1"
     r60*+            # turn time B to total seconds: "195 45 1"
     r-r60*-          # turn time A to total seconds and get difference: "90"
     60~r             # turn difference (time left) to minutes and seconds: "1 30"
     n58P             # pop and print minutes, print colon (ASCII code 58): "30"
     A~rnn            # print seconds. Padding with zeroes is done by dividing by
                      #10 (A), and printing the quotient and the remainder.

请注意,我不检查分钟值是否需要零填充,因为OP指出的最大值为m9。


以下是我最初的44个字节的答案,该答案使用date命令将以秒为单位的总时间转换为m:ss格式。

date -d@`tr : \ |dc -e?r60*+r-r60*-p` +%M:%S

2
@DigitalTrauma谢谢。但是最后,我设法删除了date命令,并在dc中也进行了格式打印。
seshoumara

1
划掉的44看起来像普通的44。–
莱利

1
@Riley我也划掉了44周围的空间,以获得最初应该存在的效果。
seshoumara



5

c,86

f(a,b,c,d){scanf("%d:%d%d:%d",&a,&b,&c,&d);d+=(c-a)*60-b;printf("%d:%02d",d/60,d%60);}

从STDIN读取以空格分隔的时间。

在线尝试


5

批处理,74个字节

@set t=%2-(%1)
@set/as=%t::=*60+1%,m=s/60,t=s/10%%6
@echo %m%:%t%%s:~-1%

用替换:时间中的*60+1将其转换为可计算秒数的表达式。批处理将前导零解释为八进制,因此我1在秒前添加了a ,以确保进行十进制转换。幸运的是两个1取消了。


5

C,112100字节

感谢@betseg保存11个字节,感谢@Johan du Toit保存一个字节!

i,j;f(char*a,char*b){i=atoi(b)-atoi(a);j=atoi(b+2)-atoi(a+2);j<0?i--,j+=60:0;printf("%d:%02d",i,j);}

在线尝试!


1
您可以%s%d使用%02d和删除?:在线尝试!
betseg

1
scanf() is your friend for reading multiple integers.
Digital Trauma

1
You can also save 1 byte by using: j<0?i++,j+=60:0;
Johan du Toit

@DigitalTrauma Nononono, It's usually shorter to use arguments which he did.
Matthew Roh

5

MySQL, 13 22 bytes

select right(timediff(B,A),5)

expects the times in A and B.


4

Bash + GNU utilities, 43

date -d@`date -f- +%s|dc -e??r-60/p` +%M:%S

Try it online.

Explanation

         date -f- +%s                        # read in 2 line-delimited dates and output as number of seconds since the epoch
                     |dc -e                  # pipe to dc expression:
                           ??                # - read 2 input numbers
                             r-              # - reverse and subtract
                               60/           # - divide by 60
                                  p          # - output
        `                          `         # evaluate date|dc command
date -d@                             +%M:%S  # format seconds difference and output

Note the dc expression divides by 60, because date reads the input as H:MM instead of M:SS.


4

ECMAScript 6, 99 91 85 bytes

Single Line:

f=s=>s.split`:`.reduce((a,e,i)=>a+e*(!i?60:1),0);t=n=>~~(n/60)+":"+n%60;t(f(b)-f(a));

Slightly formatted:

f=s=>s.split`:`.reduce((a,e,i)=>a+e*(!i?60:1),0);
t=n=>~~(n/60)+":"+n%60;
t(f(b)-f(a));

I feel there could be some some savings in there.. but I am not seeing them at present.

Edit - excellent suggestions in the comments.


You can remove the parentheses around the s.
Arjun

And instead of s.split(":"), you can use the newer syntax : s.split<backtick>:<backtick>.
Arjun

4

PHP, 55 53 bytes

<?=date('i:s',($s=strtotime)($argv[2])-$s($argv[1]));

takes input from command line arguments


1
53 bytes: <?=date('i:s',($x=strtotime)($argv[2])-$x($argv[1]));
Ismael Miguel

4

C#, 72 bytes

using System;a=>b=>((DateTime.Parse(b)-DateTime.Parse(a))+"").Remove(5);

Takes input as strings. b="3:15" a="1:45".

Explanation:

Because DateTime.Parse() returns a Date in hh:mm:ss format, I am able to parse the result into a string using +"", then trim the trailing :00.

This works with hh:mm because there are both 60 seconds in a minute and 60 minutes in an hour.

0:01 0:00 returns 0:01

1:00 0:55 returns 0:05

3:15 1:45 returns 1:30


3
Unfortunately, the DateTime.Parse() is taking the input -- for example, 1:45 -- as hh:mm and not mm:ss, resulting in the follow output -- for A 1:45 and B 3:15 -- [01:30:00] ( hh:mm:ss ) ( even with CultureInfo.InvariantCulture specified ). You might have to add a "0:" + a/b when parsing.
auhmaan

@auhmaan Ah, nice catch. I ended up trimming the trailing :00.
Oliver

I believe you need a ; on the end, you can use currying i.e. a=>b=>, you need to fully qualify DateTime or include using System;.
TheLethalCoder


2

Pyth, 47 45 44 40 Bytes

J.U-Zbm+*60hdedmmvkcd\:.z%"%d:%02d".DJ60

Takes the input separated by newlines.

Pyth had no time built-ins useful for this. I tried some fancy eval() stuff but apparantly Pyth can't eval stuff with * or any leading zeroes whatsoever. This got much longer than i hoped. Quite some bytes are spent on adding a leading zero to the output. At least I'm shorter than bash. Will add explanation if asked.

Try this!

alternative solution, 48 Bytes

J.U-Zbm+*60hdh_dmmvkcd\:.z
K%J60
s[/J60\:*<KT\0K

2

Haskell, 98 127 86 Bytes

r(m:_:s)=60*read[m]+read s
a#b|(d,m)<-divMod(r b-r a)60=show d++':':['0'|m<=9]++show m

Try it online!

But I wonder if there are some library functions for this

EDIT: Removed import, also fixed an error where it showed m:s instead of m:ss

Also, well-formatted version:

convert :: String -> Integer
convert (a:_:b) = (read [a])*60+(read b)

diffTime :: String -> String -> String
diffTime s1 s2 = let (d,m) = divMod (c b-c a) 60 in show d ++ ":" ++ pad2d m

pad2d :: Int -> String
pad2d n = ['0'|n<=9]++show n

EDIT2: Golfed off (30?) bytes thanks to Laikoni! Also golfed some other misc. bytes.


1
You should tell us what language this is and how many bytes it uses.
Josh

2
Yeah, I didn't mean to press post (who knew tab+enter from the text box posts your answer?)
Generic Display Name

Same approach, 86 bytes: Try it online!
Laikoni

I didn't think of using a list comprehension. Thanks :)
Generic Display Name

2

T-SQL, 238 bytes

CREATE PROCEDURE d @a time,@b time AS BEGIN DECLARE @d int DECLARE @s varchar(2) SET @d=datediff(s,@a,@b);SET @s=CAST(@d%3600/60 AS VARCHAR(3)) SELECT CAST(@d/3600 AS VARCHAR(3))+':'+(SELECT CASE WHEN LEN(@s)=1 THEN '0'+@s ELSE @s END)END

Usage:

EXEC d '00:55','01:00'

Seeing the PostGres example earlier I realised I hadn't seen many golfing attempts in SQL so I had a go at it in T-SQL. Now I know why you don't see much golfing in SQL :D


2

CJam, 34 33 25 bytes

Saved 8 bytes thanks to Martin Ender!

{r':/60b}2*\m60mds2Te[':\

Try it online!

Explanation

{             e# Start of block
 r            e#  Read one time from input
 ':/          e#  Split on colons, gives [minutes seconds]
 60b          e#  Convert from base 60
}2*           e# Run this block 2 times
              e# At this point, we have the two times in seconds on the stack
\             e# Swap top elements
m             e# Subtract
60md          e# Divmod the result by 60, to convert back to minutes and seconds
s             e# Convert the seconds to a string
2Te[          e# Pad it to 2 characters by adding 0s to the left (T = 0)
':            e# Push a colon character
\             e# Swap top elements, bringing seconds back to the top

2

T-SQL, 82 Bytes

select left(cast(dateadd(minute, datediff(S,'0:00','0:01')/60,114) as time(0)), 5)

2

Python, 160 bytes

I am still new to code golf so if anyone has any suggestions, I would appreciate it.

a, b = input()
def z(x):
    x = x.split(":")
    return int(x[0])*60+int(x[1])
a, b = z(a),z(b)
s, m = b-a,0
while s >= 60:
    s -= 60
    m += 1
print(str(m)+":"+str(s))

1
Hello and welcome to our site. It seems that you are taking input for your program from preinitialized variables. However this is not permitted under out defaults for IO. I would recommend for this specific case to take input via raw_input().
Wheat Wizard

1

REXX, 79 bytes

arg t q
say right(time(,f(q)-f(t),s),5)
f:return time(s,'00:'right(arg(1),5,0))

1

Pyth, 28

%"%d:%02d".Dh.+misMcd\:60Q60

Try it.

Explanation

                   cd\:      # lambda to split c on ":"
                 sM          # map to convert string to int
               mi      60Q   # convert from base-60 list to give seconds
             .+              # delta of the two seconds values
            h                # single-item list to int
          .D              60 # divmod by 60
%"%d:%02d"                   # format output

1

Java 7, 164 bytes

String c(String a,String b){long s=x(b,1)-x(a,1)+(x(b,0)-x(a,0))*60,m=s%60;return(s/60)+":"+(m>9?m:"0"+m);}long x(String s,int i){return new Long(s.split(":")[i]);}

Explanation:

String c(String a, String b){       // Method with two String parameters and String return-type
  long s = x(b,1) - x(a,1)          //  Get difference in seconds from input times
           + (x(b,0) - x(a,0)*60,   //   plus the difference in minutes times 60 to get the seconds
    m = s%60;                       //  Temp variable of seconds after we've subtracted the minutes (used multiple times)
  return (s/60)                     //  Return minutes
    +":"                            //   plus ":"
    +(m>9?m:"0"+m);                 //   plus seconds (with a leading 0 if necessary)
}                                   // End of method

long x(String s,int i){             // Separate ethod with String and Integer parameters and long return-type
  return new Long(s.split(":")[i];  //  Return either minutes or seconds of String parameter based on the index
}                                   // End of method

Test code:

Try it here.

class M{
  String c(String a,String b){long s=x(b,1)-x(a,1)+(x(b,0)-x(a,0))*60,m=s%60;return(s/60)+":"+(m>9?m:"0"+m);}long x(String s,int i){return new Long(s.split(":")[i]);}

  public static void main(String[] a){
    M m = new M();
    System.out.println(m.c("0:00", "0:01"));
    System.out.println(m.c("0:55", "1:00"));
    System.out.println(m.c("1:45", "3:15"));
  }
}

Output:

0:01
0:05
1:30

1

TXR Lisp, 101 bytes

$ txr -e '(awk (:let (s "%M:%S"))
               ((mf (time-parse s))
                (prn (time-string-local (- [f 1].(time-utc) [f 0].(time-utc)) s))))'
13:49 14:49 
01:00
0:13 1:47
01:34
5:01 5:59
00:58
6:00 6:00
00:00
6:00 5:00
59:00

Condensed: (awk(:let(s"%M:%S"))((mf(time-parse s))(prn(time-string-local(-[f 1].(time-utc)[f 0].(time-utc))s))))


You need a bytecount, and I don't think this is fully golfed.
Rɪᴋᴇʀ

1

Ruby, 91 bytes

require'time';t=Time;d=t.parse($*[1])-t.parse($*[0]);puts t.at(d.to_i).utc.strftime '%H:%M'

Try it online!

Takes input from command line arguments.

Invocation:

ruby outatime.rb $A $B

Example:

ruby outatime.rb 1:45 3:15

Output:

01:30


Welcome to the site!
DJMcMayhem

1

PowerShell 47 Bytes

param($s,[timespan]$f)($f-$s).ToString("h\:mm")

Simple timespan math and coverting to hour and seconds string.


0

JavaScript, 88 bytes

a=>b=>{c=a.split`:`,d=b.split`:`;return +c[0]-d[0]-d[1]>c[1]?1:0+":"+(+c[1]+60-d[1])%60}

Try it online!

Explanation:

Splits the inputs on the colon

c=a.split`:`,d=b.split`:`;

Converts string to int

+c[0]

Gets the minute value

+c[0]-d[0]-d[1]>c[1]?1:0

Gets the second value

(+c[1]+60-d[1])%60

Returns the string minutes:seconds

return +c[0]-d[0]-d[1]>c[1]?1:0+":"+(+c[1]+60-d[1])%60
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.