Reto
Escriba una función que tome un parámetro: un número entero t
. Su función tiene que detener su programa por t
segundos antes de continuar, de manera similar a time.sleep(t)
Python y WAIT t
BBC BASIC.
No debe utilizar ninguna función integrada de espera ni ninguna función integrada para ejecutar código después de un cierto tiempo, y su programa debe reanudarse después de unos t
segundos.
Para probar su función, hay una tolerancia de 0.1 segundos más o menos que la dada t
en su propia máquina: las variaciones entre las computadoras están bien.
Si alguien cuestiona su respuesta, debe proporcionar una prueba fotográfica (capturada) de que su función funciona correctamente para t=1
, t=5
y t=25
. También puede proporcionar los detalles de su computadora para que las personas puedan intentar replicarla en su propia máquina.
Su programa debe ejecutarse y se ejecutará en una computadora cuya velocidad de reloj sea 1.6 GHz o superior.
Victorioso
El programa más corto gana.
Generosidad
Se otorgará una recompensa por el programa más corto que lo detiene sin usar un bucle que verifica cuánto tiempo ha transcurrido. Si está compitiendo por esta recompensa, agregue una nota al pie que diga que su respuesta es para la recompensa.
Tabla de clasificación
/* Configuration */
var QUESTION_ID = 55293; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 30525;
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var patt = new RegExp(/[Bb]ounty/);
var res = patt.test(body);
var bountyyn = "no";
if (res) {
bountyyn = "yes";
}
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
bounty: bountyyn
});
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link)
.replace("{{BOUNTY}}", a.bounty);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
if (/<a/.test(lang)) lang = jQuery(lang).text();
languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 400px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td><td>Bounty?</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<div id="language-list">
<h2>Winners by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td>{{BOUNTY}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
BBC BASIC
ejemplo una referencia al programa de televisión Sherlock o estoy leyendo demasiado sobre esto?Respuestas:
Código de máquina x86_64, 10 bytes
Hexdump del código:
Código fuente (puede ser ensamblado por
ml64
Visual Studio):Realiza un ciclo vacío, comenzando desde el valor especificado hasta 0. Elegí el multiplicador 945421514 empíricamente por prueba y error, hasta que mi programa de prueba arrojó resultados satisfactorios.
Programa de prueba (espera 10 veces para cada una de las duraciones 1, 5 y 25 segundos):
El resultado:
Ejecuté este programa en una computadora con Windows que no tiene nada más que hacer. Si ejecuta algunas aplicaciones, los tiempos de espera son más erráticos.
La velocidad de la CPU es de 3.9 GHz. Parece que este código es apenas lo suficientemente bueno para la tecnología de PC actual : si la frecuencia del reloj es de aproximadamente 8.8 GHz, el multiplicador no se ajustará a un int de 32 bits con signo.
PD Como esta respuesta no comprueba cuánto tiempo ha pasado, es un candidato para la recompensa.
fuente
Bash,
2925242319 bytesAccuracy test (
time
) where$1
= 1 second:Thanks Dennis for shaving the byte count down to 19 from 23!
EDIT: I've changed the IP to avoid
ping
on Linux pinging 0.0.0.0, which is the loopback device.How this works
ping
has a default timeout of 1 second, so, when contacting an IP address which does not exist, ping can't continue until either the time out has passed, or it has got a reply from the IP.-t
tellsping
to try$1
number of times on this fake IP address, forcingping
to take$1
seconds to complete the ping.It's eligible for the bounty! No loop!
fuente
w()(ping -t$1 0.0)
(We must have differentping
s; mine requires-w$1
and gets a reply from localhost.)/dev/lo
w 10
, I get10.02 sec real
usingtime
.w()(ping -w$1 1.2)
works like a charm.Matlab, 33 bytes
Or you can also use this in Octave: try it online
Matlab, 31 bytes
As suggested by @flawr, it can be done with an anonymous function (it should be assigned a name in order to use it):
Example:
fuente
@(t)eval('tic;while toc<t,end')
eval
to pack several statements in an anonymous function. Thanks!bsxfun
.t
variable inside eval.Java,
6362 bytesNothing surprising - just grabs the number of nanoseconds since 1/1/1970 multiple times and checks if a second has passed.
Saved 1 byte thanks to Ypnypn and aditsu.
fuente
for(long a=System.nanoTime();System.nanoTime()-a<t*1E9;);
t->
?Batch, 27 Bytes
A popular batch trick, since batch didn't have a sleep function.
No loop, so bounty eligible
fuente
set/ac=%1+1
saves 2 bytes.Commodore 64 BASIC, 19
16bytesWith a call
N=<number-of-secods>:GOSUB1000
.However, I cannot provide enough accuracy. Because C64 had about 1 MHz CPU speed, I remember it was good enough to make an empty
FOR
-NEXT
loop 1000 times so that it was about 1 second.In fact there were two main versions of the machine: PAL 0.985 MHz and NTSC 1.023 MHz (all data from C64 Wikipedia Page). As I had NTSC version, it was required to run loop about 930 times.
Tests with the following program (
N
seconds, provided by user inINPUT
):where
TI$
is a system variable containing string (hhmmss
format) with time elapsed from last reset (1 second accuracy, however also depending on CPU speed, so this is not quite relevant, because it's the same clock).Screenshot made with online C64 emulator http://codeazur.com.br/stuff/fc64_final/.
This program (line
1000
only) occupies1619 bytes in memory, as tested withPRINT FRE(0)+65535
both before typing the code (38908 bytes) and after (3889338889 bytes).PRINT FRE(0)
returns free memory for BASIC program (it's a negative value and constant65535
should be added, but in fact it does not matter).Because this program does not test the time elapsed in a loop, it qualifies for a bounty.
fuente
TI$
variable is accurate and it was about 1 second per ca. 2 hours difference with the reference clock (outside C64), so the accuracy is enough. What I am unsure is the value950
, however, would it be any other value <1000 (which I am sure), it's still the same amount of bytesJ
variable should somehow be a part of the real code, not a part of the testing program - so it would wait for N seconds, not just 1 second. I don't know how to integrate it into BASIC's syntax though.1000 FOR I=1 TO N:FOR I=1 TO 950:NEXT I:NEXTJ:RETURN
with a call eg.200 N=5:GOSUB 1000
. Also I've noticed the OP required a function. I will try to fix itGOSUB
-RETURN
statement, as there are no functions in BASICDEF FN
like in BBC BASIC?JavaScript ES6,
504540 bytesthis uses self-executing functions, not sure why
+new Date
isn't working.Usage
I've tested this with Safari Nightly but it will also work on Firefox. Tested with:
You can run it by either surrounding it with parenthesis:
Or by naming it:
Explanation
Here's the main logic behind the program:
The version I'm using uses the same logic:
fuente
CJam, 15
This is a block that can be executed or stored into a variable (thus becoming a named function). Dennis and Mr Consensus agree that counting only the block is acceptable :)
Explanation:
Try it online
fuente
JavaScript,
68 54 5142I think no screenshot is needed. But I suspect you could golf this even more...
New version: I now finally managed to avoid
new
and usingDate
twice:Older versions:
fuente
PHP,
1711778479656462 bytesUsage:
Call the function like so:
php -d error_reporting=0 -r "require 'script.php'; a(5);echo 'Hello, World!';"
Where 5 is the time in seconds the programm should wait before it echoes "Hello, World!".
Explanation:
At first the function gets the current time in milliseconds. Then the function does a loop until the current Time is smaller then the first time + the input. Afterwards "Hello World!" gets echo'ed.
Log:
Saved 113 bytes thanks to Voitcus
Saved 2 bytes thanks to axiac
fuente
$get_as_float
parameter. Also remove$t
,$s
- you don't need them (see my code)echo 1e6;
works. But yes - getting as float is number of seconds, so$e=microtime(1)+$i;
would be enoughJulia,
3320 bytesOnly works in Julia v0.4 due to changes in the function signature of
watch_file
. Defines an anonymous function with a single parametert
that (ab)uses the timeout parameter in thewatch_file
function.This is a candidate for the bounty!
Demonstration using the Julia REPL:
Previous answer (33 bytes), also working in Julia stable
fuente
R, 48 bytes
Demonstration:
fuente
f=
in the byte count, function snippets are fine.PHP, 39 bytes
(Note that I can actually get this shorter if a full program is required by taking advantage of arguments passed on command line. Down to 35)
Program used for testing:
Results:
Though I qualify for the bounty, I'm hardly in the running with some of the other entries!
fuente
Windows CMD, 22 bytes
This uses no loop (label and goto) so this qualifies for the bounty
It sends
t
pings to to 1.0.0.1 (invalid) and waits for a responce for 1000 msfuente
JavaScript ES6, 40 bytes
Tested with the following:
fuente
elapsed(STOP, t)
does? What are STOP and elapsed?elapsed
measures the time it took the first argument to run, in this case,STOP
, which in turn is just the first code snippet. The second arg to elapsed is the arg passed toSTOP
.TI-BASIC (84+SE), 21 bytes
Input method:
T:prgmT
. This is the closest equivalent of a function in TI-BASIC. Program:All accuracy is gained via trial-and-error; timing it with a stopwatch works for all of the given test cases to within a twentieth of a second.
Device information:
W00T eligible for a bounty!
fuente
For(
loops depends on how many letter variables exist? More variables clog up the VAT and can take up to 20% or so of your time. System variables (e.g. n,Xmin
) are immune.Python, 57 bytes
Call function
y()
fuente
PureBasic, 92 bytes
It's the shortest I can think of. I suspect this will be the longest here as well...
To test:
fuente
PowerShell, 75 bytes
Long, descriptive procedure calls. Yay for clarity in a language. :)
Called within a program with something like
Alternatively, if we're allowed external programs to be called instead, we can get down to 59 Bytes with the following:
This would be called within a program as follows (presuming the above to be saved as "wait-function.ps1" and saved in the same folder):
What we save in writing the function/program is more than clobbered by the excess needed to actually execute it, though. Le sigh.
fuente
Python, 66 bytes
Note, my implementation neither calls an inbuilt time function, nor using scheduling feature.
And yes, it is eligible for bounty.
fuente
Hassium, 55 Bytes
Run and see expanded: http://HassiumLang.com/Hassium/index.php?code=9f4e2bdb292b14b150fba63677a11a79
fuente
Pyth, 19 bytes
Late entry but after finding
.d0
in the docs last night I decided to give it a go.Defines a function which loops until the time elapsed is
N
seconds.Try it here.
fuente
DCNJ+.dZN#Ig.dZJB))
, which is also 19 bytes.RProgN 2, 13 bytes
Explained
The bounty specifically says "without using a loop checking how much time has elapsed", which this does not do. This sets a target time, and keeps checking if it's passed that target time, thus it's eligible for the bounty.
Try it online!
fuente
Tcl, 53 bytes
Try it online!
Explained
Command
clock milliseconds
can be reduced toclock mil
, with escaped 1st bracket, it'll be interpreted at each loop, and w/o just once. As it measures milliseconds, we need to multpily by 1000 or 1e3 which saves 1 Byte.fuente
C# (Visual C# Interactive Compiler) + /u:System.Threading, 36 bytes
Try it online!
Creates a semaphore with no capacity and tries to get it for the specified number of seconds.
I realize I am "wait"ing on something here. To me this seems more like the ping/timeout solution as opposed to
Thread.Sleep
. The code tries to get a resource that it cannot get and stops trying after a limit.===
Below is a variation that starts a
Task
with an infinite loop, then waits for it to complete with a timeout. All required namespaces are included by default, but the solution is a few bytes longer than the one above.C# (Visual C# Interactive Compiler), 40 bytes
Try it online!
fuente
05AB1E, 22 bytes
Try it online.
NOTE: Depending on how many microseconds in the current second have already passed, the tolerance might be slightly larger than 0.1 sec. But since almost halve the answers have similar issues, I figured it's allowed.
Explanation:
05AB1E doesn't have any builtins for the current time. It does however have a builtin for the current year/month/day/hours/minutes/seconds/microseconds as separated builtins. Since only using seconds can potentially wrap around from 59 to 0 causing issues, I need both the minutes and seconds, making the code even longer than most answers in non-codegolfing languages unfortunately.
fuente
SmileBASIC, 20 bytes
Opens a dialog box that closes automatically after
T
seconds. I'm not sure if this counts as a "built in waiting function", but I think this is just as valid as usingping
.An alternative 37-byte program which definitely isn't cheating:
Causes the screen fade color to change to 0 (alpha=0,red=0,green=0,blue=0) (no effect) gradually over
T
seconds, then waits for that animation to finish.fuente