Приготовь мне хот-дог! [закрыто]


13

Иногда мне хочется хот-дога (не мы все), и поэтому я его делаю. Теперь сделать хот-дог очень просто.

1) Положите хот-доги в кипящую воду

2) Подождите некоторое время (подробности ниже)

3) Ешьте хот-дог по истечении времени.

Вы могли заметить, что я сказал

определенное время (подробно ниже)

и так подробно опишу.

Многие разные бренды имеют много разных рекомендаций относительно того, как долго мы должны готовить хот-доги, но я нашел, что лучше всего готовить их ровно 4 минуты и 27 секунд (не спрашивайте). Я пробовал много разных таймеров, но обнаружил, что программа, которая непрерывно выводит, является лучшим способом привлечь мое внимание.

ТВОЕ ЗАДАНИЕ

Вы должны составить программу, которая будет выводить сообщение Not ready yetровно за 4 минуты и 27 секунд. По истечении этого времени вы должны выводить данные Eat your hot dogдо конца времени. Пожалуйста, не принимайте никакой информации.

КАК ПОБЕДИТЬ

Вы должны написать кратчайший код в байтах, чтобы выиграть, потому что это



1
Довольно близко к Легену ... подожди ... тоже.
manatwork

Единственное отличие состоит в том, что этот вызов требует, чтобы программа ждала определенное время
user41805

8
Должны ли мы выводить «Пока не готово» непрерывно снова и снова, пока не закончится интервал ( Not ready yet\nNot ready yet\n...), или мы можем просто вывести его один раз и изменить выход после того, как 4м 27 с закончится?
user41805

1
Ой, мой ответ напоминает мне о том, чтобы я ел хот-дог последние два дня ...
Нил

Ответы:


20

Скретч, 93 78 байт

представление изображения

Код:

