24小时制的总和


21

给定一个介于0和141(含)之间的整数,请列出所有24小时制,其小时,分钟和秒单位加到该整数上。

加法规则

数字是按其时间单位而不是一位数字相加的。

例如,以17:43:59

17 + 43 + 59 = 119

请记住,这是添加数字的示例实际上,您将输入119,而17:43:59将是结果之一。输出应为HH:MM:SS或H:MM:SS。

另外请记住,最大数目可能是141,即23:59:59。这是代码高尔夫球,因此赢利最少。允许反复试验,但是可能有更好的方法来解决此问题。

编辑:请指定输入值在代码中的何处。


3
欢迎来到编程难题和代码高尔夫球!如果插入意味着将其包含在源代码中,通常是不允许的。通常,最好遵循这些默认值。我们是否必须将结果显示为字符串?如果可以,允许使用什么格式?
丹尼斯,

输入数字是否保证为正?至少会有一种解决方案吗?
xnor

我已经对问题进行了一些编辑,以澄清/回答一些问题。如果您的意图与我的更改不同,请随时对其进行编辑以匹配该意图。
Geobits,2013年

1
我之所以这样做,是因为这是我看到给定时间(在现实世界中)的通常方式。从来没有人说过13:4:7,但是5:10:30几乎总是可以接受的。我没有改变的问题。
Geobits '16

3
“请指定输入值在代码中的什么位置。” -关于PPCG接受输入的约定是使用参数以及其他一些选项。请参阅Code Golf的默认值: Meta上的输入/输出方法
user2428118 '16

Answers:


8

果冻16 30 29 20字节

现在具有正确的输出格式!非常感谢Dennis调试此答案的帮助。欢迎打高尔夫球。在线尝试!

编辑:使用正确的输出格式时+14个字节。从-1个字节中删除多余的空间。-3从更改24,60,60“ð<<‘。从更改+100DḊ€€为-6个字节d⁵

“ð<<‘Œp’S=¥Ðfd⁵j€”:Y

说明

“ð<<‘Œp’S=¥Ðfd⁵j€”:Y  Main link. Argument: n

“ð<<‘                 Jelly ord() the string `ð<<` to get [24, 60, 60]. Call this list z.
     Œp               Cartesian product of z's items. 
                        Since each item of z is a literal,
                        Jelly takes the range [1 ... item] for each item.
       ’              Decrements every number in the Cartesian product 
                        to get lowered ranges [0 ... item-1].
        S=¥           Create a dyadic link of `sum is equal to (implicit n)`.
           Ðf         Filter the Cartesian product for items with sum equal to n.
             d⁵       By taking divmod 10 of every number in each item,
                        we get zero padding for single-digit numbers
                        and every double-digit number just turns into a list of its digits.
               j€”:   Join every number with a ':'.
                   Y  Join all of the times with linefeeds for easier reading.

8

巴什71

  • @hvd节省了8个字节
