It's time for a clock challenge!

25

4

I'd like you to build me a clock that displays time in this format:

18 ----------
19 --------------------------------------------------

This displays '18:10'. The current hour and the next hour are shown at the front of the line, followed by a space and a number of dashes: on the first line the number of minutes that have passed in this hour, and the second line shows how many more minutes to go in this hour.

To clarify

  • The clock should display the system's time. If fetching the time from another source is more convenient, that's fine too. It may not be supplied as input.
  • At 18:00, the top line is just 18 (Trailing spaces allowed but not required)
  • At 18:59, the bottom line is 19 -
  • The hours < 10 are either pre-padded with a 0 (01 -----) or right-aligned ( 1 -----). A left-aligned single digit is not allowed, not even if the dashes start at the right place (1 ----- is invalid).
  • The clock should display the hours in a 24h-format.
  • Although it's called the 24h format, there is not actually a 24 on it. During the 23rd hour, the second line starts with 00 or 0.
  • The display needs to be updated at least once a minute, but that doesn't have to happen at exactly 00 seconds. You may update more frequently / continuously if that is more convenient, but the result must of course still be legible - not one smear all over the screen.

Input

None.

Output

  • As described above. Trailing spaces to pad the clock to 60-ish positions is allowed on both lines, a trailing newline is also allowed.
  • The screen needs to be cleared when displaying the next minute: either with a clear-screen command or by adding no less than 30 newlines.

Additional rules

steenbergh

Posted 2017-01-17T16:04:03.197

Reputation: 7 772

may we have two spaces between the number and the dashes? – Adám – 2017-01-17T16:48:59.157

@Adám I think not, see the last example in "To clarify" bullet #4. But this may not address your question, which is more general. – Timtech – 2017-01-17T16:49:43.493

6"updated once a minute" -- Can it be updated more often? – smls – 2017-01-17T16:49:59.050

1@smls Yes, you may update as often as you like. I'll change the specs to 'at least once a minute'. – steenbergh – 2017-01-17T17:52:17.513

@Adám No, only one space between the numbers and he dashes. – steenbergh – 2017-01-17T17:52:48.793

Does it have to print immediately or can it print after a minute? – George Reith – 2017-01-17T18:51:24.967

Just to clarify, is it okay for numbers less than 10 to be outputted like this 1 ----- without a leading space? – user41805 – 2017-01-17T18:52:46.810

1@KritixiLithos That would break alignment with two-digit hours (9, 10 or 23, 00), so no, not allowed. – steenbergh – 2017-01-17T19:04:29.820

Can I have a leading space on all lines (and two leading spaces for single digits)? It would save about a gajillion bytes in QBasic. – DLosc – 2017-01-17T19:31:23.947

Actually, it may not be a gajillion--looks like PRINT USING can be used to avoid the leading space for positive numbers. TIL. But thanks. :) – DLosc – 2017-01-17T19:49:09.900

1After 23, is the next hour 24 or 0? – user41805 – 2017-01-18T15:43:40.957

@KritixiLithos It's 0. – steenbergh – 2017-01-18T15:52:25.717

@steenbergh: You might want to clarify that in the question, since practically every submission has 24. – Nick Matteo – 2017-01-18T16:13:24.333

@kundor Added your suggestion. – steenbergh – 2017-01-18T16:25:32.707

Answers

2

MATL, 41 bytes

Thanks to @Kundor for noticing a mistake, now corrected

`XxFT"4&Z'@+24\OH&YAO'-'60@*5&Z'-|Y"hhD]T

Try it at MATL online! But note that the program is killed after 30 seconds, so it's difficult to catch any changes in the output.

How it works

`           % Do...while
  Xx        %   Clear screen
  FT        %   Push [0 1]
  "         %   For each k in [0 1]
    4&Z'    %     Push current hour
    @+      %     Add k
    24\     %     Modulo 24. This transforms 24 into 0
    OH&YA   %     Convert to base-10 string with 2 digits
    O       %     Push 0. Concatenating with chars will convert this to char,
            %     and char(0) will be displayed as a space
    '-'     %     Push '-'
    60@*    %     Push 60*k
    5&Z'    %     Push current minute
    -|      %     Absolute difference. This gives current minute for k==0,
            %     or 60 minus that for k==1
    Y"      %     Repeat '-' that many times
    hh      %     Concatenate the top three elements into a string
    D      %      Display
  ]         %   End
  T         %   Push true
            % End (implicit). Since the top of the stack contains true, this
            % gives an infinite loop

Luis Mendo

Posted 2017-01-17T16:04:03.197

Reputation: 87 464

Could be me, but at the second iteration, only the top line is printed... – steenbergh – 2017-01-17T17:28:08.100

@steenbergh It works for me with minutes and seconds instead of hours and minutes, so the changes are easily seen: https://matl.suever.net/?code=%60XxFT%225%26Z%27%40%2BOH%26YAO%27-%2760%40%2a6%26Z%27-%7CkY%22hhD%5DT&inputs=&version=19.7.1

– Luis Mendo – 2017-01-17T17:56:12.267

1Yep, works. - in fact, might be cool to have this as lines 3 and 4 of my own clock. – steenbergh – 2017-01-17T18:01:15.460

@steenbergh: you accepted this answer, but it's not valid—it shows the hour after 23 as 24. I believe the shortest correct answer is the Ruby one by Value Ink. – Nick Matteo – 2017-01-22T23:06:37.500

@kundor Thanks for noticing. Corrected at the cost of 3 bytes – Luis Mendo – 2017-01-23T00:31:38.793

11

TI-Basic, 94 bytes

