一時停止


15

課題は、入力を印刷し、任意の時間待機し、入力を印刷し、最初に待機した時間の2倍の時間待機し、再度入力を印刷することです。最初の遅延は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できる限り出力する必要があります(宇宙の熱死、コンピューターのクラッシュ、スタックオーバーフロー、メモリ不足など)
Programmer5000

@ComradeSparklePonyは、stackoverflow、メモリ不足などのような場合に限ります。これy=x=>(x&&alert(x),y())技術的には許可されますが、私はそれを投票します。
Programmer5000

@ programmer5000ありがとう、わかった。
同志SparklePony

改行を印刷できますか?
MD XF

回答:


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があっても1秒待機し、ポップしてそのミリ秒数待機します。
同志SparklePony

@ComradeSparklePonyそのとおりです。それはそうでなければならないでしょうGw
ライリー

コードの問題を必ずしも反映しているかどうかはわかりませんが、リンクされた例を実行すると、「警告:要求が60秒の制限時間を超えて終了しました」というメッセージが表示されます。
-doppelgreener

@doppelgreenerええ、この場合、オンライン通訳は最良の選択肢ではないかもしれません。しかし、オフラインは魅力のように機能します。
アドナン


5

Pythonの3、60の 56バイト

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

変更ログ:

  • 再帰ラムダを再帰関数に変更(-4バイト)

printPython 2に切り替えることでステートメントのバイトを節約できます:)
numbermaniac

1
@numbermaniacはい、しかしその後、Python 2に切り替える必要があります。:P
L3via17年

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

@ 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の再帰的ソリューションでもう1バイト削る

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

@ngenisisはReplaceRepeated再帰を使用して別のバイトを削ります

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

4
True is 1>0. But something like this is a bit shorter: ±n_:=#0[Print@n;Pause@#;2#]&@1
Martin Ender

I put the 1<2 prior to your comment. However, your recursive solution does save a byte. Thanks @MartinEnder
Kelly Lowder

± is one byte in CP-1252 encoding (default Windows encoding).
JungHwan Min

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

5

Octave, 42 41 bytes

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

Saved one byte thanks to rahnema1, p*=2 is shorter than p=p*2.

I can't believe I haven't been able to golf this down, but it was actually not that easy.

  • The input must be in the start, so the first part is impossible to avoid.
  • I need a number that gets doubled, and it must be initialized in front of the loop
    • It would be possible to use the input as a conditional for the loop, but then I would have to have p*=2 somewhere else.
    • Pause doesn't have a return value, otherwise it could have been while pause(p*=2)

2
A trick I learned from rahnema1: input(0) works
Luis Mendo

1
@LuisMendo Unfortunately the trick doesn't work in recent version of octave :(
rahnema1

4

Java (OpenJDK 8), 113 bytes

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

Try it online!

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