显示数字时钟


20

显示数字时钟

(我看到时钟挑战很多,我已经尝试阅读所有挑战,我敢肯定这是独一无二的)

写一些代码,不断更新的格式显示一个数字时钟h:m:s,其中hms可以占据每1个或2个字符。简单的限制如@BlueEyedBeast所说的,我基本上希望它代替显示的时间。

  • 不允许换行
  • 允许尾随空格
  • 不允许其他尾随字符
  • 不应错过任何秒数(不允许57-> 59)
  • 允许以“ 0”开头的数字,只要它们不超过2个字符
  • 该代码不得接受任何输入
  • 如果您的语言在没有输入的情况下无法获取当前时间,则可以使用标准允许的方式,最多输入8个字节
  • 输出必须是stdout
  • 这是codegolf,所以最短的答案就是成功!

我正在使用一种名为*> <>(海星)的语言,因为在> <>中(例如,等待文件I / O)无法使用此类程序。这是其中一个正在工作的数字时钟程序(已取消存储)。该程序用*> <>编写:

s":"m":"hnonon"   "ooo88888888888ooooooooooo1S

注意:除了s =秒,m =分钟,h =小时,S =睡眠(100ms * x)之外,其他所有内容均与> <>相同。

输出:

14:44:31

每100ms更新一次,直到终止。

不允许的例子

不允许以下内容:

1:

14:44:3114:44:32

2:

14:44:31 14:44:32

3:

14:44:31
14:44:32

时间必须保留在输出的第一行上,并且没有可见的尾随字符。但是,清除终端将被允许,因为它仍然没有任何尾随字符。


1
我们必须等待100毫秒还是可以永远不断更新?
蓝色

1
您不必等待,等待就是示例所要做的。
redstarcoder

2
挑战要求对我来说似乎太严格了。
mbomb007 '16

1
@ mbomb007我删除了“该程序必须能够在不是信号/中断的用户输入下退出”,因为当前的答案似乎并没有遵循它。
redstarcoder '16

1
程序可以依赖于操作系统的特定本地设置吗?
raznagul '16

Answers:


5

Pyke,6个字节

Ctr\ J

在这里尝试!

我认为这是有效的。用回车符代替空格字符以获取有效输出(不能在线使用)


抱歉,不是。时间后不允许换行或结尾字符。我将举两个例子更明确。
redstarcoder

我在规格中看不到吗?

1
第一行说不允许换行,第三行说没有尾随字符。很抱歉,如果不清楚,请多多指教。
redstarcoder

因此,您希望它取代显示的旧时间吗?
2016年

对,就是这样!您当前的代码似乎很完美。
redstarcoder

10

HTML + JS(ES6),8 + 60 = 68字节

在Chrome中测试。

setInterval`a.innerHTML=new Date().toLocaleTimeString('fr')`
<a id=a>

-1字节(@ETHProductions):使用法语时间格式,而不是 .toTimeString().slice(0,8)


HTML + JS(ES6),8 + 62 = 70字节

这将在FireFox中起作用。

setInterval('a.innerHTML=new Date().toLocaleTimeString`fr`',0)
<a id=a>

-3个字节(@ETHProductions):使用法语时间格式,而不是 .toTimeString().slice(0,8)


2
这是如何运作的?我以前从未看过反引号语法。经过一些快速搜索后,我也找不到任何东西。
Carcigenicate's

1
在Inox(铬)中为我工作
redstarcoder

1
@Carcigenicate它是最新的JavaScript规范ECMAScript6的一部分。developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/...
darrylyeo

@darrylyeo谢谢。我可以在文字语法上找到所需的内容,但是在这里看不到它是如何应用的。我需要再次阅读规范。我仍然不明白如何使用反引号之前的功能。
Carcigenicate's

2
您可以在Firefox中保存3个字节new Date().toLocaleTimeString`fr` (其中1个字节在Chrome中保存1个字节...TimeString('fr')
ETHproductions

6

Python 2,50个字节

ctime不带参数的Python 2.1+ )

import time
while 1:print'\r'+time.ctime()[11:19],

time.ctime()产生一个格式化的字符串,可以从中使用hh:mm:ss对其进行切片[11:19](无论日期和时间,它都位于相同的位置)。

print'\r'在文本之前设置回车符,并使文本成为元组的第一项,可以,有效地抑制隐式尾随'\n'并覆盖先前写入的输出。

while 1 永远循环。


3
我认为这需要,在末尾禁止换行符,否则在Python 2.7.12中我会换行符。
redstarcoder '16

糟糕,是的,您是正确的...更新
Jonathan Allan

5

Mathematica,48 41 37 28字节

