Given an integer between 0 and 141 (inclusive), list all 24-hour times whose hour, minute, and second units add to that integer.

Rules of addition

Numbers are added by their time units, not by single digits.

For example, take 17:43:59

17+43+59=119

Remember, that is an example of digits being added. In reality, you would enter 119, and 17:43:59 would be one of the results. Output should be given as HH:MM:SS or H:MM:SS.

Also keep in mind the highest number possible is 141, being 23:59:59. This is code golf, so the lowest amount wins. Trial and error is permitted, but there may be a better way to go about this.

Edit: Please specify where in your code the input value is.

share|improve this question
3  
Welcome to Programming Puzzles & Code Golf! If by plugged in you mean made part of the source code, that's usually disallowed. In general, it's a good idea to stick to those defaults. Do we have to display the results as strings? If so, what formats are allowed? – Dennis 19 hours ago
    
Is the input number guaranteed to be positive? Will there be at least one solution? – xnor 19 hours ago
    
I've edited the question a bit to clarify/answer some things. If your intent was different than my changes, feel free to edit it to match that. – Geobits 19 hours ago
    
Hours can be single digit but the rest must be padded to two? I'd rather these be consistent. – xnor 19 hours ago
3  
"Please specify where in your code the input value is." - The convention on PPCG for taking input is using arguments, as well as a few other options. See Default for Code Golf: Input/Output methods on Meta. – user2428118 13 hours ago

18 Answers 18

Jelly, 16 30 29 20 bytes

Now with the correct output format! Many thanks to Dennis for his help in debugging this answer. Golfing suggestions welcome. Try it online!

Edit: +14 bytes from using the correct output format. -1 byte from removing an extra space. -3 from changing from 24,60,60 to “ð<<‘. -6 bytes from changing +100DḊ€€ to d⁵.

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

Explanation

“ð<<‘Œ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.
share|improve this answer

Bash, 71

  • 8 bytes saved thanks to @hvd
for t in {0..23}+{00..59}+{00..59};{((${t//+0/+}-$1))||echo ${t//+/:};}

Try it online.

share|improve this answer
    
printf is costly here. By getting t closer to the right format, and fixing it up to make ((t-$1)) work, you can get it down to 71: for t in {0..23}+{00..59}+{00..59};{((${t//+0/+}-$1))||echo ${t//+/:};} – hvd 10 hours ago
    
@hvd Good golfing - thanks! – Digital Trauma 2 hours ago

Python 3, 91 bytes

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

There are shorter solutions using exec (Python 2) or recursion (Python 3), but both require an unreasonable amount of memory.

Try it online!

share|improve this answer

PowerShell, 87 77 bytes

Saved 10 bytes thanks to John L. Bevan

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

Try it online! (this will time out, it's very slow)

Explanation

Pretty simple, starting with the current [datetime], add 1 second 86,399 times, format as a string, then keep only the ones where sum adds up.

share|improve this answer
    
FYI: You can replace 10000000 with 1e7l to save 4 bytes... or even 1e7 for an extra byte (I think; I had to include the L for the benefit of the parameter; but suspect your approach avoids that need. – JohnLBevan 2 hours ago
1  
@JohnLBevan thanks! I struggled with 1e7 for at least 30 minutes, and it was the L postfix I missed; I forgot about it and couldn't figure out a way to get it to int that was shorter than the constant. Who decided that that a [timespan] interprets an [int] as ticks and a [double] as days anyway?? The iex bit is pretty brilliant, though it makes this whole thing inordinately slower. – briantist 1 hour ago
1  
No worries; I had some help on that one too ;) : stackoverflow.com/q/41408902/361842 – JohnLBevan 1 hour ago
1  
@JohnLBevan I literally just saw this question before the comment where you linked it! Nice. – briantist 1 hour ago
1  
Also the iex trick was adapted from a tip here: codegolf.stackexchange.com/a/746/6776 – JohnLBevan 1 hour ago

Haskell, 77 bytes

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

Pyth - 30 bytes

Takes all possible times then filters.

mj\:%L"%02d"dfqsTQsM*U24*KU60K

Test Suite.

share|improve this answer

Perl 6, 62 56 bytes

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

Just checks all possible combinations in the cross product of all hours, minutes, and seconds.

share|improve this answer

Haskell, 90 bytes

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]

Returns a list of HH:MM:SS strings, e.g. f 140 -> ["22:59:59","23:58:59","23:59:58"].

It's three simple loops through the hours, minutes and seconds. Keep and format all values where the sum is the input number x.

share|improve this answer

Octave, 83 , 87 bytes

@(a){[H,M,S]=ndgrid(0:23,s=0:59,s);printf("%d:%02d:%02d\n",[H(x=H+M+S==a),M(x),S(x)]')}

Try it Online!

share|improve this answer

Julia 0.5, 69 bytes

!n=[h+m+s==n&&@printf("%d:%02d:%02d
",h,m,s)for s=0:59,m=0:59,h=0:23]

Try it online!

share|improve this answer

Batch, 168 bytes

@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%

Outputs single-digit hours.

share|improve this answer

Mathematica, 79 bytes

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

JavaScript, 120 118 bytes

Takes one additional empty string as input, which I presume doesn't count towards the size.

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:",""))(""))

share|improve this answer

QBIC, 82 72 bytes

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

This hits an unfortunate spot in QBasic, with casting to number, trimming and prepending a 0 when necessary is really costly.

Sample output:

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

Explanation I wrote a novel about it:

:           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 :-)
share|improve this answer

Racket 39 bytes

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

Ungolfed:

(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
share|improve this answer

MATL, 29 bytes

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

Try it online!

Explanation

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
share|improve this answer

[PowerShell], 91 97 bytes (including input)

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,$_}}}

or

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

Expanded & commented

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, $_
        }
    }
}
share|improve this answer

[PowerShell], 79 Bytes (nasty version)

Since the rules say nothing about completing in a certain time (or at all), and nothing about no duplicates, here's a horrific solution:

param($x)for(){if(($d=Date).Second+$d.Minute+$d.Hour-eq$x){"{0:H:mm:ss}"-f$d}}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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