暂停时间是原来的两倍


15

您面临的挑战是打印输入,等待任何时间,打印输入,等待两次您最初等待的时间,再次打印输入,依此类推。初始延迟必须小于1小时,并且后续延迟的精度必须为+/- 5%。除此之外,对延迟时间没有限制。

例:

输入:hi

输出:hi(1ms暂停)hi(2ms暂停)hi(4ms暂停)hi(8ms暂停)hi(16ms暂停),等等

还允许:

hi(暂停1分钟)hi(暂停2分钟)hi(暂停4分钟)hi(暂停8分钟)hi(暂停16分钟),等等。

输入必须在程序开始时提供(STDIN,命令行参数,函数参数等),并且必须是字符串。

初始延迟不能为0。


输出需要是无限的,还是可以在一段时间后停止?
“ SparklePony同志”

1
@ComradeSparklePony,它必须一直输出(直到宇宙热死,计算机崩溃,stackoverflow,内存不足等)
程序员

@ComradeSparklePony仅在出现类似stackoverflow,内存不足等情况时才y=x=>(x&&alert(x),y())可以使用。从技术上讲,这是允许的,但我会拒绝投票。
程序员

@ programmer5000谢谢,知道了。
SparklePony同志'17

我可以打印换行符吗?
MD XF

Answers:


12

05AB1E,6个字节

码:

