時計の挑戦の時です!


25

次の形式で時間を表示する時計を作成してください。

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

これは「18:10」を表示します。現在の時間と次の時間が行の先頭に表示され、その後にスペースとダッシュの数が続きます。最初の行にはこの時間で経過した分数、2行目はあと何分かを示しますこの時間に行きます。

明確にするために

  • 時計はシステムの時刻を表示する必要があります。別のソースから時間を取得する方が便利な場合は、それでも問題ありません。それはないかもしれません、入力として供給すること。
  • 18:00、トップラインがちょうどある18(末尾のスペースが必要な許可はありません)
  • 18:59、一番下の行は、19 -
  • 10時間未満は、001 -----)で事前に埋め込まれるか、右揃え( 1 -----)でます。左揃えの1桁は、ダッシュが正しい場所から始まっている場合でも1 -----無効です(無効です)。
  • 時計は24時間形式で時間を表示する必要があります。
  • 24h形式と呼ばれていますが、実際にはありません24。23時間目の間に、2行目は00または 0ます。
  • 表示は少なくとも1分間に1回更新する必要がありますが、正確に00数秒で更新する必要はありません。それがより便利な場合は、より頻繁に/継続的に更新できますが、結果はもちろん判読可能でなければなりません-画面全体に1つのスミアはありません。

入力

なし。

出力

  • 上記のように。クロックを60桁の位置に埋め込むための末尾のスペースは両方の行で許可されますが、末尾の改行も許可されます。
  • 次の分を表示するときは、画面をクリアする必要があります:clear-screenコマンドを使用するか、30行以上の改行を追加します。

追加のルール


数字とダッシュの間に2つのスペースがありますか?
アダム

6
「1分間に1回更新」-より頻繁に更新できますか?
SMLS

1
@smlsはい、何度でも更新できます。仕様を「少なくとも1分間に1回」に変更します。
steenbergh

1
@KritixiLithosこれは、2桁の時間(9、10、または23、00)でアライメントを壊すため、許可されません。
steenbergh

1
23の後、次の1時間は24ですか、それとも0ですか?
クリチキシリトス

回答:


2

MATL、41バイト

間違いに気付いた@Kundorに感謝します。

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

MATLオンライン試しくださいただし、プログラムは30秒後に強制終了されるため、出力の変更をキャッチすることは困難です。

使い方

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

私にできるが、2回目の反復では、唯一のトップラインが印刷されています...
steenbergh

変更が簡単に見られるよう@steenberghそれは、分、秒の代わりに、時間と分で私の作品:matl.suever.net/...
ルイスMendo

1
はい、動作します。-実際、これを自分の時計の3行目と4行目として使うといいかもしれません。
steenbergh

@steenbergh:あなたはこの答えを受け入れましたが、それは有効ではありません。23時間後の24時間を示しています。最短の正解はValue InkによるRubyの答えだと思います。
ニックマッテオ

@kundor気づいてくれてありがとう。3バイトのコストで修正
ルイスメンドー

11

TI-Basic、94バイト

" 
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

比較的簡単です。これは、先頭にスペースが1つある文字列です。時間は右揃えです。TI-83には内部クロックがないため、これはTI-84 +計算機でのみ機能します。

編集:私は最後のループを閉じていないことに気付いて@kundorに感謝します。修正されました(+2バイト)。

編集#2:最初の1時間は24ではなく0でなければなりません。+14バイトのコストで修正されました。


すべてのコマンドは1バイトとしてカウントされますか?
シグメイ