Do[s=Now[[2]],∞]~Monitor~s

输出将是TimeObject,连续刷新。

看起来像这样: enter image description here

替代版本

48个字节:

Dynamic@Refresh[TimeObject[],UpdateInterval->.1]

53个字节:

Dynamic@Refresh[DateString@"Time",UpdateInterval->.1]

1
每秒更新一次,您是否确保它不会跳过几秒钟?(例如:11:11:11-> 11:11:13)
redstarcoder

Dynamic@{DateString@TimeObject[], Clock[]}[[1]]
DavidC,2013年

1
@redstarcoder它每〜1.002s更新一次,所以我改为每100ms更新一次
JungHwan Min 2016年

Welp,我只是意识到我实际上并不需要Pause
JungHwan Min

Dynamic@{Now,Clock[]}[[1]]是26个字节,并显示一个datetime对象。Dynamic@{DateString@"Time",Clock[]}[[1]]是40个字节,仅输出hh:mm:ss
Kelly Lowder'Dec 12'12

5

我看到不再需要非信号UI输入来停止程序了。所以现在我们可以做:

Bash + coreutils,28岁

yes now|date -f- +$'\e[2J'%T

yes 每行一次将字符串“ now”连续输出到管道中。

date -f-reads将每个“现在”解释为当前时间,然后以所需格式输出。格式字符串包括ANSI转义序列以清除屏幕。 date 确实在日期之后输出换行符-我不确定这是否不合格,因为无论如何每次都会清除屏幕。

如果它不符合条件,那么我们可以tr改用:

Bash + coreutils,31岁

yes now|date -f- +%T|tr \\n \\r

以前的答案:

重击+ X,32

xclock -d -update 1 -strftime %T

不幸的是,这只能每秒更新一次。如果那不符合资格,那么我们可以改为:

Bash + coreutils,43岁

until read -t0
do printf `date +%T`\\r
done

只要不跳过秒数,每秒更新一次就可以了(IE:12-> 14)。
redstarcoder '16

我允许你换行!我从没料到这件事会发生,呵呵。
redstarcoder '16

可以吗?date +$'\e[2J'%T;$0
Evan Chen

@EvanChen否,因为每次迭代都会递归产生一个新进程,并且最终将耗尽可用的内存或PID空间,类似于堆栈溢出。但是,您可以做date +$'\e[2J'%T;exec $024个字节...
Digital Trauma

4

QBIC,6个字节