[=No.W

说明:

[        # Start an infinite loop
 =       # Print the top of the stack without popping
  No     # Compute 2 ** (iteration index)
    .W   # Wait that many milliseconds

在线尝试!


如果您先等待1秒钟,则可以使用w代替.W
莱利

@Riley我认为这行不通。w无论如何都等待一秒钟,然后.W弹出并等待那么多毫秒。
SparklePony同志'17

@ComradeSparklePony你是对的。一定是Gw
莱利

我不知道这是否一定反映了代码中的任何问题,但是当我运行链接的示例时,引擎给了我:“警告:请求已超过60秒的时间限制并被终止。”
doppelgreener

@doppelgreener是的,在这种情况下,在线翻译可能不是最佳选择。离线功能虽然很吸引人。
阿德南

15

临时,8块+ 3字节

set [n] to [1]; forever { say [x]; wait (n) secs; set [n] to ((n) * (2)) }

在Python中等效:

import time
n = 1
while 1:
    print("x")
    time.sleep(n)
    n = n * 2

1
为什么“ + 3个字节”?
科尔·约翰逊

2
9个块(例如,Forever,n)+ 3个字节(例如,x,2)
OldBunny2800

5

Python 3中,60 56个字节

import time
def f(x,i=1):print(x);time.sleep(i);f(x,i*2)

变更日志:

  • 将递归lambda更改为递归函数(-4字节)

您可以print通过切换到Python 2来在语句上节省一个字节:)
numbermaniac '17

1
@numbermaniac是的,但是然后我必须切换到Python2。:P
L3viathan

5

MATL,8字节

`GD@WY.T

第一次暂停是2秒。

MATL Online上尝试一下。或者查看修改后的版本,该版本显示自程序启动以来经过的时间。(如果解释器不起作用,请刷新页面,然后重试)。

或查看gif:

enter image description here

说明

`     % Do...while
  G   %   Push input
  D   %   Display
  @   %   Push iteration index (1-based)
  W   %   2 raised to that
  Y.  %   Pause for that time
  T   %   Push true. This will be used as loop confition
      % End (implicit). The top of the stack is true, which produces an infinite loop 

@ programmer5000出于好奇:在线口译员为您工作了吗?
路易斯·门多

是的,为什么呢?
程序员

@ programmer5000谢谢。只是检查一下。有时会有超时问题
路易斯·门多

5

Mathematica 34 32 30 29字节

原始解决方案34字节:

For[x=.1,1<2,Pause[x*=2];Print@#]&

用Do删除2个字节

x=1;Do[Pause[x*=2];Print@#,∞]&

使用@MartinEnder的递归解决方案再减少一个字节

±n_:=#0[Print@n;Pause@#;2#]&@1

@ngenisis使用ReplaceRepeated递归删除另一个字节

1//.n_:>(Print@#;Pause@n;2n)&

4
True1>0。但是这样的话要短一些:±n_:=#0[Print@n;Pause@#;2#]&@1
Martin Ender

我把1<2你的评论放在前面。但是,您的递归解决方案确实节省了一个字节。感谢@MartinEnder
Kelly Lowder

±以CP-1252编码(默认Windows编码)为1个字节。
JungHwan Min

3
甚至更短:1//.n_:>(Print@#;Pause@n;2n)&
ngenisis

5

八度,42 41字节

x=input('');p=1;while p*=2,pause(p),x,end

由于rahnema1,节省了一个字节,p*=2比还要短p=p*2

我不敢相信我还不能打高尔夫球,但实际上并不是那么容易。

  • 输入必须从头开始,因此第一部分不可避免。
  • 我需要一个加倍的数字,并且必须在循环前对其进行初始化
    • 可以将输入用作循环的条件,但那时我将不得不 p*=2其他地方。
    • 暂停没有返回值,否则可能是 while pause(p*=2)

2
我从rahnema1学到的一个窍门:input(0)作品
Luis

1
@LuisMendo不幸的是,该技巧在最新版本的八度中
不起作用

4

Java(OpenJDK 8),113字节

interface M{static void main(String[]a)throws Exception{for(int i=1;;Thread.sleep(i*=2))System.out.print(a[0]);}}

在线尝试!

-60个字节感谢Leaky Nun!


2
+1 for "Do not use Java for golfing. It is a bad idea." Could you add a TIO link?
programmer5000

@programmer5000 Sure, but it doesn't work, because TIO waits for the code to finish.
HyperNeutrino

2
Why an interface instead of a class?
rightfold

2
@rightfold An interface allows you to omit the public in public static void main.
Leaky Nun

1
@ColeJohnson the arguments are required.
Leaky Nun

4

R, 50 48 bytes

function(x,i=1)repeat{cat(x);Sys.sleep(i);i=i*2}

returns an anonymous function which has one mandatory argument, the string to print. Prints no newlines, just spits x out on the screen. i is an optional argument that defaults to 1, waits for i seconds and doubles i.

-2 bytes thanks to pajonk

Try it online!


Why not start at i=1 then use i=i*2 at the end and sleep just i?
pajonk

that's a great idea...I'll change that.
Giuseppe

4

Ruby, 34 28 23 22 (+2 for -n) = 24 bytes

3 bytes saved thanks to Value Ink!

1 byte saved thanks to daniero

loop{print;sleep$.*=2}

Starts at 2, then 4, etc.

Explanation

-n                       # read a line from STDIN
  loop{                } # while(true):
       print;            # print that line
             sleep$.*=2  # multiply $. by 2, then sleep that many seconds. 
                         # $. is a Ruby special variable that starts at 1.

It will sleep one second before reading the input, but you can enter it already
John Dvorak

Starting the Ruby program with the -n flag lets you skip the initial gets call, because the flag will handle it for you
Value Ink

print without an argument is equivalent to puts$_ -- one byte saved
daniero

4

Alice, 16 bytes

1/?!\v
T\io/>2*.

Try it online! (Not much to see there of course, but you can check how often it was printed within one minute.)

Explanation

1    Push 1 to the stack. The initial pause duration in milliseconds.
/    Reflect to SE. Switch to Ordinal.
i    Read all input.
!    Store it on the tape.
/    Reflect to E. Switch to Cardinal.
>    Move east (does nothing but it's the entry of the main loop).
2*   Double the pause duration.
.    Duplicate it.
     The IP wraps around to the first column.
T    Sleep for that many milliseconds.
\    Reflect to NE. Switch to Ordinal.
?    Retrieve the input from the tape.
o    Print it.
\    Reflect to E. Switch to Cardinal.
v    Move south.
>    Move east. Run another iteration of the main loop.

4

R, 44 43 bytes

Crossed out 44 is still regular 44 ;(

This answer already provides a decent solution, but we can save some more bytes.

function(x)repeat{cat(x);Sys.sleep(T<-T*2)}

Anonymous function taking practically anything printable as argument x. Starts at 2 seconds and doubles every time afterwards. Abuses the fact that T is by default defined as TRUE which evaluates to 1.

Also, as long as this comment still gets a green light from OP, we can make it even shorter, but I don't think it is in the spirit of the challenge. Wait times of 0 are not allowed anymore.

function(x)repeat cat(x)

2
look at you, abusing poor T like that. in the shorter version of the answer, you don't even need braces, just a space.
Giuseppe

1
Hey, if T doesn't like it, T can stand up for itself. Also, nice find :)
JAD

3

Cubix, 30 bytes

/(?:u<q.;1A>?ou2$/r;w;q^_q.\*/

Try it here

This maps onto a cube with side length 3.

      / ( ?              # The top face does the delay.  It takes the stack element with the
      : u <              # delay value, duplicates and decrements it to 0.  When 0 is hit the
      q . ;              # IP moves into the sequence which doubles the delay value.
1 A > ? o u 2 $ / r ; w  # Initiates the stack with one and the input.  For input hi this
; q ^ _ q . \ * / . . .  # gives us 1, -1, 10, 105, 104.  There is a little loop that prints 
. . . . . . . . . . . .  # each item in the stack dropping it to the bottom until -1 is hit.
      . . .              # Then the delay sequence is started om the top face
      . . .
      . . .

oh wow this looks like a neat language
Skidsdev


3

PHP, 31 bytes

for(;;sleep(2**$i++))echo$argn;
for(;;sleep(1<<$i++))echo$argn;

sleeps 1, 2, 4, 8, ... seconds. Run as pipe with php -nR '<code>'

Will work until the 63rd print (on a 64 bit machine), after that there will be no more waiting.
Version 1 will yield warnings sleep() expects parameter 1 to be integer, float given,
Version 2 will yield one warning sleep(): Number of seconds must be greater than or equal to 0.

Insert @ before sleep to mute the warnings.



2

Python 3, 61 bytes

import time;i=1;x=input()
while 1:print(x);time.sleep(i);i*=2

Similar to @L3viathan's golf, but uses while loop


2

CJam, 26 bytes

qKes{es1$-Y$<{W$o;2*es}|}h

Doesn't work properly on TIO.

The first pause is 20 milliseconds.

Explanation

q                           e# Push the input.
 K                          e# Push 20 (the pause time).
  es                        e# Push the time (number of milliseconds since the Unix epoch).
    {                       e# Do:
     es1$-                  e#  Subtract the stored time from the current time.
          Y$<{              e#  If it's not less than the pause time:
              W$o           e#   Print the input.
                 ;2*es      e#   Delete the stored time, multiply the pause time by 2, push
                            e#     the new time.
                      }|    e#  (end if)
                        }h  e# While the top of stack (not popped) is truthy.
                            e#  (It always is since the time is a positive integer)

2

C, 51 bytes

main(c,v)char**v;{puts(v[1]);sleep(c);main(2*c,v);}

C, 35 bytes as a function

c=1;f(n){puts(n);sleep(c*=2);f(n);}

Takes input as a command line argument.


2

Batch, 62 bytes

@set/at=%2+0,t+=t+!t
@echo %1
@timeout/t>nul %t%
@%0 %1 %t%

This turned out to be a byte shorter than explicitly doubling t in a loop:

@set t=1
:g
@echo %1
@timeout/t>nul %t%
@set/at*=2
@goto g

2

Reticular, 12 bytes

1idp~dw2*~2j

Try it online!

Explanation

1idp~dw2*~2j
1               push 1 (initial delay)
 i              take line of input
  d             duplicate it
   p            print it
    ~           swap
     d          duplicate it
      w         wait (in seconds)
       2*       double it
         ~      swap
          2j    skip next two characters
1i              (skipped)
  d             duplicate input
   p            print...
                etc.

2

C#, 80 79 bytes

s=>{for(int i=1;;System.Threading.Thread.Sleep(i*=2))System.Console.Write(s);};

Saved one byte thanks to @raznagul.


You can save 1 byte by moving the Write statement to the body of the loop.
raznagul

@raznagul Don't know how I missed that one, thanks!
TheLethalCoder

2

Python 2, 54 bytes

Uses a lengthy calculation instead of timing libraries.

def f(x,a=1):
 while 1:a*=2;exec'v=9**9**6;'*a;print x

I now notice that my answer is similar to yours. I had not read your answer when I posted, but if you would like to incorporate my solution into yours I'll happily remove my answer.
Tim

2

PowerShell, 35 33 30 29 Bytes

With a helpful hint from whatever and Joey

%{for($a=1){$_;sleep($a*=2)}}

Explanation

%{          # Foreach
for($a=1){  # empty for loop makes this infinite and sets $a
$_;         # prints current foreach item
sleep($a*=2)# Start-Sleep alias for $a seconds, reassign $a to itself times 2           
}}          # close while and foreach

Executed with:

"hi"|%{for($a=1){$_;sleep($a*=2)}}

1
you should be able to use an empty for instead of the while: %{$a=1;for(){$_;sleep($a*=2)}}``
whatever

Thanks! I had tried using a for loop before but I put for(;;). Didn't even try to remove the semi-colons.
SomeShinyMonica

1
Put the $a=1 as the initialization into the for to save another byte (for($a=1){...}). Also, I'm not sure whether to count the %, as the actual routine you're running is just a script block. (My challenges tend to be rather strict about requiring a program, sidestepping such ponderings, but for anything goes questions I'm still not quite sure how to count various ways of using PowerShell.)
Joey

@Joey, sweet that does work. Thanks for the tip
SomeShinyMonica

2

Python 3, 49 bytes

b=input();x=6**6
while 1:print(b);exec("x+=1;"*x)

Uses the slight delay of the += operation and executes it x times. x doubles by adding one to itself as many times as the value of x.

It starts at 6^6 (46656) to stick to the maximum of 5% variation in the delay.


Clever, but this is a memory hog.
eush77

@eush77 yes, on my tablet it terminated after just 7 iterations of the loop! I expect it would last a few longer on my desktop.
Tim

1

Perl 6, 39 bytes

print(once slurp),.&sleep for 1,2,4...* 

Try it (print overridden to add timing information)

Expanded:

  print(        # print to $*OUT
    once slurp  # slurp from $*IN, but only once
  ), 
  .&sleep       # then call sleep as if it was a method on $_

for             # do that for (sets $_ to each of the following)

  1, 2, 4 ... * # deductive sequence generator

1

JS (ES6), 44 42 40 38 36 bytes

Crossed out 44 is still 44

i=1,y=x=>setTimeout(y,i*=2,alert(x))

Don't like alert bombs?

i=1,y=x=>setTimeout(y,i*=2,console.log(x))

Technically correct, but loophole-abusing:

y=x=>(x&&alert(x),y())

-3 bytes thanks to Cyoce, -2 thanks to Business Cat, -2 thanks to Neil


2
I don't seem to be able to test this properly, but you could probably do i=1,y=x=>(alert(x),setTimeout(y,i*=2)) to save a couple bytes
Business Cat

1
I went ahead and edited in a credit message for Cyoce; if you want to change it, feel free to edit/rollback.
HyperNeutrino

1
How about i=1,y=x=>setTimeout(y,i*=2,console.log(x))?
Neil

1

Common Lisp, 49 bytes

(do((a(read))(i 1(* 2 i)))(())(print a)(sleep i))

first delay should be 1 second.


1
You have 321 rep!
programmer5000

@programmer5000 you have 3683 rep!
Cyoce

1

Pyth, 7 bytes

#|.d~yT

Explanation:

#           Infinitely loop
  .d         Delay for 
      T      10 seconds
    ~y       and double T each time
 |           print input every iteration, too

1

TI-BASIC, 36 bytes

Initial wait period is 1 second.

1→L
Input Str1
checkTmr(0→T
While 1
While L>checkTmr(T
End
Disp Str1
2L→L
End

1

Racket, 51 bytes

(λ(s)(do([n 1(* n 2)])(#f)(displayln s)(sleep n)))

Example

➜  ~  racket -e '((λ(s)(do([n 1(* n 2)])(#f)(displayln s)(sleep n)))"Hello")'
Hello
Hello
Hello
Hello
Hello
^Cuser break
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.