@Sygmeiほとんどのトークンは1バイトです、はい。しかし、などトークンStr1getTimeおよびsub(各バイトの2つです。詳細については、tibasicdev.wikidot.com / tokens
Timtech

エミュレータへのリンクはたまたまありませんか?
steenbergh

cemetech.net/projects/jstifiedをお勧めしますが、自分でそのタイプの電卓を所有していない限り、このエミュレータでインターネットのROMを使用するのは道徳的に間違っていることを覚えています。
ティムテック

1
エミュレータは正当であり、動作する前に独自のROMをアップロードするように要求するため、リンクをクリックするのを恐れないでください。TIは以前は無料で利用できるようにしていましたが、それ以上ではありません。友人からTI-84を見つけることができれば、それが最良の選択肢でしょう。
ティムテック

9

バッチ、197バイト

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

注:10行目には末尾スペースがあります。私にとっては、%time%時間を先行スペースでフォーマットしますが、分を先行ゼロでフォーマットします。先行ゼロは簡単な出力形式であると判断しました。そのために必要なのは、100時間を追加して最初の数字を削除するだけです。分としてトリッキーです0809私は接頭辞ので、進解析エラーが発生します1100を引いよりバイト短い適切にループを、相殺することで、このために調整し、効果的に追加する100分。


7

パイソン3.6、110の 114 112バイト

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

これは、新しいf-stringフォーマットを使用して1バイトを保存します(f'\n{h+1:2} 'vs. '\n%2d '%(h+1))8バイトを保存[sleep(9)]する1ように変更できますが、その後は画面をスパムします。

TuukkaXのおかげで、1バイトをに変更while 1:...;sleep 60して保存while[sleep(60)]:...しました。

OPがコメントしたように、23の後に表示される次の時間を24ではなく0にするには、さらに5バイトを使用する必要がありました。:-(

60秒ではなく9秒だけスリープして1バイトを回復しました。

Value InkのRuby answer(h+1)%24から借用して、ビットフィドリングを使用して2バイトを短縮しました。


if条件を角かっこで囲んだ理由を説明してください。whileとsleepの間のスペースが1バイトであるのではなく、どちらかの側の2バイトではありませんか?編集:気にしないで、それを真実にすることです。けっこうだ。
シャドウ

1
@shadow:をsleep返しますがNone、これは偽です。
ニックマッテオ

@ToivoSäwén:sleeptimeモジュール内にあるため、*をインポートする方が適切です。
ニックマッテオ

5

ルビー、98 95 91バイト

5秒ごとに更新します。Unixスタイルの端末でのみ機能します。

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

Windowsコマンドプロンプトバージョン、95 92バイト:

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

システムの代わりにバックティックを使用できますか?`cls`vssystem'cls'
IMP1

そうではないようですが、使用してh=t.hourからh2番目の代わりに使用してt.hour、3バイトを節約できます。
IMP1

実際、@ IMP1では、バックティックは機能しませんcls。ただし、他の提案をありがとう!
バリューインク

結局のところ、@ IMP1 puts`clear`は、Unix端末を使用する場合の方法です。Windowsコマンドプロンプトでは機能しませんcls
バリューインク

Windowsの場合puts"\e[H\e[2J"、コンソールをクリアできます。これにより、4バイト削減できます。最初の行が読み取られるloop{t=Time.now;puts"\e[H\e[2J%02d %s
-IMP1

4

Perl 6、113バイト

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

1秒のタイムアウトで1 回試してください

または、数時間実行した結果を出力する変更バージョン試してください

拡張:

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
}

「三角形が生成する」演算子は何をサポートしていますか?その中[\+]に追加し、[\-]その中に減算するようです。これは乗算などで機能しますか?
イッツィー

@TuukkaXほとんどすべての挿入演算子で動作するはずです。[+] LIST中間値を提供することを除いて、基本的にはreduce と同じです。農産物
ブラッドギルバートb2gills

4

QBasic、120 127 121バイト

これを非常に長く実行しないでください。そうしないと、ラップトップが発火します。CPU効率が99.several9s%向上しました。

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

非ゴルフと説明

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

画面をクリアすることから始めて、現在の時間と分をから取得しTIMERます。これは、午前0時からの秒数を返します。

これは私が試したのは初めてなPRINT USINGので、正の数が先行スペースで印刷されるという通常のQBasicの癖に悩まされないことを発見してうれしく思いました。##書式指定子により、必要に応じて1桁の数字が右揃えになり、スペースが埋め込まれるようになります。残念ながら、QBasicには文字列の繰り返し機能がないため、ハイフンにループを使用する必要があります。(私が間違えた場合、私に知らせてください!)

すべてのPRINTステートメント;は、改行を抑制するために終了します。しかし、ハイフンの後には改行が必要です。したがって、?内側のFORループの後の孤独です。

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.


How does this handle the last hour of the day? Top line reads 23, but what;'s the hour on the bottom line?
steenbergh

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

@steenbergh Whoops, fixed. It would be helpful for you to mention that edge case in the question.
DLosc

@DLosc Nah, I'm just joking :)). But yeah, smart!!
owlswipe

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

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!


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

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

@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

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

1
@KevinCruijssen Ha I didn't pick up on that! h<9. I will edit it to save 1 more byte. Thanks again!
CraigR8806

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));
 }
}

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)


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

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

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


2
You don't need the newline and space after the while 1:
Wheat Wizard

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

@steenbergh I tried it myself by setting the clock manually and it works for me.
ovs

@ovs aren't clock challenges fun :-). Anyway, probably something with repl.it then...
steenbergh

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

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.


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

Instead of printf("\n"); you can use puts("");
Seth

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.


Welcome to PPCG, good answer
george

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

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

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.


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.


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

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? :)


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)]])

1
Can 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

Oh, I didn't read it properly then. Thanks a lot man.
Gurupad Mamadapur

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

1
@ElPedro Yea I forgot to do it. I'll edit now.
Gurupad Mamadapur

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)))

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

2
You can fix the issue described by @kundor in 1 byte by adding a space after the corresponding {}.
Phlarx

@kundor fixed! Thanks. I kept the :02 format to right-pad one digit hours with zeroes.
dfernan

@kundor *left-pad one digit hours with zeroes.
dfernan

@dfernan: Well, :2 left-pads with spaces, which the challenge says is OK.
Nick Matteo

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)}");}

1
Can 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

@steenbergh see update
series0ne

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

@TheLethalCoder I specifically put C# Interactive because this works in the interactive console ONLY. This would not work as a standard C# program.
series0ne

Also note that this won't work when the hour is 23 and when the minute is 0
TheLethalCoder

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.


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

@steenbergh That´s a notice; it will not be displayed if you use default values (command line parameter -n or error_reporting(22519);
Titus

hours must be padded to length 2
Titus

Good point, the H setting for date goes from 00-23, but I forgot about it for the second hour.
user59178

Save two bytes with physical linebreaks.
Titus

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.


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

Hrm, that means my script is broken in several ways. Thanks.
Evan Krall

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

1
I 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

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

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

Whats wrong with 24?
pLumo

I need the -M because $((60-08)) gives an error.
pLumo

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


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

Forgot a semicolon ! You can try to run it again :)
Sygmei

1
Does this update every minute? The console seems to run this code just once...
steenbergh

Woops, did not saw that part, should be working now !
Sygmei

When it updates, it should either clear the screen or add 30 newlines. Man, I'm on your case...
steenbergh

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

spliced the 2 echos into 1, saved a few bytes ... (sleep 9 instead of sleep 10 saves 1 byte :P ) lol
Ditto

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]

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();
}

Changing ((i=hour())<10?" ":"")+i into ((i=hour())>9?i:" "+i) would save 2B twice... Good luck with further golfing!
Luke

@L.Serne thanks for the tip :)
Kritixi Lithos

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

@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 :)
Kritixi Lithos

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.


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...


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);
    }
}

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

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
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.