{_C?_d

{      Starts a DO-loop
 _C    CLS
   ?   PRINT
    _d TIME$

不断清除屏幕并以格式打印系统时间22:03:41


3

Clojure, 150 136 141 bytes

V3: 141 bytes :(

+5 bytes to fix a bug. Since the times aren't zero padded, the clock can "shrink" and expand when the time changes. It was "smearing" when it shrunk because the last digit was no longer being cleared. Fixed it by adding some spaces at the end to ensure everything is being overwritten.

#(while true(flush)(print(str(apply str(repeat 9"\b"))(.format(java.text.SimpleDateFormat."H:m:s")(java.util.Date.))"   "))(Thread/sleep 99))

V2: 136 bytes

#(while true(flush)(print(str(apply str(repeat 9"\b"))(.format(java.text.SimpleDateFormat."H:m:s")(java.util.Date.))))(Thread/sleep 99))

-14 bytes by switching to using SimpleDateFormat to format the date. Still huge.

V1: 150 bytes

#(while true(let[d(java.util.Date.)](flush)(print(str(apply str(repeat 9 "\b"))(.getHours d)":"(.getMinutes d)":"(.getSeconds d)))(Thread/sleep 100)))

I realized I'm probably using the worst way possible to get the date. Definitely room for improvement here.

Ungolfed:

(defn -main []
  (while true
    (let [d (java.util.Date.)]
      (flush)
      (print
        (str
          (apply str (repeat 9 "\b"))
          (.getHours d)":"(.getMinutes d)":"(.getSeconds d)))
      (Thread/sleep 100))))

3

Bash + watch, 19 bytes

watch is not a part of coreutils, but is available out of the box on virtually every Linux distro.

Golfed

watch -tn1 date +%T

Try it online !


2

WinDbg, 73 bytes

.do{r$t0=0;.foreach(p {.echotime}){r$t0=@$t0+1;j8==@$t0'.printf"p \r"'}}1

It continually updates a line with the current time until the user presses Ctrl+Break.

How it works:

.do                          * Start do-while loop
{
    r$t0 = 0;                * Set $t0 = 0
    .foreach(p {.echotime})  * Foreach space-delimited word in a sentence like "Debugger (not 
    {                        * debuggee) time: Mon Dec  5 14:08:10.138 2016 (UTC - 8:00)"
        r$t0 = @$t0+1;       * Increment $t0
        j 8==@$t0            * If $t0 is 8 (ie- p is the current time)
        '
            .printf"p \r"    * Print p (current time) and \r so the next print overwrites
        '
    }
} 1                          * Do-while condition: 1, loop forever

Sample output (well, you get the idea):

0:000> .do{r$t0=0;.foreach(p {.echotime}){r$t0=@$t0+1;j8==@$t0'.printf"p \r"'}}1
14:10:12.329

2

PHP, 28 bytes

for(;;)echo date("\rH:i:s");

The date function prints everything literally that it doesn´t recognize.

\r is the carriage return, sets the cursor to the first column.

Run with -r.


2

MATL, 11 bytes

`XxZ'13XODT

Infinite loop that clears the screen and prints the time in the specified format.

You can try it at MATL Online!. This compiler is experimental; if it doesn't work refresh the page and press "Run" again.


2

C#, 82 bytes

()=>{for(;;)Console.Write(new string('\b',8)+DateTime.Now.ToString("HH:mm:ss"));};

Anonymous method which constantly overwrites 8 characters with new output. Can be made 1 byte shorter if modifying to accept a dummy parameter (z=>...).

Full program:

using System;

public class Program
{
    public static void Main()
    {
        Action a =
        () =>
        {
            for (;;)
                Console.Write(new string('\b', 8) + DateTime.Now.ToString("HH:mm:ss"));
        };

        a();
    }
}

1
Is it allowed not to import System? Some people do it, and some people don't :/
Yytsi

He didn't in his actual solution, just in the demo program, so yes, it is ok
Stefan

2

C#, 65 bytes

()=>{for(;;)Console.Write("\r"+DateTime.Now.ToLongTimeString());};

Works by overwriting the same line within an endless loop


2

SmileBASIC 3.3.2, 38 bytes

@L?TIME$;" ";
GOTO@L

UTF-16 sucks :(

Anyway, this repeatedly prints the local time in HH:MM:SS with a space after it, no newline afterward. It doesn't update every second though, it just repeatedly prints forever.


Sorry this isn't valid, it needs to replace the output, this doesn't. Setting the first line to @L?TIME$ and appending a line after (for a total of 3 lines) that reads LOCATE 0, 0 does the trick (does SmileBASIC support carriage return?).
redstarcoder

Also you forgot to score the newline, making this 40 bytes (UTF-16 is brutal for code golf). You can get the character length very easilly via Python REPL len(""" YOUR CODE HERE """), then just do *2 for UTF-16.
redstarcoder

No SB doesn't do CR actually, I would have to drop a LOCATE statement into there which would absolutely destroy my score :P Or a CLS:VSYNC which is just as bad.
snail_

Yeah, sadly this solution is invalid without it. Good news though! SmileBASIC is scored as UTF-8.
redstarcoder

2

C, 134 116 89 80 76 75 73 bytes

main(n){for(;time(&n);)printf("\r%02d:%02d:%02d",n/3600%24,n/60%60,n%60);}

---- Old versions:
main(n){for(;;)n=time(0),printf("\r%02d:%02d:%02d",n/3600%24,n/60%60,n%60);}

n;main(){for(;;)n=time(0),printf("\r%02d:%02d:%02d",n/3600%24,n/60%60,n%60);}

---- 

n;main(){for(;;)n=time(0),printf("\r%02d:%02d:%02d",n/3600%24,n/60%60,n%60);}

----

Saved 9 more bytes thanks to @nmjcman101 again:
n;main(){for(;;)n=time(0),printf("\r%02d:%02d:%02d",(n/3600)%24,(n/60)%60,n%60);}

----

Saved 27 bytes thanks to @nmjcman101
n,b[9];main(){for(;;){n=time(0);strftime(b,9,"%H:%M:%S",localtime(&n));printf("\r%s",b);}}

----

I figured out I don't need to put `#include<stdio.h>` into the file :)
#include<time.h>
main(){for(;;){time_t n=time(0);char b[9];strftime(b,9,"%H:%M:%S",localtime(&n));printf("\r%s",b);}}

----

#include<time.h>
#include<stdio.h>
main(){for(;;){time_t n=time(0);char b[9];strftime(b,9,"%H:%M:%S",localtime(&n));printf("\r%s",b);}}

It looks like (for me) you can remove time.h as well. This removes the time_t type, so you need to make n an int instead. This can be done by declaring it outside of main (like n;main...), which removes the need for the int. You can also get rid of the char with the same trick: b[9];main.... They're both int type now, but it's flexible enough.
nmjcman101

Wow, thanks a lot, I didn't know this would work. Thank you
Stefan

Please stop me if you'd like to golf it yourself, but I also took out the strftime... and the b[9] and just made print into this: printf("\r%d:%d:%d",(n/3600)%60-29,(n/60)%60,n%60); I'm not sure if the parens are needed or not. Also you can take out a set of {} by putting commas between your statements so it's for(;;)a,b,c;
nmjcman101

1
These parentheses are annoying. (n/60)%60, seriously?
anatolyg

1
You can save 1 byte by declaring n as parameter of main, say main(n) instead of n;main()
Karl Napf


2

Pascal, 61 bytes

uses sysutils;begin while 1=1do write(#13,timetostr(now))end.

Free pascal has nice time routines in SysUtils unit. Ungolfed:

uses
  sysutils;
begin
  while 1=1 do
    write(#13, timetostr(now));
end.

2

C 65 (prev 64) bytes

Guaranteed to work on Linux machine. :)

@Marco Thanks!

f(){while(1){system("date +%T");usleep(100000);system("clear");}}

1

Vim, 26 bytes

qqS<C-r>=strftime("%T")<CR><esc>@qq@q

This creates a recursive macro (e.g. an eternal loop) that deletes all the text on the current line and replaces it with the current time.


1

Pyth - 28 bytes

Kinda longish, because pyth has no strftime.

#p+"\r"j\:m.[`02`dP>4.d2.d.1

1

Groovy, 45 characters

for(;;)print(new Date().format("\rHH:mm:ss"))

1

Jelly, 8 bytes

13Ọ7ŒTȮß

13Ọ        chr(13), carriage return
   7ŒT     time string, which extends the previous character
      Ȯ    print
       ß   call the whole link again

Try it online!

The carriage return doesn't work online, and I can't get the interpreter to work, so its kinda untested, but it works as expected when I use printable characters in place of the CR.


1

ForceLang, 123 bytes

def s set
s d datetime
s z string.char 8
s z z.repeat 16
label 1
io.write z
io.write d.toTimeString d.now()
d.wait 9
goto 1

datetime.toTimeString is backed in the reference implementation by Java's DateFormat.getTimeInstance(), which is locale-dependent, so you can set your default system locale to one that uses 24-hour time.


1

PowerShell, 30 28 24 20 bytes

Changed my computer's region to Germany based on raznagul's comment to save 4 bytes. :)

for(){date -F T;cls}

Previous version that works in all locales.

for(){date -F h:m:s;cls}


0

Batch, 36 bytes

@set/p.=␈␈␈␈␈␈␈␈%time:~0,8%<nul
@%0

Where represents the ASCII BS character (code 8).


0

Racket, 71 bytes

(require srfi/19)(let l()(display(date->string(current-date)"↵~3"))(l))

Where the is actually a CR (hex 0d). Hex dump of the program for further clarification (notice byte at position hex 4d):

00000000  28 72 65 71 75 69 72 65  20 73 72 66 69 2f 31 39  |(require srfi/19|
00000010  29 28 6c 65 74 20 6c 28  29 28 64 69 73 70 6c 61  |)(let l()(displa|
00000020  79 28 64 61 74 65 2d 3e  73 74 72 69 6e 67 28 63  |y(date->string(c|
00000030  75 72 72 65 6e 74 2d 64  61 74 65 29 22 0d 7e 33  |urrent-date)".~3|
00000040  22 29 29 28 6c 29 29                              |"))(l))|
00000047

Uses SRFI/19 included with the Racket distribution. (current-date) gets the current local date & time. The date->string format ~3 is ISO-8601 hour-minute-second format. (let l () ... (l)) in an idiomatic infinite loop. (require srfi/19) loads the srfi/19 module.


0

C, 156 bytes

#include<stdio.h>
#include<time.h>
int main(){time_t a;struct tm *b;char c[9];for(;;){time(&a);b=localtime(&a);strftime(c,9,"%H:%M:%S",b);printf("%s\r",c);}}

0

TI-Basic, 40 Bytes

(In TI-BASIC, many characters are 2 byte tokens, and colons at the beginning of a line are 0 extra bytes)

:ClrHome
:Output(1,6,":
:setTmFmt(24
:While 1
:Output(1,1,getTmSrr(0
:getTime
:Output(1,7,Ans(3
:End

0

R, 41 bytes

repeat{cat(format(Sys.time(),"%T"),"\r")}

Has one trailing space (because of cat default separator being a space).
Because of the refresh rate of the R GUI, running this in the GUI will occasionally skip some seconds, but if you save it to a file and run it on the command line it will display correctly every single seconds.
Will run forever until user interrupt.

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.