" 
Repeat 99<length(Ans
Ans+"-
End
Ans→Str1
Repeat 0
getTime
ClrDraw
Ans{Ans(1)≠24,1,1
Text(0,0,Ans(1),sub(Str1,1,1+Ans(2
Text(6,0,Ans(1)+1,sub(Str1,1,61-Ans(2
End

Relatively straightforward. That's a string with one space at the beginning. The hours are right-aligned. This only works on TI-84+ calculators since the TI-83 does not have an internal clock.

Edit: Thanks @kundor for noticing that I didn't close the last loop. Fixed now (+2 bytes).

Edit #2: First hour should be zero, not twenty-four. Corrected at a cost of +14 bytes.

Timtech

Posted 2017-01-17T16:04:03.197

Reputation: 12 038

Every command count as one byte ? – Sygmei – 2017-01-17T16:39:48.087

@Sygmei Most tokens are one byte, yes. However, tokens such as Str1, getTime, and sub( are two bytes each. You can learn more at http://tibasicdev.wikidot.com/tokens

– Timtech – 2017-01-17T16:41:04.450

You wouldn't happen to have a link to an emulator, would you? – steenbergh – 2017-01-17T16:43:41.340

I would recommend https://www.cemetech.net/projects/jstified/ but do remember that it's morally wrong to use a ROM from the internet with this emulator unless you own that type of calculator yourself.

– Timtech – 2017-01-17T16:45:43.593

I would never, ever use this ROM to actually calculate anything! Perish the thought. – steenbergh – 2017-01-17T16:50:21.150

1Don't be scared to click the link, because the emulator is legit and asks you to upload your own ROM before it will work. TI used to have them freely available but they're not any more. If you can find a TI-84 from a friend, that would be the best option. – Timtech – 2017-01-17T16:51:32.823

At least in wabbitemu on my phone, this doesn't seem to update unless I add End at the end of the program, in which case it blinks constantly. – Nick Matteo – 2017-01-17T19:21:28.783

Hey @kundor, it was my fault that I didn't add the End statement -- thanks for the catch. But, the blinking may be a result of the emulator. If you want, clearing the ClrDraw command may give you nicer results on your emulator. It's required for the challenge, though. – Timtech – 2017-01-17T21:20:19.257

9

Batch, 197 bytes

@echo off
set/ah=100+%time:~0,2%,m=1%time:~3,2%
cls
call:l
set/ah=(h-3)%%24+100,m=260-m
call:l
timeout/t>nul 60
%0
:l
set s=%h:~1% 
for /l %%i in (101,1,%m%)do call set s=%%s%%-
echo %s%

Note: 10th line has a trailing space. For me, %time% formats hours with a leading space but minutes with a leading zero. I decided a leading zero was an easier output format, since all I have to do for that is to add 100 hours and remove the first digit. Minutes are trickier as 08 or 09 will cause octal parse errors, so I prefix a 1 effectively adding 100 minutes, adjusting for this by offsetting the loop appropriately, which is a byte shorter than subtracting the 100.

Neil

Posted 2017-01-17T16:04:03.197

Reputation: 95 035

7

Python 3.6, 110 114 112 bytes

from time import*
while[sleep(9)]:h,m=localtime()[3:5];print('\n'*50+'%2d '%h+'-'*m+f'\n{-~h%24:2} '+'-'*(60-m))

This uses the new f-string formatting to save one byte (f'\n{h+1:2} ' vs '\n%2d '%(h+1).) You can change [sleep(9)] to 1 to save 8 bytes, but then it just spams the screen.

Saved one byte changing while 1:...;sleep 60 to while[sleep(60)]:..., thanks to TuukkaX.

I had to use 5 more bytes to get the next hour displayed after 23 to be 0, instead of 24, as OP just commented. :-(

Recovered one byte by only sleeping 9 seconds instead of 60.

Saved two bytes using a bit-fiddling to shorten (h+1)%24, borrowed from Value Ink's Ruby answer.

Nick Matteo

Posted 2017-01-17T16:04:03.197

Reputation: 591

Could you please explain why you've put square brackets around the if condition? Wouldn't just having the space between while and sleep be 1 byte, as opposed to the 2 on either side? EDIT: Never mind, it's to make it truthy. Fair enough. – Shadow – 2017-01-19T03:22:54.920

1@shadow: sleep returns None, which is falsy. – Nick Matteo – 2017-01-19T03:24:32.010

@ToivoSäwén: sleep is also in the time module, so importing * is better. – Nick Matteo – 2017-01-19T16:50:33.407

5

Ruby, 98 95 91 bytes

Updates every 5 seconds. Only works in Unix-style terminals.

loop{t=Time.now;puts`clear`+"%02d %s
%02d "%[h=t.hour,?-*m=t.min,-~h%24]+?-*(60-m);sleep 5}

Windows command prompt version, 95 92 bytes:

loop{t=Time.now;puts"\e[H\e[2J%02d %s
%02d "%[h=t.hour,?-*m=t.min,-~h%24]+?-*(60-m);sleep 5}

Value Ink

Posted 2017-01-17T16:04:03.197

Reputation: 10 608

Can you use backticks instead of system? \cls`` vs system'cls' – IMP1 – 2017-01-18T10:14:59.487

It seems not, but you can use h=t.hour and then use h instead of the second t.hour, which saves 3 bytes. – IMP1 – 2017-01-18T10:26:24.227

@IMP1 indeed, backticks don't work for cls. Thanks for your other suggestion, though! – Value Ink – 2017-01-18T11:53:04.493

@IMP1 as it turns out, puts\clear`` is the way to go if you use Unix terminals. It just doesn't work with the Windows command prompt cls. – Value Ink – 2017-01-18T11:58:13.843

For windows, you can puts"\e[H\e[2J" to clear the console, which I think shaves four bytes. It would make your first line read loop{t=Time.now;puts"\e[H\e[2J%02d %s – IMP1 – 2017-01-18T12:03:48.387

@IMP1 thanks! Although, it only saved 3 bytes AFAIK – Value Ink – 2017-01-18T12:19:10.180

4

Perl 6, 113 bytes

loop {$_=DateTime.now;.put for |('' xx 30),|([\+](.hour,1)».fmt('%2s')Z('-' Xx[\-](.minute,60)».abs));sleep 60}

Try it once with a one second timeout.

Or try an altered version that outputs the result of running for several hours.

Expanded:

loop {                  # keep repeating forever

  $_ = DateTime.now;    # assign an object representing the current time

    .put                # print with trailing newline
                        # ( adds a space between numbers and dashes )

  for                   # for each of the following

    |(                  # make it a slip so that it is all part of one list

      '' xx 30          # 30 empty strings (30 empty lines)
    ),

    |(

        [\+](           # triangle produce
          .hour,        # the hour
          1             # the hour plus one

        )».fmt( '%2s' ) # both formatted to two element string ( space padded )

      Z                 # zipped with

        (
            '-'         # a dash

          Xx            # cross (X) using string repeat (x) operator

            [\-](       # triangle produce
              .minute,  # the minute
              60        # the minute minus 60

            )».abs      # absolute value of both
        )
    );

  sleep 60              # wait until the next minute
}

Brad Gilbert b2gills

Posted 2017-01-17T16:04:03.197

Reputation: 12 713

What operators does the 'triangle produce' support? In [\+] it adds and in [\-] it seems to subtract. Does this work with multiplication and such? – Yytsi – 2017-01-17T17:50:11.813

@TuukkaX It should work with almost all infix operators. It is basically the same as [+] LIST which is reduce, except it gives you the intermediate values. See the docs page for produce

– Brad Gilbert b2gills – 2017-01-17T20:28:25.213

4

Java 8, 313 300 299 bytes

import java.time.*;()->{for(int c=0,h=LocalDateTime.now().getHour(),m=LocalDateTime.now().getMinute(),i;;)if(c>30){c=0;String l="",u,d;for(i=0;i++<60;)l+="-";u=l.substring(0,m);d=l.substring(m);System.out.println((h<10?"0":"")+h+" "+u+"\n"+(h<9?"0":"")+(h+1)+" "+d);}else{c++;System.out.println();}}

This only updates every 30 iterations of the while loop. The other 29 iterations just print new lines.

Updated

Saved 13 14 bytes due to Kevin Cruijssen's help! Thanks!

CraigR8806

Posted 2017-01-17T16:04:03.197

Reputation: 480

Hi, welcome to PPCG! First of all, only programs/functions are allowed, and your current code is a snippet. You'll have to surround it with a method (i.e. void f(){...} and need to add the imports it required (in your case import java.time.*;). That being said, your code can be golfed at multiple places to lower it to 311 bytes (even with the added method-declaration and import). (Since it's too long for this comment, I've placed it in the next comment.. xD) – Kevin Cruijssen – 2017-01-18T08:02:42.450

import java.time.*;void f(){for(int c=0,h=LocalDateTime.now().getHour(),m=LocalDateTime.now().getMinute(),i;;)if(c>99){c=0;String l="",u,d;for(i=0;i++<61;)l+="-";u=l.substring(0,m);d=l.substring(m);System.out.println((h<10?"0":"")+h+" "+u+"\n"+(h<9?"0":"")+(h+1)+" "+d);}else{c++;System.out.println();}} (303 bytes) I recommend reading Tips for Golfing in Java and Tips for golfing in <all languages>. Enjoy your stay. – Kevin Cruijssen – 2017-01-18T08:20:16.143

@KevinCruijssen I updated my answer and was able to save 3 more bytes by using lambda notation. Also I changed a few pieces to the code you provided, as well, to meet the specifications (e.g. for(i=0;i++<60 instead of 61 and (h<10? instead of 9. Thanks for informing me about method declaration and some golfing tips! – CraigR8806 – 2017-01-18T12:36:26.373

Ah, the 61 instead of 60 was indeed my mistake. I thought I had written it as for(i=0;++i<61 instead of for(i=0;i++<61 (in this second case it should indeed be 60, and even though it's the same amount of bytes, it's probably more obvious/readable). The h<9 in my code is correct, though. You had h+1<10 before and I simply changed this to h<9 by removing 1 on both sides. :) – Kevin Cruijssen – 2017-01-18T13:52:36.650

1@KevinCruijssen Ha I didn't pick up on that! h<9. I will edit it to save 1 more byte. Thanks again! – CraigR8806 – 2017-01-18T13:54:31.647

4

QBasic, 120 127 121 bytes

Don't run this for very long or your laptop will catch fire. Now 99.several9s% more CPU-efficient.

CLS
m=TIMER\60
h=m\60
m=m MOD 60
FOR i=1TO 2
?USING"## ";h MOD 24;
FOR j=1TO m
?"-";
NEXT
?
h=h+1
m=60-m
NEXT
SLEEP 1
RUN

Ungolfed and explanation

DO
    CLS
    totalMinutes = TIMER \ 60
    hour = totalMinutes \ 60
    minute = totalMinutes MOD 60

    FOR row = 1 TO 2
        PRINT USING "## "; hour MOD 24;
        FOR j = 1 TO minute
            PRINT "-";
        NEXT j
        PRINT

        hour = hour + 1
        minute = 60 - minute
    NEXT row

    SLEEP 1
LOOP

We start by clearing the screen, then get the current hours and minutes from TIMER, which returns the number of seconds since midnight.

This is the first time I've tried PRINT USING, so I was delighted to discover that it doesn't suffer from the usual QBasic quirk that positive numbers are printed with a leading space. ## as the format specifier ensures that single-digit numbers are right-aligned and padded with a space, as required. We have to use a loop for the hyphens, unfortunately, since QBasic does not have a string repetition function. (If I'm mistaken, please let me know!)

All the PRINT statements end with ; to suppress the newline; but after the hyphens, we need a newline; thus, the solitary ? after the inner FOR loop.

The SLEEP 1 is now necessary. Without it, the screen gets cleared so quickly after printing that it's just a flickering mess. (I used LOCATE 1 instead of CLS at first for that reason, until I realized that CLS with SLEEP is shorter anyway.) RUN restarts the program from the top--the shortest way to get an infinite loop.

DLosc

Posted 2017-01-17T16:04:03.197

Reputation: 21 213

How does this handle the last hour of the day? Top line reads 23, but what;'s the hour on the bottom line? – steenbergh – 2017-01-17T21:04:47.940

I'm using the Note7 and thinking of running this program for the foreseeable future in place of my status bar clock. Is that a good idea? – owlswipe – 2017-01-17T21:39:01.540

@steenbergh Whoops, fixed. It would be helpful for you to mention that edge case in the question. – DLosc – 2017-01-17T22:03:18.310

@DLosc Nah, I'm just joking :)). But yeah, smart!! – owlswipe – 2017-01-18T00:16:11.723

@DLosc I see you're still just adding 1 to the hour for line 2. Again, I don't see how does this handles 23/00? – steenbergh – 2017-01-18T06:35:33.270

1@steenbergh He prints h MOD 24, if initially h=23 then the next loop cycle its 24 and gets modded to 0. But I'm curious if it works as well. The CLS clears the first line so there are never both printed lines on the screen, right? – Jens – 2017-01-18T07:18:26.690

@Jens it works fine -- the CLS is only called when the main loop (defined by RUN) loops, so both lines are printed, then there's the SLEEP 1, then the CLS etc. – Chris H – 2017-01-18T12:15:22.640

In the line FOR j=1TO m what happens if m is 0? Does it skip or result in an endless loop? Online interpreters seem to go into an endless loop. – styletron – 2017-01-18T21:03:51.663

@styletron It works as expected (skips the loop) in QB64 and on archive.org. Other emulators I've tried (such as repl.it) are very incomplete, so I'm not surprised to hear that they're buggy.

– DLosc – 2017-01-19T06:40:49.027

4

C, 176 162 161 160 156 bytes

This is a gross abuse of pointers but compiles and runs as specified. Be sure to compile without optimization otherwise you are likely to hit a segfault.

main(){int*localtime(),b[9],*t;memset(b,45,60);for(;;)time(&t),t=localtime(&t),usleep(printf("\e[2J%.2d %.*s\n%.2d %.*s\n",t[2],t[1],b,t[2]+1,60-t[1],b));}

Ungolfed:

#import<time.h>
main()
{
 int *t,b[60];
 memset(b,45,60);
 for(;;) {
  time(&t);
  t=localtime(&t);
  usleep(printf("\e[2J%.2d %.*s\n%.2d %.*s\n",t[2],t[1],b,t[2]+1,60-t[1],b));
 }
}

Seth

Posted 2017-01-17T16:04:03.197

Reputation: 276

3

Python 2, 131 129 127 bytes

from time import*
while[sleep(9)]:exec(strftime("a='%H';b=int('%M')"));print "\n"*30+a+" "+"-"*b+"\n"+`int(a)+1`+" "+"-"*(60-b)

saved a byte thanks to @TuukkaX

ovs

Posted 2017-01-17T16:04:03.197

Reputation: 21 408

2You don't need the newline and space after the while 1: – Post Rock Garf Hunter – 2017-01-17T19:02:27.213

I started your code @19:55. At 20:01, I see 19 - \n 20 -----------------------------------------------------------. The hours aren't updating... – steenbergh – 2017-01-17T19:02:40.677

@steenbergh I tried it myself by setting the clock manually and it works for me. – ovs – 2017-01-17T19:07:24.573

@ovs aren't clock challenges fun :-). Anyway, probably something with repl.it then... – steenbergh – 2017-01-17T19:09:13.120

head-desk The Repl.it server is one hour behind to my local time... And it even says so at the very top of the console. I'll see myself out, thanks... – steenbergh – 2017-01-17T19:14:36.477

3

JavaScript (ES6), 162 bytes

Updates once per second

setInterval(c=>{c.clear(d=new Date,m=d.getMinutes(),h=d.getHours(),H=_=>`0${h++}`.slice(-2)),c.log(H()+` ${'-'.repeat(m)}
${H()} `+'-'.repeat(60-m))},1e3,console)

George Reith

Posted 2017-01-17T16:04:03.197

Reputation: 2 424

You can save quite a few bytes by restructuring the code so it is only one statement (it's possible to call console.clear() inside the console.log argument) and assigning in unused parentheses as much as possible. Version for 154B: setInterval(c=>c.log(H(h,c.clear(d=new Date))+\ ${'-'.repeat(m)} ${H(h+1)} `+'-'.repeat(60-m)),1e3,console,m=d.getMinutes(h=d.getHours(H=$=>$<9?'0'+$:$)))`. – Luke – 2017-01-17T19:56:07.207

You can save a bunch of byte by putting the hours and minutes into a single function m=>\0${h++} .slice(-3)+'-'.repeat(m)`. – Neil – 2017-01-17T21:31:07.783

3

C 251 267 251 bytes

 #include<time.h>f(){time_t t;struct tm *t1;h,m,i;while(1){time(&t);t1=localtime(&t);h=t1->tm_hour;m=t1->tm_min;printf("%d ",h);for(i=1;i<=m;i++)printf("-");puts("");printf("%d ",h+1);for(i=0;i<=59-m;i++)printf("-");puts("");sleep(1);system("clear");}}

Ungolfed version

#include<time.h>
void f()
{
 time_t t;
 struct tm *t1;
 int h,m,i;

 while(1)
 {
  time(&t);     
  t1=localtime(&t);
  h=t1->tm_hour;
  m=t1->tm_min;

  printf("%d ",h);
  for(i=1;i<=m;i++)
   printf("-");

  puts("");
  printf("%d ",h+1);

  for(i=0;i<=59-m;i++)
   printf("-");

  puts("");    

  sleep(1);
  system("clear");    
 }
}

Gets the work done! Can definitely be shortened in some way. Assume unistd.h file is included.

@Neil Thanks for the info.

@Seth Thanks, for saving 8 bytes.

Abel Tom

Posted 2017-01-17T16:04:03.197

Reputation: 1 150

IIRC you have to include everything necessary to get the code to compile (in this case, the definitions of time_t and struct tm) in your byte count. – Neil – 2017-01-17T21:33:02.403

Instead of printf("\n"); you can use puts(""); – Seth – 2017-01-19T04:04:47.203

3

PHP, 104 105 bytes

<? for(;;sleep(6))printf("%'
99s%2d %'-".($m=date(i))."s
%2d %'-".(60-$m).s,"",$h=date(H),"",++$h%24,"");

showcase for printf´s custom padding characters:
"%'-Ns"=left pad string with - to N characters.

will print 99 newlines (every 6 seconds) instead of clearing the screen.

First newline must be a single character. So, on Windows, it must be replaced with \n.

Titus

Posted 2017-01-17T16:04:03.197

Reputation: 13 814

3

First time golfing...

Powershell, 116 bytes (was 122)

while($d=date){$f="{0:D2}";$h=$d.Hour;$m=$d.Minute;cls;"$($f-f$h)$("-"*$m)`n$($f-f(++$h%24))$("-"*(60-$m))";Sleep 9}

Edit: From @AdmBorkBork's advice, changed Get-Date to date, and Clear to cls, for a saving of 6 bytes.

mcmurdo

Posted 2017-01-17T16:04:03.197

Reputation: 71

Welcome to PPCG, good answer – george – 2017-01-19T15:28:25.257

Welcome to PPCG! A couple easy golfs -- you can use cls instead of clear and (so long as you're on Windows) date instead of get-date. I'm also sure there's some easier way to output the formatting -- I'm playing with it and I'll let you know if I come up with anything. – AdmBorkBork – 2017-01-19T18:19:20.963

Nice. Try this: 108 bytes while($d=date){cls;"{0,2} {2}``n{1,2} {3}"-f($h=$d.Hour),(++$h%24),('-'*($m=$d.Minute)),('-'*(60-$m));Sleep 9}. Use LF line break in your editor instead ``n` – mazzy – 2018-08-09T21:57:26.990

2

GameMaker Language, 134 bytes

s=" "while 1{s+="-"a=current_hour b=current_minute draw_text(0,0,string(a)+string_copy(s,1,b+1)+"#"+string(a+1)+string_copy(s,0,61-b)}

In the settings, you must be ignoring non-fatal errors in order for this to work. Also, in GML, # is equivalent to \n in most languages.

Timtech

Posted 2017-01-17T16:04:03.197

Reputation: 12 038

2

Perl 6, 104 bytes

DateTime.now.&{"\ec{.hour.fmt: '%2s'} {'-'x.minute}\n{(.hour+1).fmt: '%2s'} {'-'x 60-.minute}"}.say xx*

Needs to be run on a ANSI compatible terminal so that the control sequence for resetting the terminal works.

Pretty basic (because the more obfuscated approaches I tried turned out longer):

  • DateTime.now.&{" "}.say xx*: Transform the current time into a string (see below) and say it, and repeat all of that an infinite number of times. The string is built like this:
    • \ec: ANSI control code <ESC>c for resetting the terminal, which clears the screen.
    • {.hour.fmt: '%2s'}: hour, right-aligned to 2 columns
    • : space
    • {'-'x.minute}: dash repeated times the minute
    • \n: newline
    • {(.hour+1).fmt: '%2s'}: next hour, right-aligned to 2 columns
    • : space
    • {'-'x 60-.minute}: dash repeated times 60 minus the minute

smls

Posted 2017-01-17T16:04:03.197

Reputation: 4 352

2

PHP, 112 120 bytes

for(;;sleep(9))echo($s=str_pad)($h=date(H),99,"\n",0).$s(" ",1+$m=date(i),"-")."\n".$s(++$h%24,2,0,0).$s(" ",61-$m,"-");

As there's no way to clear the screen (that I can find) I had to go with a pile of newlines. Also the question being updated to "at least" once a minute saves a byte with 9 instead of 60.

edit: @Titus noticed a bug in the padding of the second hour. Fixing it cost 8 bytes.

user59178

Posted 2017-01-17T16:04:03.197

Reputation: 1 007

This displays warning text on stdout along with the correct output: Notice: Use of undefined constant str_pad - assumed 'str_pad' in C:\wamp64\www\my-site\a.php on line 2 - Notice: Use of undefined constant H - assumed 'H' in C:\wamp64\www\my-site\a.php on line 2 - Notice: Use of undefined constant i - assumed 'i' in C:\wamp64\www\my-site\a.php on line 2. Anything on Meta about that? – steenbergh – 2017-01-17T18:46:11.880

@steenbergh That´s a notice; it will not be displayed if you use default values (command line parameter -n or error_reporting(22519); – Titus – 2017-01-17T19:39:30.510

hours must be padded to length 2 – Titus – 2017-01-17T20:27:11.260

Good point, the H setting for date goes from 00-23, but I forgot about it for the second hour. – user59178 – 2017-01-18T15:51:14.360

Save two bytes with physical linebreaks. – Titus – 2017-02-02T03:08:44.800

... and 7 more with this: Remove 1+ and replace everything from ."\n" to the end with $p(date("-\ns ",++$h%24),65-$i,"-");. – Titus – 2017-02-02T03:25:01.553

2

Python 3.5, 127 120 117 bytes

from time import*
while[sleep(9)]:h,m=localtime()[3:5];print('\n'*88,*['%2d '%x+'-'*y+'\n'for x,y in[(h,m),(h+1,60-m)]])

Gurupad Mamadapur

Posted 2017-01-17T16:04:03.197

Reputation: 1 791

1Can you not just print('\n'*50) instead of os.system('cls') so it works on both *nix and Windows? Would save a couple of bytes as you can lose the os import and OP says that this is allowed. – ElPedro – 2017-01-17T20:57:42.153

Oh, I didn't read it properly then. Thanks a lot man. – Gurupad Mamadapur – 2017-01-17T21:25:13.407

Just for info, most people tend to use <s></s> around their old byte count and then put the new byte count after it because it is interesting to see the progress as an answer is improved :-) Must try 3.5 some time. I'm still working with Python 2. – ElPedro – 2017-01-17T21:57:59.410

1@ElPedro Yea I forgot to do it. I'll edit now. – Gurupad Mamadapur – 2017-01-17T21:59:31.230

2

Python, 115 113 bytes

saved a couple of bytes thanks to @kundor and @Phlarx

import time
while 1:h,m=time.localtime()[3:5];print("\x1b[0;H{:02} {}\n{:02} {} ".format(h,"-"*m,h+1,"-"*(60-m)))

dfernan

Posted 2017-01-17T16:04:03.197

Reputation: 528

At least on my system, this doesn't erase underlying characters, so that the number of dashes on the second line doesn't go down as time passes. Also: you can save three bytes by putting your while loop on one line, and two bytes by changing the :02 formats to just :2. – Nick Matteo – 2017-01-17T20:58:39.140

2You can fix the issue described by @kundor in 1 byte by adding a space after the corresponding {}. – Phlarx – 2017-01-17T21:23:19.767

@kundor fixed! Thanks. I kept the :02 format to right-pad one digit hours with zeroes. – dfernan – 2017-01-18T08:35:25.187

@kundor *left-pad one digit hours with zeroes. – dfernan – 2017-01-18T11:00:03.933

@dfernan: Well, :2 left-pads with spaces, which the challenge says is OK. – Nick Matteo – 2017-01-18T16:11:35.903

2

AWK, 190 bytes

#!/bin/awk -f
func p(x,y,c){printf("%2s ",x)
for(j=0;j<y;j++)printf(c)
print}BEGIN{for(;;){split(strftime("%H %M"),t)
m=t[2]
if(o!=m){p(a,30,"\n")
p(t[1],m,"-")
p((t[1]+1)%24,60-m,"-")}o=m}}

Since AWK doesn't have a built-in sleep function, I simply have it continually check the clock to see if the minute has changed yet. The key thing is that it works... right? :)

Robert Benson

Posted 2017-01-17T16:04:03.197

Reputation: 1 339

2

BASH, 165 141 155 bytes

while :
do
clear
m=`date +%-M`
a=`printf %${m}s`
b=`printf %$((60-m))s`
h=`date +%H`
echo $h ${a// /-}
printf "%02d %s" $((10#$h+1)) ${b// /-}
sleep 9
done

pLumo

Posted 2017-01-17T16:04:03.197

Reputation: 121

1I could save another 8 bytes removing the sleep, but I'm not comfortable with an indefinite while loop running on my computer without a sleep ;-) – pLumo – 2017-01-17T21:46:32.963

Some optimizations: move sleep 9 to the condition of the while loop; remove the - in front of M in the format string on line 4. You also don't need to use $ in front of variable names in arithmetic expressions, so $((60-$m)) can be $((60-m)) – Evan Krall – 2017-01-19T00:52:43.290

I'm not sure whether your math on line 9 is accurate: h=23; echo $((10#$h+1)) prints 24 for me. – Evan Krall – 2017-01-19T00:52:49.337

Whats wrong with 24? – pLumo – 2017-01-19T06:34:12.963

I need the -M because $((60-08)) gives an error. – pLumo – 2017-01-19T06:35:56.470

If I put sleep in the condition, which saves me 2 bytes, I would need to wait 9 seconds for the clock to appear ...

$((60-m)) saves me 1 byte though. Thanks ! – pLumo – 2017-01-19T08:06:35.203

2

C# Interactive (138 Bytes)

while(true){var d=DateTime.Now;Console.WriteLine($"{d.Hour:00} {new string('-',d.Minute)}\n{d.Hour+1:00} {new string('-',60-d.Minute)}");}

Matthew Layton

Posted 2017-01-17T16:04:03.197

Reputation: 129

1Can you golf this down by 1) naming the date var d instead of dt? and 2) use sleep(1e3) or 999 instead of 1000? – steenbergh – 2017-01-18T14:10:58.353

@steenbergh see update – Matthew Layton – 2017-01-18T14:13:33.807

A few things... This is just a snippet not a method or program (not sure if it's valid in C# Interactive though), it is essentially a golfed version of my code, and if it is should have been commented as improvements not a separate solution (though this is speculation) and there are lots of small improvements you can make here, and do you even need the sleep? – TheLethalCoder – 2017-01-18T14:15:27.333

@TheLethalCoder I specifically put C# Interactive because this works in the interactive console ONLY. This would not work as a standard C# program. – Matthew Layton – 2017-01-18T14:16:53.260

Also note that this won't work when the hour is 23 and when the minute is 0 – TheLethalCoder – 2017-01-18T14:21:04.953

Golfing tips: true=>1>0, WriteLine=>Write, set d.Hour and d.Minute to variables etc... Also I don't know C# Interactive but you probably have to include using System; into the byte count – TheLethalCoder – 2017-01-18T14:27:03.063

@TheLethalCoder if you have VS2015+ you can try this out in interactive yourself...it comes shipped with VS, but thanks for the tips – Matthew Layton – 2017-01-18T14:28:23.560

Also this solution is invalid (assuming consecutive calls to Console.WriteLine don't clear the console in interactive) as each call is placed on top of the other and not clearing the console as required – TheLethalCoder – 2017-01-18T14:29:04.480

2

Bash (3 and 4): 90 bytes

d=(`sed s/./-/g<$0`);let `date +h=%H,m=%M`;echo $h ${d:0:m}'
'$[++h%24] ${d:m}
sleep 5
$0

Due to the use of $0, this script must be put into a file, not pasted into an interactive bash shell.

The first command sets $d to 60 hyphens; it relies on the fact that the first line of this script is 60 characters long. This is three characters shorter than the next best thing I could come up with:

d=`printf %060d|tr 0 -`

If you don't want this to run your box out of PIDs or memory eventually, you can add eval to the beginning of the last line, which would make this 95 bytes.

Evan Krall

Posted 2017-01-17T16:04:03.197

Reputation: 251

Gives me the error let: h=09: value too great for base (error token is "09"). Problem is that leading zeros are interpreted as octal constants, so 09 is invalid. – Nick Matteo – 2017-01-20T16:26:38.970

Hrm, that means my script is broken in several ways. Thanks. – Evan Krall – 2017-01-26T18:03:54.230

1

Gura, 138 bytes

k(a,b)={if(a<10){a="0"+a;}println(a," ","-"*b)};repeat{t=datetime.now();k(t.hour,t.min);k(t.hour+1,60-t.min);os.sleep(60);print("\n"*30);}

Pretty short and straightforward :)

Sygmei

Posted 2017-01-17T16:04:03.197

Reputation: 1 137

Wow ... That's fast. Any tips on running Gura? Just downloaded the binaries, but running Gura.exe and pasting in this code gives me a syntax error symbol k is not defined. – steenbergh – 2017-01-17T16:17:01.340

Forgot a semicolon ! You can try to run it again :) – Sygmei – 2017-01-17T16:19:05.883

1Does this update every minute? The console seems to run this code just once... – steenbergh – 2017-01-17T16:30:50.680

Woops, did not saw that part, should be working now ! – Sygmei – 2017-01-17T16:38:29.613

When it updates, it should either clear the screen or add 30 newlines. Man, I'm on your case... – steenbergh – 2017-01-17T16:43:00.663

I rushed, I should have been more attentive :/ – Sygmei – 2017-01-17T17:02:21.017

1

Ok, haven't done a code golf in a while, so here goes my sad attempt :)

Unix Korn Shell: 177 171 170 bytes

while :
do
clear
h=`date +%H`
m=`date +%M`
d=-----
d=$d$d$d$d
d=$d$d$d
a=`echo $d|cut -b-$m`
let m=60-$m
b=`echo $d|cut -b-$m`
let i=h+1
echo "$h $a\n$i $b"
sleep 9
done

Ditto

Posted 2017-01-17T16:04:03.197

Reputation: 495

spliced the 2 echos into 1, saved a few bytes ... (sleep 9 instead of sleep 10 saves 1 byte :P ) lol – Ditto – 2017-01-17T21:27:59.510

1

Processing, 204 200 198 197 bytes

5 bytes saved thanks to @L. Serné by using smarter ternaries

void draw(){int i;String s=((i=hour())>9?i:" "+i)+" ";for(i=0;i<minute();i++)s+="-";s+="\n"+((i=hour()+1)>9?i>23?" 0":i:" "+i)+" ";for(i=0;i<60-minute();i++)s+="-";print(s);for(;i++<99;)println();}

This outputs 30+ newlines for each update (which takes place when the frame gets updated)

Ungolfed

void draw(){
  int i;
  String s=((i=hour())>9?i:" "+i)+" ";
  for(i=0;i<minute();i++)
    s+="-";
  s+="\n"+((i=hour()+1)>9?i>23?" 0":i:" "+i)+" ";
  for(i=0;i<60-minute();i++)
    s+="-";print(s);
  for(;i++<99;)
    println();
}

user41805

Posted 2017-01-17T16:04:03.197

Reputation: 16 320

Changing ((i=hour())<10?" ":"")+i into ((i=hour())>9?i:" "+i) would save 2B twice... Good luck with further golfing! – Luke – 2017-01-17T20:14:09.377

@L.Serne thanks for the tip :) – user41805 – 2017-01-17T20:30:00.497

Another improvement that might work: ((i=hour()+1)>24?i=0:i)>9 becomes (i=hour()+1)>9, since hour outputs a number in the range 0-23, and even with 1 added to that, it'll never be greater than 24. Also, you should move the increment of i inside the condition in the for loop like you did in the very last loop. Should save 13B in total. – Luke – 2017-01-17T22:57:35.180

@L.Serné For the first point, I still have to include the ternary because 23+1 in a 24-hour clock becomes 0 (or at least I think). Next, if I move the increment of i inside the condition of the for-loop, i will start as 1 instead of 0 and I need to add one more byte i++<=minute() and the bytecount will still be the same. But nonetheless, thanks for helping me golf 1 more bytes :) – user41805 – 2017-01-18T15:48:04.500

1

Mathematica, 235 bytes

d=UpdateInterval;e=Dynamic;f=Refresh;g=AbsoluteTime;Grid[Partition[Riffle[e[f[Floor@Mod[g[]/3600+#,24],d->1]]&/@{0,1},With[{t=#},e[f[""<>Array["-"&,If[t==60,60-#,#]]&@Setting@Floor@Mod[g[]/60+#,60],d->1]]]&/@{0,60}],2],Alignment->Left]

martin

Posted 2017-01-17T16:04:03.197

Reputation: 1 335

1

Python3.5 104 127 125 bytes.

from time import* while[sleep(9)]:h,m=localtime()[3:5];print("{:02d} {}".format(h,m*'-'),end='\n'*30)

Riffing off Gurupad Mamadapur's answer above.

edit: xnor is right. This isn't a valid answer. - This misses the second line completely.

edit2: Instead, to at least have an answer that works:

from time import* while[sleep(9)]:h,m=localtime()[3:5];print("{:02d} {}\n{:02d} {}".format(h,m*'-',h+1,(60-m)*'-'),end='\n'*30)

edit3: Saved two bytes by moving the \n*30 to the format instead of the end='\n'*30

from time import*
while[sleep(9)]:h,m=localtime()[3:5];print("{}{:02d} {}\n{:02d} {}".format('\n'*30,h,m*'-',h+1,(60-m)*'-'))

Aaron

Posted 2017-01-17T16:04:03.197

Reputation: 11

I don't think this does the right thing. The next hour needs to be printed with a dash for each remaining minute to it. – xnor – 2017-01-18T01:45:24.477

1

C#, 192 185 176 172 169 bytes

Saved 3 bytes thanks to @nurchi

using System;()=>{for(;;){Console.Clear();var t=DateTime.Now;int h=t.Hour,m=t.Minute;Console.Write($"{h:00} {new string('-',m)}\n{++h%24:00} {new string('-',60-m)}");}};

Uses C# 6 features which I don't have access to so cannot test it properly yet.

Full version showing how it works and is called including a Thread.Sleep so the input can actually be seen. Note that this version shows the use of Console.Writes overload to use String.Format and doesn't use string interpolation like the golfed version above.

using System;

class P
{
    static void Main()
    {
        Action a = () =>
        {
            for (;;)
            {
                Console.Clear();

                var t = DateTime.Now;
                int h = t.Hour,m=t.Minute;

                Console.Write("{0:00} {1}\n{2:00} {3}", h, new string('-', m), ++h % 24, new string('-', 60 - m));

                System.Threading.Thread.Sleep(500);
            }
        };

        a();
    }
}

TheLethalCoder

Posted 2017-01-17T16:04:03.197

Reputation: 6 930

Your line does not include the Sleep (which is included in the full code), so the output will flicker. – nurchi – 2017-01-26T00:13:27.893

@nurchi the sleep is in the full code to view the output easier, as far as I am aware a smooth clock is not needed – TheLethalCoder – 2017-01-26T00:52:47.367

TheLethalCoder, you are right if the output doesn't flicker too much (it has to be legible). And I just tested it, it barely flickers, but this may depend on the system. My answer below is 176 chars with Sleep (but I rely on the using System.Threading;. I do like your code though. To further shorten it, replace your while(1>0){...} with for(;;){...} – nurchi – 2017-01-26T01:04:42.660

1

Guile, 146, 143 bytes

(while(sleep 9)(let*((t(gmtime(current-time)))(h(tm:hour t))(m(tm:min t)))(format #t "~d ~v,,'-t~%~d ~v,,'-t~%" h m(modulo(1+ h)24)(- 60 m))))

Shaved off three bytes thanks to ceilingcat.

Michael Vehrs

Posted 2017-01-17T16:04:03.197

Reputation: 771

1

C, 239 bytes

#include<time.h>
#include<unistd.h>
#define F printf(
void d(n,p){for(;n--;F"%c",p));}int main(){time_t*t;for(;;){d(30,10);time(t);int*m=localtime(t);F"%2d ",m[2]);d(m[1],45);F"\n%2d ",(m[2]+1)%24);d(60-m[1],45);F"\n");sleep(1);}return 0;}

Inspired by Seth's and Abel's entries, this will output 0 instead of 24 for the next hour, as required, and will use 30 lines to clear the screen.

Ahemone

Posted 2017-01-17T16:04:03.197

Reputation: 608

1

SmileBASIC, 55 bytes

TMREAD OUT H,M,
CLS?H,"-"*M?(H+1)MOD 24,"-"*(60-M)EXEC.

Explanation:

TMREAD OUT HOUR,MINUTE,
CLS
PRINT HOUR,"-"*MINUTE
PRINT (HOUR+1) MOD 24,"-"*(60-MINUTE)
EXEC 0 'runs the code stored in slot 0 (the default)

Note: SmileBASIC only has 50 columns of text, so it won't look good...

12Me21

Posted 2017-01-17T16:04:03.197

Reputation: 6 110

1

C# 181 176

for(;;){Console.Clear();var t=DateTime.Now;var h=t.Hour;var m=t.Minute;Console.Write("{0,2} {1}\n{2,2} {3}",h,"".PadLeft(m,'-'),++h%24,"".PadLeft(60-m,'-'));Thread.Sleep(100);}

This code assumes that the using System.Threading; line is included.

Full class:

class Program
{
    static void Main(string[] args)
    {
        Console.Title = string.Format("Started the app at: {0}", DateTime.Now.TimeOfDay);
        //new Timer((o) => { Console.Clear(); var t = DateTime.Now; var h = t.Hour; var m = t.Minute; Console.Write("{0,2} {1}\n{2,2} {3}", h, "".PadLeft(m, '-'), ++h % 24, "".PadLeft(60 - m, '-')); }, null, 0, 60000);

        for (; ; ) { Console.Clear(); var t = DateTime.Now; var h = t.Hour; var m = t.Minute; Console.Write("{0,2} {1}\n{2,2} {3}", h, "".PadLeft(m, '-'), ++h % 24, "".PadLeft(60 - m, '-')); Thread.Sleep(100); }

        Console.ReadKey(true);
    }
}

nurchi

Posted 2017-01-17T16:04:03.197

Reputation: 111

This solution has no way of exiting the loop (the original, commented, runs the code on a separate thread), so the Console.ReadKey statement is redundant. The only way to exit is to either close the console window or Ctrl+Break... – nurchi – 2017-01-26T00:38:28.003

This is only a code snippet not a method or program, also the using System.Threading; needs to be included in the byte count if you are using it. Same with Using System;. – TheLethalCoder – 2017-01-26T08:55:35.600

0

tcl, 164

while 1 {scan [clock f [clock se] -f %T] %d:%d h m
puts "[format %2s $h] [string repe - $m]\n[format %2s [expr ($h+1)%24]] [string repe - [expr 60-$m]]"
after 9999}

demo

sergiol

Posted 2017-01-17T16:04:03.197

Reputation: 3 055

This code can be golfed quite a bit. This is only 165 bytes. Also, it doesn't clear the screen (or add 30 newlines) between frames.

– steenbergh – 2017-01-24T06:33:56.403

@steenbergh When I execute the code of your link I get errors. – sergiol – 2017-02-04T16:06:00.943

Oh, now I see what happened. That environment just kept running your original code instead of running my modifications. Sorry about that... – steenbergh – 2017-02-04T18:50:48.447

0

Bash + Coreutils, 114 bytes

while sleep 9; do date +'%k %_M'|{ read h m;printf %02d:%${m}s\n$((h+1)):%$((60-m))s\n" $h|tr " :"  "- "; }; done

Michael Vehrs

Posted 2017-01-17T16:04:03.197

Reputation: 771