for t in {0..23}+{00..59}+{00..59};{((${t//+0/+}-$1))||echo ${t//+/:};}

在线尝试


1
printf这里很贵。通过t接近正确的格式并进行修复以使其((t-$1))正常工作,您可以将其降低到71:for t in {0..23}+{00..59}+{00..59};{((${t//+0/+}-$1))||echo ${t//+/:};}
hvd

@hvd打高尔夫球好-谢谢!
Digital Trauma

6

Perl 6的62 56个字节

{map *.fmt('%02d',':'),grep $_==*.sum,(^24 X ^60 X ^60)}

只需检查所有小时,分钟和秒的叉积中的所有可能组合。


4

Python 3,91字节

def f(n):
 for k in range(86400):t=k//3600,k//60%60,k%60;sum(t)==n!=print('%d:%02d:%02d'%t)

使用exec(Python 2)或递归(Python 3)的解决方案较短,但是两者都需要不合理的内存量。

在线尝试!


4

PowerShell87 77字节

由于约翰·L·贝文节省了10个字节

$d=date;0..86399|%{$d+=1e7l;"$d".Split()[1]}|?{("{0:H+m+s}"-f$d|iex)-in$args}

在线尝试!(这会超时,非常慢)

说明

非常简单,从current开始[datetime],添加1秒86,399次,格式为字符串,然后仅保留求和的值。


仅供参考:您可以替换为100000001e7l以节省4个字节...,甚至可以1e7保留一个额外的字节(我认为;L为了参数的好处,我必须包括;但是怀疑您的方法避免了这种需求。)
JohnLBevan

1
@JohnLBevan谢谢!我挣扎了1e7至少30分钟,这是L我错过的后缀;我忘记了它,无法找到一种方法来将其转换为比常量短的整数。谁决定了一个[timespan]解释的[int]蜱和[double]作为呢?该iex位是非常辉煌的,但它使这整个事情不相称慢。
briantist

1
别担心; 我也对此有所帮助;):stackoverflow.com/q/41408902/361842
JohnLBevan 2016年

1
@JohnLBevan我实际上只是在链接到的评论之前看到了这个问题!真好
briantist

1
同样,iex技巧也从这里的技巧中改编而成:codegolf.stackexchange.com/a/746/6776
JohnLBevan,2016年

3

Haskell,77个字节

f x=[tail$(':':).tail.show.(+100)=<<t|t<-mapM(\x->[0..x])[23,59,59],sum t==x]

2

Haskell,90个字节

p x=['0'|x<10]++show x
i=[0..59]
f x=[p h++':':p m++':':p s|h<-[0..23],m<-i,s<-i,h+m+s==x]

返回HH:MM:SS字符串的列表,例如f 140-> ["22:59:59","23:58:59","23:59:58"]

通过小时,分钟和秒,这是三个简单的循环。保留并格式化所有总和为输入数字的值x




2

批处理,168字节

@for /l %%t in (0,1,86399)do @call:c %1 %%t
@exit/b
:c
@set/ah=%2/3600,m=%2/60%%60,s=%2%%60,n=%1-h-m-s
@set m=0%m%
@set s=0%s%
@if %n%==0 echo %h%:%m:~-2%:%s:~-2%

输出单位数小时。


2

Mathematica,79个字节

Cases[Tuples@{(r=Range)@24-1,x=r@60-1,x},t_/;Tr@t==#:>DateString@TimeObject@t]&


1

QBIC82 72字节

:[0,23|[0,59|[0,59|~b+c+d=a|?!b$+@:`+right$(@0`+!c$,2)+A+right$(B+!d$,2)

这在QBasic中很不幸,因为将其转换为数字,修剪和0在必要时添加前缀确实非常昂贵。

样本输出:

Command line: 119
1:59:59
2:58:59
2:59:58
3:57:59
[... SNIP 270 lines ...]
23:58:38
23:59:37

解释我写了一本关于它的小说:

:           Get N, call it 'a'
[0,23|      Loop through the hours; this FOR loop is initialised with 2 parameters
            using a comma to separate FROM and TO, and a '|' to delimit the argument list
[0,59|      Same for the minutes
[0,59|      And the seconds
            QBIC automatically creates variables to use as loop-counters: 
            b, c, d (a was already taken by ':')
~b+c+d=a    IF a == b+c+d
|           THEN
 ?          PRINT
  !         CAST
   b        'b'
    $       To String; casting num to str in QBasic adds a space, this is trimmed in QBIC
+@:`        Create string A$, containing ":"
+right$      This is a QBasic function, but since it's all lowercase (and '$' is 
            not a function in QBIC) it remains unaltered in the resulting QBasic.
(@0`+!c$,2) Pad the minutes by prepending a 0, then taking the rightmost 2 characters.
+A          Remember that semicolon in A$? Add it again
+right$     Same for the seconds
(B+!d$,2)   Reusing the 0-string saves 2 bytes :-)

QBIC看起来很有趣。您是否仅为#code-golf!创建了它?:)
wasatchwizard

@wasatchwizard Yup :-)
steenbergh

1

PowerShell,67 79字节(讨厌的版本)

由于这些规则并没有说明在一定时间内(或根本没有完成),也没有关于没有重复的内容,因此这是一个可怕的解决方案:

for(){if(("{0:H+m+s}"-f($d=date)|iex)-in$args){"{0:H:mm:ss}"-f$d}}

1
我找不到相关的元信息,但是我敢肯定提交必须暂停,除非挑战明确指出
Sefa

谢谢@Sefa ...如果是这种情况,我找不到一种比Briantist的纯净版本少用讨厌的字符来工作我的讨厌版本的好方法了。不好;)
JohnLBevan'1

0

拍子39字节

(for*/sum((h 24)(m 60)(s 60))(+ h m s))

取消高尔夫:

(for*/sum      ; loop for all combinations; return sum of values for each loop
   ((h 24)     ; h from 0 to 23
    (m 60)     ; m from 0 to 59
    (s 60))    ; s from 0 to 59
  (+ h m s))   ; sum of all 3 variables

0

MATL,29个字节

24:q60:qt&Z*t!si=Y)'%i:'8:)&V

在线尝试!

说明

24:q     % Push [0 1 ... 23]
60:q     % Push [0 1 ... 59]
t        % Duplicate
&Z*      % Cartesian product of the three arrays. This gives a matrix with each
         % on a different row Cartesian tuple
t!       % Push a transposed copy
s        % Sum of each column
i=       % Logical mask of values that equal the input
Y)       % Select rows based on that mask
'%i:'    % Push this string
8:)      % Index (modularly) with [1 2 ... 8]: gives string '%i:%i:%i'
&V       % Convert to string with that format specification. Implicitly display

0

JavaScript, 122 120字节

接受一个额外的空字符串作为输入, 我认为这不计入尺寸更新了字节数(包括历史记录),以添加两个字节来初始化字符串。

console.log((
//Submission starts at the next line
i=>o=>{for(h=24;h--;)for(m=60;m--;)for(s=60;s--;)if(h+m+s==i)o+=`${h}:0${m}:0${s} `;return o.replace(/0\d{2}/g,d=>+d)}
//End submission
)(prompt("Number:",""))(""))


如果您需要将字符串初始化为空,则必须计算初始化次数
edc65'1

@ edc65完成。··
user2428118

0

JavaScript(ES6),110

v=>eval("o=[];z=x=>':'+`0${x}`.slice(-2);for(m=60;m--;)for(s=60;s--;h>=0&h<24&&o.push(h+z(m)+z(s)))h=v-m-s;o")

少打高尔夫球

v=>{
  o=[];
  z=x=>':' + `0${x}`.slice(-2);
  for(m = 60; m--;)
    for(s = 60; s--; )
      h = v - m - s,
      h >= 0 & h < 24 && o.push(h + z(m) + z(s))
  return o
}

测试

F=
v=>eval("o=[];z=x=>':'+`0${x}`.slice(-2);for(m=60;m--;)for(s=60;s--;h>=0&h<24&&o.push(h+z(m)+z(s)))h=v-m-s;o")

function update() {
  O.textContent=F(+I.value).join`\n`
}

update()
<input id='I' value=119 type=number min=0 max=141 oninput='update()'><pre id=O></pre>


0

JavaScript,96个字节

v=>{for (i=86399;i;[a,b,c]=[i/3600|0,i%3600/60|0,i--%60]){v-a-b-c?0:console.log(a+":"+b+":"+c)}}

展开的视图:

v => {
    for (i = 86399; i;
        [a, b, c] = [i / 3600 | 0, i % 3600 / 60 | 0, i-- % 60]) {
        v - a - b - c ? 0 : console.log(a + ":" + b + ":" + c)
    }
}

通过将86399循环为1,循环遍历所有可能的时间

  • 用3600除以将整数转换为时间,以获得第一个数字
  • 通过取整数mod 3600然后除以60得到第二个数字
  • 最后一位是整数mod 60

如果三个数字加起来等于输入值,则从输入值中减去所有三个数字以返回假值。如果该值为false,则输出该值。


0

bash,78个字节(使用BSD实用程序)或79个字节(也非BSD)

这比@DigitalTrauma和@hvd的漂亮的71字节bash解决方案要长一点,但是我有点喜欢这里使用以60为底的数字的想法。我很好奇是否有人可以再打一点。

使用BSD标准的jot实用程序:

jot '-wx=`dc<<<60do3^%d+n`;((`dc<<<$x++'$1'-n`))||tr \  :<<<${x:3}' 86400 0|sh

使用更通用的seq实用程序:

seq '-fx=`dc<<<60do3^%.f+n`;((`dc<<<$x++'$1'-n`))||tr \  :<<<${x:3}' 0 86399|sh

想法是生成从0到83699的数字,并使用dc将其转换为以60为基数。dc的base-60输出中的“数字”是从00到59的2位数字,中间用空格分隔“数字”,因此它以几乎所需的格式列出了从00 00 00到23 59 59的所有所需时间。

但是,如果按字面意义执行,则60 ^ 2以下的数字不是以60为基数的3位数字,因此缺少开头的00或00 00。因此,我实际上是在生成从60 ^ 3到60 ^ 3 + 83699的数字。这样可以确保在基数60中生成的所有数字都恰好是4位数字。只要我最终将不需要的多余第一位数字(01)丢掉,就可以了。

因此,一旦生成了所需的时间,我就将每个四元组从01 00 00 00提取到01 23 59 59,将最后三个数字相加并减去参数$ 1。如果该值为0,则将第三个字符中的所有字符都从第三个字符开始(丢弃“ 01”),使用tr将空格转换为冒号,然后打印结果。


0

PowerShell,91 97字节(包括输入)

param($x)1..864e3|%{($d=date($_*1e7l))}|?{("{0:H+m+s}"-f$_|iex)-eq$x}|%{"{0:H:mm:ss}"-f$_}

param($x)0..23|%{$h=$_;0..59|%{$m=$_;0..59|?{$h+$m+$_-eq$x}|%{"{0:0}:{1:00}:{2:00}"-f$h,$m,$_}}}

要么

param($x)0..23|%{$h=$_;0..59|?{($s=$x-$h-$_)-le59-and$s-ge0}|%{"{0:0}:{1:00}:{2:00}"-f$h,$_,$s}} <\ s>

展开并评论

param($x)
#loop through the hours
0..23 | %{
    $h=$_
    #loop through the minutes
    0..59 | %{
        $m=$_
        #loop through the seconds
        0..59 | ?{ #filter for those where the sum matches the target
            $h + $m + $_ -eq $x
        } | %{
            #format the result
            "{0:#0}:{1:00}:{2:00}" -f $h, $m, $_
        }
    }
}

NB:被@Briantist版本超越:https ://codegolf.stackexchange.com/a/105163/6776

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.