when gf clicked
say[Not ready yet
wait until<(timer)>[267
say[Eat your hot dog

Сгенерировано https://scratchblocks.github.io/ , который, кажется, является стандартом для Scratch скоринга.

Довольно понятно, Когда программа запускается, говорите «Еще не готов», пока таймер (который считается в секундах) больше 267. Затем запускается бесконечный цикл, где он говорит Eat your hot dog.

Это является непрерывным выводом, потому что sayблок не работает вечно , если вас say []или sayчто - то другое.


7
Нет необходимости вечно экономить 8 байтов. Это занимает до 85 байт. Он также короче в Hñähñu (Mezquital Otomi) , вместо английского, еще на 8 байтов (без вечности) , доведя его до 77 байтов.
Тим


@ Спасибо, но зеленый флаг не работает.
Okx

На самом деле это происходит из официального перевода на сайте, так что это ошибка, которую он отображает неправильно.
Тим

@Tim Блок зеленого флага, вероятно, еще не реализован (хотя перевод все еще переводит его). Кроме того, нет официального языка Hñähñu в официальном Scratch.
Эрик Outgolfer

14

Баш + кореутилс, 50

timeout 267 yes Not ready yet
yes Eat your hot dog

объяснение

Я думаю, что это довольно очевидно, но на всякий случай:

  • yesCoreutil непрерывно многократно выводит любые переданные ей параметры в командной строке
  • timeoutCoreutil принимает числовой параметр тайм - аута , затем по команде. Команда запускается, а затем уничтожается по истечении указанного времени ожидания.

8

Язык сценариев работы Flashpoint , 67 байт

#l
s="Not ready yet"
?_time>267:s="Eat your hot dog"
hint s
goto"l"

Сохранить как "hotdog.sqs"(или что-то еще) в папке миссии и позвонить с [] exec "hotdog.sqs".

Объяснение:

#l                                  // Label for the "goto"
s="Not ready yet"
?_time>267:s="Eat your hot dog"     // "?:" means "if () then" in a script.
                                    // "_time" is a local variable that is automatically
                                    // created and updated in every script. Its value
                                    // is the time in seconds since the script started.

hint s                              // Outputs the text in a text box.

~.1                                 // Sleeps for a tenth of a second.
                                    // The script seems to work without sleeping too,
                                    // so I didn't include this in the golfed version.
                                    // Looping in a script without sleeping is always
                                    // a bad idea, though. It sometimes crashes the game.

goto"l"                             // Go back to the beginning of the loop.
                                    // This is the only way to create a loop if you don't 
                                    // want to halt the game (and the time calculation)
                                    // until the loop finishes.

Я пробовал много разных таймеров, но обнаружил, что программа, которая непрерывно выводит, является лучшим способом привлечь мое внимание.

Это решение должно быть особенно полезным для привлечения вашего внимания, поскольку hintкоманда воспроизводит цепляющий звуковой эффект при каждом вызове, что звучит очень раздражающе, когда одновременные звуки обрезаются в тесной петле.


7

JavaScript ES6, 76 байт

$=>setInterval("console.log(--_>0?`Not ready yet`:`Eat your hot dog`)",_=517)

объяснение

Это выводит что-то на консоль каждые 517 миллисекунд. Сначала он печатает 'Not ready yet'и уменьшает счетчик. После 517 итераций ( = 517 * 517 = 267289 ms) начинается печать 'Eat your hot dog'.

Тестовое задание

f=
  $=>setInterval("console.log(--_>0?`Not ready yet`:`Eat your hot dog`)",_=517);
(setInterval("console.log('DONE NOW')",267000)&&f())();


ты не можешь просто сделать settimeout и сохранить байт?
user1910744

setTimeoutвыполняет функцию только один раз. Задача состоит в том, чтобы непрерывно выводить строку, поэтому setTimeoutона будет недействительной.
Люк

(--_? works instead of (--_>0? (-2)
dandavis

Unfortunately, it doesn't _ will be decremented every time something is printed, so it will also go below zero. All negative integers are truthy, so those would print 'Not ready yet' as well (which is not what we want).
Luke

7

Powershell, 85 71 59 bytes

1..276|%{Sleep 1;'Not ready yet'};for(){'Eat your hot dog'}

There's probably a much better way, so criticism welcome! This is my first golf attempt :)

EDIT Down a whole 14 bytes thanks to AdmBorkBork! And definitely a technique to remember!

EDIT 2 Another 12 bytes gone thanks to Matt. Not calling write twice also removed 2 spaces, very helpful!


1
Welcome to PPCG! Nice to see another PowerSheller around. An easy golf is to run a loop a fixed number of times 1..276|%{} instead of a for loop with an increment. Check out some other tips on that page, too!
AdmBorkBork

Strings are sent to std out be default. No need to specify with the write-output cmdlet.
Matt

7

GameMaker' scripting language variant used in Nuclear Throne Together mod, 68 bytes

t=0while 1{trace(t++<8010?"Not ready yet":"Eat your hot dog")wait 1}

Explanation

  • GML's parser is deliciously forgiving. Semicolons and parentheses are optional, and the compiler is not at all concerned about your spacing outside the basic rules (0while parses as 0,while and thus is ok)
  • Variables leak into the executing context unless declared via var (same as with JS).
  • GML variant used in NTT introduces a wait operator, which pushes the executing "micro-thread" to a list for the specified number of frames, resuming afterwards. Coroutines, basically.

    The game is clocked at 30fps, so 4m27s == 267s == 8010 frames.

  • trace() outputs the given string into the chat.

If you have the videogame+mod installed, you can save that as some test.mod.gml, and do /loadmod test to execute it, flooding the chat with "status reports":

Скриншот


3
I am not exactly sure what is going on here, but I approve.

3

Python 2, 92 bytes

from time import*
t=time()
while 1:print"Not ready yet"if time()-t<267else"Eat your hot dog"

Try it online!


9
while 1:print'ENaott yroeuard yh oyte td o g'[time()-t<267::2] for 90 bytes
ovs

@ovs while 1:print['Eat your hot dog','Not ready yet'][time()-t<267] would also be 90 (while being clearer and not printing the extra white space).
Jonathan Allan

3

TI-Basic, 75 bytes

For(A,1,267
Disp "Not ready yet
Wait 1
End
While 1
Disp "Eat your hot dog
End

Explanation

For(A,1,267             # 9 bytes, for 267 times...
Disp "Not ready yet     # 26 bytes, display message
Wait 1                  # 3 bytes, and wait one second
End                     # 2 bytes, ...end
While 1                 # 3 bytes, after that, continuously...
Disp "Eat your hot dog  # 31 bytes, output second message
End                     # 1 byte, ...end

2

Batch, 99 bytes

@for /l %%t in (1,1,267)do @echo Not ready yet&timeout/t>nul 1
:l
@echo Eat your hot dog
@goto l

Batch has no date arithmetic so as a simple 267 second timeout isn't permitted the best I can do is 267 one-second timeouts.


2

C# 144 bytes

()=>{for(int i=0;;){var s="\nEat your hot dog";if(i<267e3){i++;s="\nNot ready yet";}System.Console.Write(s);System.Threading.Thread.Sleep(1);}};

Ungolfed full program:

class P
{
    static void Main()
    {
        System.Action a = () => 
            {
                for (int i = 0; ;)
                {
                    var s = "\nEat your hot dog";
                    if (i < 267e3)
                    {
                        i++;
                        s = "\nNot ready yet";
                    }
                    System.Console.Write(s);
                    System.Threading.Thread.Sleep(1);
                }
            };

        a();
    }
}

Unfortunately I could not use the ?:-operator as I have not found a way to stop incrementing i without the if.


Try something like if(i++<267e3) to save a few bytes.
adrianmp

1
@adrianmp: That wouldn't work, as that would still increment i every millisecond. And once int.MaxValue is reached the program would either crash or start printing Not ready yet again.
raznagul

I've managed to pull this off by greatly delaying the overflow (or even mitigating it at the cost of a few bytes). I've "borrowed" some ideas from your answer. Thanks!
adrianmp

2

C#, 174 172 147 bytes

Saved 25 bytes by "borrowing" some ideas from raznagul's C# answer and merging them with the sum of first n numbers trick!

Saved 2 bytes by using the sum of first n numbers trick for a loss of precision of 185 milliseconds.

class P{static void Main(){for(int i=1;;){System.Console.WriteLine(i++<731?"Not ready yet":"Eat your hot dog");System.Threading.Thread.Sleep(i);}}}

Ungolfed program:

class P
{
    static void Main()
    {
        for (int i=1;;)
        {
            System.Console.WriteLine( i++ < 731 ? "Not ready yet" : "Eat your hot dog");
            System.Threading.Thread.Sleep(i);
        }
    }
}

Explanation:

Since the total time to wait is hardcoded at 267 seconds, one can consider this number as a telescopic sum of the first n natural numbers, n * (n + 1) / 2, which must equal 267000 milliseconds.

This is equivalent to n^2 + n - 534000 = 0.

By solving this second order equation, n1 = 730.2532073142067, n2 = -n1. Of course, only the positive solution is accepted and can be approximated as 730.

The total time can be calculated as 730 * (730 + 1) / 2 = 266815 milliseconds. The imprecision is 185 milliseconds, imperceptible to humans. The code will now make the main (and only) thread sleeps for 1 millisecond, 2 milliseconds and so on up to 730, so the total sleep period is ~267 seconds.

Update:

The program's logic can be simplified further - basically it needs to continuously display a message and wait a specified time until switching to the second message.

The message can be change by using a ternary operator to check the passing of the specified time (~267 seconds).

The timing aspect is controlled by using an increasing counter and pausing the execution thread.

However, since the counter variable continues increasing indefinitely without any conditions to check its value, one can expect an integer overflow at some point, when the message reverts to Not ready yet.

A condition can be added to detect and mitigate the issue by assigning a positive value greater than 730 when the overflow occurs - like i=i<1?731:i inside the for loop. Sadly, it comes at the cost of 11 additional bytes:

class P{static void Main(){for(int i=1;;i=i<1?731:i){System.Console.Write(i++<731?"\nNot ready yet":"\nEat your hot dog");System.Threading.Thread.Sleep(i);}}}

Ключевым моментом здесь является использование значения счетчика в миллисекундах, чтобы значительно задержать момент переполнения.

Время до переполнения можно рассчитать по sum(1..n)формуле, где n = максимальное 32-разрядное целое число со знаком в C # (и .NET Framework) или 2 ^ 31 - 1 = 2147483647:

2 147 483 647 * 2 147 483 648 / 2 = 2,305843008 x 10^18 milliseconds = 2,305843008 x 10^15 seconds = 26 687 997 779 days = ~73 067 755 years

Через 73 миллиона лет может не иметь значения, если в системе появится сбой - хот-дог, голодный ОП и, возможно, сама человеческая раса давно исчезли.


Предыдущая версия (172 байта):

namespace System{class P{static void Main(){for(int i=1;i<731;){Console.Write("\nNot ready yet");Threading.Thread.Sleep(i++);}for(;;)Console.Write("\nEat your hot dog");}}}

Нежелтая программа:

namespace System
{
    class P
    {
        static void Main()
        {
            for (int i = 1; i < 731; )
            {
                Console.Write("\nNot ready yet");
                Threading.Thread.Sleep(i++);
            }
            for ( ; ; )
                Console.Write("\nEat your hot dog");
        }
    }
}

Предыдущая версия (174 байта):

namespace System{class P{static void Main(){for(int i=0;i++<267e3;){Console.Write("\nNot ready yet");Threading.Thread.Sleep(1);}for(;;)Console.Write("\nEat your hot dog");}}}

Нежелтая программа:

namespace System
{
    class P
    {
        static void Main()
        {
            for (int i=0; i++ < 267e3; )
            {
                Console.Write("\nNot ready yet");
                Threading.Thread.Sleep(1);
            }
            for ( ; ; )
                Console.Write("\nEat your hot dog");
        }
    }
}

Кроме того, программа может отображать Not ready yetтолько один раз, подождать, пока не истечет указанное время, и затем вывести Eat your hot dogее, переписав предыдущее сообщение, в то время как оно на несколько байт короче:

C #, 145 байт

namespace System{class P{static void Main(){Console.Write("Not ready yet");Threading.Thread.Sleep(267000);Console.Write("\rEat your hot dog");}}}

Нежелтая программа:

namespace System
{
    class P
    {
        static void Main()
        {
            Console.Write("Not ready yet");
            Threading.Thread.Sleep(267000);
            Console.Write("\rEat your hot dog");
        }
    }
}

That's great. I'd give you +1, if I hadn't already. ;)
raznagul

2

Ruby, 80 71 67 Bytes

Edit: Thanks to manatwork for shaving off 13 whole bytes

267.times{puts"Not ready yet"
sleep 1}
loop{puts"Eat your hot dog"}

Why not 267.times{…}?
manatwork

Wow, thanks. I feel dumb now.
BRFNGRNBWS

Looks like you are counting with CR/LF line separators. As Ruby allows LF only, we used to count that only. And there is no need for the line break after the {. That would result 67 bytes.
manatwork

I'm a beginner at Ruby, and a total noob at code golfing, so thanks for all the help!
BRFNGRNBWS

In case you missed it, there is a collection of Tips for golfing in Ruby to help beginners.
manatwork

2

05AB1E, 43 29 28 bytes (Thanks to Adnan)

267F…€–Žä‡«ªw,}[“Eat€ž…ß‹·“,

Does not work online, since it times out. Offline it will work.

267F: Loop 267 times

…€–Žä‡«ª: First string with dictionary

w,: Wait one second and print

}[: End if loop and start infinite loop

“Eat€ž…ß‹·“: Second string with dictionary

,: Print


Thanks, my client saw that this code was short and works offline - now he wants me to write his website using this language. . .
Pascal Raszyk

It works online, but just not on the interpreter that is given online. You can see for yourself here
P. Knops

I know. It was a joke :D.
Pascal Raszyk

1
It's best to just answer the normal way :D
P. Knops

“NotŽä‡«“ can be replaced by …€–Žä‡«ª
Adnan

1

Python, 115 bytes

My first time trying something like this. I am also a beginner so here it goes in Python 3 for 115 bytes:

import time
for i in range(267):
    time.sleep(1)
    print("Not ready yet")
while 1:
    print("Eat your hotdog")

3
Welcome to the site! The aim of code golf is to write the shortest code possible in your language. There are a few things that can be improved and it couldn't hurt to look at the current Python winner for some tips!

Remove the time.sleep(1) - saves a few bytes
Pascal Raszyk

@praszyk, then the for will finish looping over range(267) much faster than 4 minutes 27 seconds and the solution becomes invalid. ☹
manatwork

1

JavaScript Blocks Editor for micro:bit, 90 Bytes

enter image description here

The code:

basic.showString("Not ready yet")
basic.pause(254000)
basic.showString("Eat your hot dog")

You can try it here.

Got inspired by the Scratch answer to solve the task with my micro:bit. The only Problem is that the pause-block starts after outputting the first string so i needed to reduce the pause by 13s.

Note: The old Microsoft Block Editor for micro:bit is shorter to create but produces more code so is in fact longer.


1

On the basis that the OP wants hotdogs continuously, until the end of time - which I understand from the phrase:

After this time has elasped, you should output Eat your hot dog until the end of time.

This is my answer:

C++, 187 188 224 167 bytes

Whitespace removed (167 bytes):

#include<stdio.h>
#include<windows.h>
int main(){for(;;){for(int x=0;x<267;x++){Sleep(1000);printf("Not ready yet");}Sleep(1000);printf("Eat your hot dog");}return 0;}

readable form (224 bytes):

#include <stdio.h>
#include <windows.h>

int main() {
  for( ; ; ){ 
    for(int x=0; x < 267; x++){
      Sleep(1000);
      printf("Not ready yet"); 
    }
    Sleep(1000);
    printf("Eat your hot dog");
  }
  return 0;
}

If, on the other hand, OP enjoys his hot dogs in moderation, then this is my answer:

Whitespace removed (158 bytes):

#include<stdio.h>
#include<windows.h>
int main(){for(int x=0;x<267;x++){Sleep(1000);printf("Not ready yet");}Sleep(1000);printf("Eat your hot dog");return 0;}

readable form (198 bytes):

#include <stdio.h>
#include <windows.h>

int main() {
  for(int x=0; x < 267; x++){
    Sleep(1000);
    printf("Not ready yet"); 
  }
  Sleep(1000);
  printf("Eat your hot dog");
  return 0;
}

What's delay?
Quentin

OK that's an old function. Replaced with Sleep(1000)
Tombas

You can get rid of a bunch of whitespace to save bytes. Also, I count 224 bytes, not 188.
HyperNeutrino

@HyperNeutrino you're right - I counted line endings but not leading whitespace. Edited accordingly (sorry I'm new at this!)
Tombas

@Quentin delay() is a function that I hoped could be lifted straight from Arduino... turns out that I can't! It did exist back in the day as part of the dos.h library, I understand.
Tombas

1

Excel VBA, 82 Bytes

Anonymous VBE immediates window function that takes no input and outputs whether or not you should eat your hot dog to cell [A1].

d=Now+#0:4:27#:Do:[A1]=IIf(Now<d,"Not ready yet","Eat your hot dog"):DoEvents:Loop

1
Interesting I didn't knew you can run the program directly from Immediate window
Stupid_Intern

1

Excel VBA 122 94 bytes

Sub p()
e=Now+#0:4:27#
Do
[a1]=IIf(Now<e,"Not ready yet","Eat your hot dog")
Loop
End Sub

Thanks Taylor Scott


You can cut down this solution quite a bit, CDate("00:04:28") can be condensed to #0:4:27#, you can replace your While ... Wend loop with a Do .. Loop Loop and you can replace your if clause with an iif clause
Taylor Scott

@TaylorScott Yes thanks :)
Stupid_Intern

1
@TaylorScott is there any alternative for msgbox ?
Stupid_Intern

1
@TaylorScott also iif clause is not working with msgbox I am not sure why and #0:4:27# autoformats to a date not time you are free to edit the answer if you want
Stupid_Intern

1
Actually because VBA does not have any STDIN or STDOUT, there are a lot of options available to you, such as the VBE immediates window and to cells in excel, you can see more about this at codegolf.stackexchange.com/a/107216/61846
Taylor Scott

0

Javascript, 83 Bytes

d=Date.now()
while(1)alert(Date.now()-d<267000?"Not ready yet":"Eat your hot dog"))

Alertz for everyone!


1
You can change 267000 to 267e3 and save a byte.
powelles

From the question: "You have to make a program". This is not a program or a function, but a snippet.
Luke

7
This is a program.
programmer5000

1
You can save a few bytes by using new Date in place of Date.now(), and another few by using for(d=new Date;;)alert...
ETHproductions

2
alert() halts the program until the user closes and the challenge bans input
dandavis

0

PERL, 76 bytes

$|++;
for(1..247){print'Not ready yet';sleep 1};print "Eat your hot dog";for(;;){}

6
I count 82 bytes.
Oliver

0

PHP 88 bytes

<?$t=0;do{$t++;echo "Not ready yet";sleep(1);} while ($t<267);echo "Eat your hotdog";?>

1
“After this time has elasped, you should output Eat your hot dog until the end of time.” So you have to repeat the 2nd message too. That will add to its length, but fortunately there is place to shorten it: for($t=267;$t--;sleep(1))echo"Not ready yet";for(;;)echo"Eat your hotdog";. By the way, running code with php -r is accepted, so no need for the PHP tags (especially not the closing one, which is considered bad habit in that case: “The closing ?> tag MUST be omitted from files containing only PHP” – PSR-2).
manatwork

1
@manatwork untested: for($t=267;;sleep(1))echo $t-->0?"Not ready yet":"Eat your hotdog";
diynevala

Interesting one, @diynevala. According to the documentation, “If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.” – Integer overflow, so that condition should work correctly until the end of time.
manatwork

@manatwork Also sleeps for 1 second between outputs even after 267 seconds.
diynevala

0

REXX, 82 bytes

do forever
if time(e)<267 then say 'Not ready yet'
else say 'Eat your hot dog'
end

0

Java 7, 152 bytes

void c(){for(long s=System.nanoTime(),e=s+(long)267e9;s<e;s=System.nanoTime())System.out.println("Not ready yet");System.out.print("Eat your hot dog");}

Explanation:

void c(){                                 // Method
  for(                                    //  Loop
      long s=System.nanoTime(),           //    Current time in nanoseconds as start
      e=s+(long)267e9;                    //    End time (267 seconds later)
      s<e;                                //    Loop as long as we haven't reached the end time
      s=System.nanoTime())                //    After every iteration get the new current time in nanoseconds
    System.out.println("Not ready yet");  //   Print "Not ready yet" as long as we loop
                                          //  End of loop (implicit / single-line body)
  System.out.print("Eat your hot dog");   //  Print "Eat your hot dog"
}                                         // End of method

0

PHP, 68 bytes

for($t=268;$t--;sleep(1))echo$t?"Not ready yet←":"Eat your hot dog";

continuous output; is ASCII 10 = LF. Run with -r.

one-time output, 50 bytes

Not ready yet<?sleep(267);echo"←Eat your hot dog";

where is ASCII 13 = CR. Save to file or use piping to run.


0

RBX.Lua, 69 bytes

for i=1,267 do print"Not ready yet"Wait(1)end;print"Eat your hot dog"

RBX.Lua is the language used on ROBLOX.com. It is a modified version of Lua 5.1 that features a built-in 'Wait' function. The above code is pretty self-explanatory, below is a more readable version:

for i = 1, 267 do
    print("Not ready yet");
    Wait(1);
end

print("Eat your hot dog");

The code outputs "Not ready yet" continuously into STDOUT, for 267 seconds (4 minutes 27 seconds) before outputting "Eat your hot dog".


0

C - 130 bytes

It could be slightly shorter (128bytes), but I thought it neater to overwrite "Not ready yet"

#include<stdio.h>
#include<unistd.h>
int main(){printf("Not ready yet");fflush(stdout);sleep(267);printf("\rEat your hot dog\n");}

Welcome on the site! You can omit #include<unistd.h> (it will emit a warning but still compile). Doing as you do (overwriting the previous message) is your right, but since the challenge doesn't really ask for it, I'd suggest not to do it. It would allow you to do int main(){puts("Not ready yet");sleep(267);puts("Eat your hot dog");} (with no includes, they aren't needed) - but no obligation to do it of course.
Dada


-1

Python 2.7, 90 88 bytes

import time;exec"print'Not ready yet';time.sleep(1);"*267;while 1:print"Eat your hotdog"

I don't get why someone -1'd my answer. can some1 explain? :(
Koishore Roy
Используя наш сайт, вы подтверждаете, что прочитали и поняли нашу Политику в отношении файлов cookie и Политику конфиденциальности.
Licensed under cc by-sa 3.0 with attribution required.