Attendere impazientemente l'input


39

Il tuo compito oggi è quello di attuare un limite di tempo per ottenere input, un compito che ho trovato piuttosto fastidioso da realizzare nella maggior parte delle lingue.

Verrà creata una funzione di programma che richiede all'utente l'immissione. Immediatamente dopo che l'utente ha fornito l'input, stampa il messaggio input receivede termina l'esecuzione / ritorno. Tuttavia, se l'utente attende più di 10 secondi per fornire input, emette il messaggio no input receivede termina l'esecuzione / ritorno.

L'input deve provenire dalla stdin(console) o equivalente, non dalla funzione o dagli argomenti del programma, tuttavia l'output può essere a stdout, il valore di ritorno della funzione o qualsiasi altro metodo di output accettato.

Puoi chiedere qualsiasi quantità di input, può essere un singolo carattere, una riga, una parola o qualunque sia il metodo più breve nella tua lingua fintanto che attende almeno un carattere.

È necessario emettere non appena viene ricevuto l'ingresso, non dopo che sono trascorsi i 10 secondi.

Trascorsi 10 secondi, è necessario terminare, non è possibile continuare ad attendere l'immissione dopo la no input receivedstampa.

Si può presumere che l'input non sia passato nel tempo tra 10 secondi trascorsi e il testo stampato sullo schermo, poiché questa è una finestra estremamente piccola. Puoi anche supporre che l'equivalente incorporato nella tua lingua sleepsia costantemente, assolutamente perfetto.

Questo è , vince meno byte!


6
+1 solo per il tocco gradevole per impedire alle lingue del golf di usare il loro dizionario. Oh, e anche una grande sfida.
Adám,

1
@Adám a meno che la tua lingua non abbia una lettura incorporata con timeout, penso che l'unico buon modo per farlo sia la magia OS / Thread, che la maggior parte delle lingue del golf non può fare comunque.
Pavel,

Ora devo riscrivere il mio programma. Era quasi pronto per pubblicare ... ;-)
Adám l'

1
@TheLethalCoder Puoi assumere l'equivalente delle sleepfunzioni della tua lingua perfettamente al 100% delle volte.
Pavel,

1
@Lembik Ecco qua, una risposta Python.
Pavel,

Risposte:


24

bash, 38 byte

read -t10||a=no;echo $a input received

Questo utilizza l' -topzione (timeout) per bash's read, che lo fa fallire e restituisce un codice di uscita diverso da zero se non viene fornito alcun input nel numero di secondi specificato.


6
Dovrebbe dire "(no) input rec ie ved" che ostacola in modo importante le lingue del golf con i dizionari.
Adám,

8
@Adám In realtà è un errore di battitura
Pavel,

7
@Phoenix Noooo!
Adám,

1
Perché a = no allora $ a? c'è uno scopo? EDIT Ho capito che non ho letto correttamente la domanda
Felix Guo,

12

Haskell, 97 89 byte

import System.Timeout
timeout(10^7)getChar>>=putStr.(++"input received").maybe"no "mempty

Se il timeouttimeout ritorna Nothinge Just Char( Char, perché stiamo usando getChar) altrimenti. Questo valore restituito viene convertito in "no "o ""per funzione maybe "no " mempty. Aggiungi "input received"e stampa.

Modifica: @BMO ha suggerito maybee salvato alcuni byte.


Sembra che non funzioni correttamente in ghci.
maple_shaft

@maple_shaft: Entro ghci bisogna legano gcon let: let g Nothing="no ";g _="", allora la chiamata di funzione timeout....funziona bene per me.
nimi,

1
Puoi sostituirlo gcon quello maybe"no "(pure"")più corto e puoi anche inserirlo in linea, risparmiando 6 byte.
ბიმო

@BMO: Bello! memptyinvece di (pure"")è ancora più breve.
nimi,

Molto bello, è davvero intelligente!
ბიმო

11

POSIX C99, 71 63 byte

main(){puts("no input received"+3*poll((int[]){0,1},1,10000));}

Ungolfed:

#include <unistd.h>
#include <poll.h>
#include <stdio.h>
int main()
{
  struct pollfd pfd; 
  pfd.fd = STDIN_FILENO; 
  pfd.events = POLLIN;  
  puts("no input received"+3*poll(&pfd,1,10000));
}

Poiché pollrestituirà 1 in caso di successo, moltiplichiamo il risultato per 3 e spostiamo la stringa di conseguenza. Quindi, usiamo il fatto chestruct pollfd ha il seguente layout:

     struct pollfd {
     int    fd;       /* file descriptor */
     short  events;   /* events to look for */
     short  revents;  /* events returned */
 };

e che STDIN_FILENOè 0, POLLINè 1di sostituire pfdcon int pfd[] = {0,1}, che finalmente facciamo un letterale composto (come consentito dal C99).


3
È necessario specificare che questo destinazione POSIX, poiché l' poll.hintestazione non fa parte dello standard del linguaggio C99.
Cody Gray,

8

Applescript, 113

Applescript non legge davvero da STDIN. Speriamo che a display dialogsia accettabile qui:

({"","no "}'s item((display dialog""default answer""giving up after 10)'s gave up as integer+1))&"input received"

6

APL (Dyalog) , 41 40 byte

'no input received'↓⍨{3*⍨⎕RTL10::03⊣⍞}

Questa è una funzione tacita anonima che necessita di un argomento fittizio per essere eseguita .

'no input received' la stringa completa

↓⍨ rilasciare un numero di caratteri dalla parte anteriore di quello corrispondente al numero restituito da

{ funzione esplicita anonima ( indica l'argomento)

⎕RTL←10 imposta R esponse T ime L imit su dieci secondi

3*⍨ aumentare quel numero (dieci) alla potenza di tre (un migliaio significa "tutto")

:: su tali eccezioni (tutte),

  0 ritorna 0

 provare:

   ottenere input

  3⊣ scartalo e invece restituisci 3

}fine della funzione (si noti che l'argomento non è mai stato menzionato)


6

Perl , 74 67 byte

$m="input received";$SIG{ALRM}=sub{die"no $m\n"};alarm 10;<>;say$m

Vecchia versione

$m="input received";$SIG{ALRM}=sub{die "no $m\n"};alarm 10;<stdin>;say $m;

(Esegui via perl -M5.10.1 ...)


Non è necessaria alcuna nuova riga finale nell'output, quindi è possibile tagliare \n.
Pavel,

3
Benvenuti in PPCG!
Pavel,

In realtà non è necessario -M5.10.1. Si può solo sostituire -econ -E. (se necessario -M5.10.1, dovresti aggiungere una penalità al tuo punteggio)
Brad Gilbert b2gills

@Phoenix, \nc'è a causa del diecomportamento: "Se l'ultimo elemento di ELENCO non termina in una nuova riga, vengono stampati anche il numero della riga di script corrente e il numero della riga di input (se presente) e viene fornita una nuova riga". Quindi senza di esso visualizzerebbe "nessun input ricevuto alla -e riga 1.". Ma, naturalmente, potrebbe essere un'interruzione letterale della stringa. Inoltre, gli spazi tra diee saye i loro parametri non sono necessari. Lo stesso per la finale ;. Ed <>è sufficiente leggere dallo standard input.
arte

1
If you eval the read from STDIN, you can avoid needing a die message. In fact, a runtime error works just as well: $SIG{ALRM}=sub{&0};alarm 10;say'no 'x!eval'<>','input received'.
primo

6

Perl 6,  72  66 bytes

my $s='input received';Promise.in(10).then:{say "no $s";exit};get;say $s

Try it with no input
Try it with input

my$s='input received';start {sleep 10;say "no $s";exit};get;say $s

Try it with no input
Try it with input

my $s = 'input received'; # base message

start {         # create a Promise with a code block
                # that is run in parallel
  sleep 10;     # delay for 10 seconds
  say "no $s";  # say 「no input received」
  exit          # exit from the process
}

get;            # get a line from the input
say $s          # say 「input received」

1
"my ess is input recieved -- promise in 10 then say 'no ess' and exit or get say 'ess'"
cat

Can you remove the space between start and {?
Pavel

@Phoenix That would be parsed as associative indexing on a sigilless variable named start, so no.
Brad Gilbert b2gills

Your TIO links appear not to work anymore.
Pavel

@Pavel, Fixed, just had to make the dummy test class a subtype of IO::Handle and call .new on it
Brad Gilbert b2gills

5

C#, 180 171 148 131 bytes

()=>{var t=new System.Threading.Thread(()=>{System.Console.ReadKey();});t.Start();return(t.Join(10000)?"":"no ")+"input recieved";}

Saved 17 bytes thanks to @VisualMelon.

Full/Formatted version:

class P
{
    static void Main()
    {
        System.Func<string> f = () =>
        {
            var t = new System.Threading.Thread(() =>
            {
                System.Console.ReadKey();
            });
            t.Start();

            return (t.Join(10000) ? "" : "no ") + "input recieved";
        };

        System.Console.WriteLine(f());
        System.Console.ReadLine();
    }
}

Why namespace and not a using directive?
Pavel

@Phoenix they would need a namespace anyway so they save all the bytes of the using
LiefdeWen

Why did you save the crucial part as an Action and execute it afterwards? I can't really see the question specifying this.
Snowfire

1
Can save quite a bit by using the return value from Thread.Join(int), (rid of c, lose braces, etc. etc.): var t=new System.Threading.Thread(()=>System.Console.ReadKey());t.Start();return(t.Join(10000)?"":"no ")+"input recieved"; (VB.NET already seems to do this)
VisualMelon

1
@TaylorScott I can do 1e4 but that is a double and I'd need an int so I'd have to do (int)1e4 :( Nice idea though
TheLethalCoder

5

TI-BASIC, 84 77 bytes

-7 thanks to @kamoroso94

:startTmr→T         //Start Timer, 5 bytes
:Repeat checkTmr(T)=10 or abs(int(.1K)-8)≤1 and 1≥abs(3-10fPart(.1K  //Loop until the timer is 10 seconds or a number key is pressed, 32 bytes
:getKey→K           //get key code, 4 bytes
:End                //end loop, 2 bytes
:"NO INPUT RECEIVED //Push string "NO INPUT RECEIVED" to Ans, 18 bytes
:If K               //If input was received, 3 bytes
:Disp sub(Ans,3,15  //Diplay "INPUT RECEIVED", 9 bytes
:If not(K           //If no input, 3 bytes
:Ans                //Display "NO INPUT RECEIVED", 1 byte

Waits until a number is pressed.

I am trying to figure out how to golf the sequence {72,73,74,82,83,84,92,93,94}. It is taking up a lot of space.


If you want to wait for just any key, then Repeat K or 10=checkTmr(T would do.
bb94

Also, the last 4 lines could be shortened to :4-3not(K:sub("NO INPUT RECEIVED",Ans,18-Ans
bb94

1
@bb94 I don't really want to wait for just any key, since not all of those would actually input a character. It would be like waiting for the Shift key on a computer. Also, shortening the last 4 lines with your method actually gives the same byte count as mine. I like your method, though.
Scott Milner

You could check for any key that isn't 21 or 31.
bb94

After or in your repeat statement, use this instead for -7 bytes: abs(int(.1K)-8)≤1 and 1≥abs(3-10fPart(.1K
kamoroso94

4

NodeJS, 105 103 101 bytes

-2 bytes thanks to @apsillers
-2 bytes by moving console.log() into exit()

with(process)stdin.on('data',r=x=>exit(console.log((x?'':'no ')+'input received'))),setTimeout(r,1e4)

Run by saving to a file and running it with node or run it straight from the command line by doing node -e "<code>"


@apsillers Yup, good catch.
Justin Mariner

@apsillers I was about to edit again to actually move the console.log() call into the parameter of exit(). That's two less, now.
Justin Mariner

4

JavaScript (ES6) + HTML, 86 84 82 79+11 = 97 95 93 90 bytes

setTimeout(oninput=_=>i.remove(alert(`${i.value?"":"no "}input received`)),1e4)
<input id=i
  • 2 bytes saved thanks to apsillers pointing out that I'm dumb!

Try it

Requires a closing > on the input in order to work in a Snippet.

setTimeout(oninput=_=>i.remove(alert(`${i.value?"":"no "}input received`)),1e4)
<input id=i>


1e5 is 100,000 or 100 seconds, 1e4 is 10 seconds
PunPun1000

Oops! Well spotted, thanks, @PunPun1000
Shaggy

Wouldn't it be shorter to write 10 instead of 1e4?
musicman523

@musicman523, 10 would be 10 milliseconds, the challenge challenge specifically says 10 seconds, which is 10000 milliseconds, hence 1e4.
Shaggy

My bad, forgot that 10 != 1e4 because I'm a fool
musicman523

3

VB.Net - 174 bytes

Module M
Sub Main()
Dim t=New Threading.Thread(Sub()Console.Read()):t.Start():Console.WriteLine(If(t.Join(10000),"","no ") & "input received"):End
End Sub
End Module

COBOL version coming tomorrow ;-)


3
I'm not sure what the advantage is of combining lines with :. That takes the same number of bytes as a line break, so it just decreases readability without improving the golf score.
Cody Gray

@CodyGray I believe that the : line break substitution may be so that the treading call may be declared inline without repeating - but that said I am not positive, my main language is VBA which does not support threading or reading from the <strike>console</strike> immediate window asside from at the time of function definition or calling :P
Taylor Scott

3

Go, 149 bytes

package main
import(
."fmt"
."time"
."os"
)
func main(){
o:="input received"
go func(){Sleep(1e10)
Print("no "+o)
Exit(0)}()
i:=""
Scan(&i)
Print(o)}

3

AHK, 67 65 bytes

2 bytes saved by Blauhirn

InputBox,o,,,,,,,,,10
s:=ErrorLevel?"no ":
Send %s%input received

AHK has a built-in timeout for input boxes.
I tried to get clever and use !o instead of ErrorLevel but that fails if the user inputs a falsey value.
Almost half of the answer is just the command names and fixed text.


1
What are all the commas for?
Pavel

@Phoenix Probably eliding arguments to InputBox
Adám

@Phoenix Timeout is almost the last parameter: InputBox, OutputVar [, Title, Prompt, HIDE, Width, Height, X, Y, Font, Timeout, Default]
Engineer Toast

two chars shorter: s:=errorLevel?"no ":
phil294

@Blauhirn Gah! I'm an idiot. Thanks.
Engineer Toast

3

Python3, 100 89 83 71 bytes

import pty
print("no input received"[3*any(pty.select([0],[],[],10)):])

First try at golfing.

-4 for any(), -7 for slicing, thanks @user2357112!

-6, get select() from pty instead of select.


You can cut some bytes out by slicing a "no input received" string: "no input received"[3*bool(...):].
user2357112 supports Monica

You can also use any(...) instead of bool(...[0]).
user2357112 supports Monica

-New User: "on Windows it throws ModuleNotFoundError: No module named 'termios'"
FantaC

The pty module is only available on linux platforms, but I'm only using it because its name is short and it makes select available. Version 2 probably works better on Windows.
Seth

3

PowerShell, 110 bytes

$s1=date;while(![console]::KeyAvailable-and($i=((date)-$s1).seconds-lt10)){}
"{0}input received"-f(,'no ')[$i]

3

Python 3, 158 bytes

import os,threading as t,time
def k(t=10):time.sleep(t);print("No input received"[(10-t)//3:]);os.kill(os.getpid(),t)
t.Thread(None,k).start()
if input():k(0)

I tried running Seth's Python 3 answer but on Windows it throws ModuleNotFoundError: No module named 'termios', and since I can't comment on his answer about it, I decided to instead come up with a solution that should be platform independent.

It's my first time golfing so I'm sure it could be improved.


2
Welcome to PPCG!
Steadybox

2

Tcl, 99 bytes

after 10000 {set () no}
vwait [fileevent stdin r {gets stdin (x)}]
puts [lappend () input received]

2

SmileBASIC 3, 74 bytes

"Accepts input" by waiting for any button press (that should count as input.)

M=MAINCNT@L
N=MAINCNT-M>599CLS?"NO "*N;"INPUT RECEIVED
ON N+BUTTON()GOTO@L

Output should be "(no) input received", not "INPUT (NOT) RECEIVED"
Pavel

2

Scratch 2/3.x, 41 points (Explanation)

Impatient timer

1: When GF clicked

1: ask [] and wait

1 + 14 chars: say [input received]

1: stop [all v] (note: since "all" was its default setting I counted the block as 1)

1 + 2 digits: wait (10) seconds

1 + 17 chars: say [no input received]

1: stop [all v]


Welcome to PCG!
Rahul Bharadwaj

1

><>, 43 + 6 = 49 bytes

a/!/i0(?\~"input recieved"r>o<
o "\?:-1/r"n

Try it online!

+5 for the -t.08 flag, which sets the tick to 0.08 seconds, and +1 for the a flag, which counts whitespace and skipped instructions as ticks.

The program checks for input about once every second, and exits the loop if input is detected. If input is not received, it exits the loop from the bottom, appending no to the beginning of the string. The initial / is to ensure that the last check for input is exactly on the 10 second mark.

It then takes about 5-6 seconds to print the string itself.


You can use a single flag, -at.08 to save a byte.
Pavel

@Pavel, Thanks!
Jo King

1

Java 1.4+, 284 bytes

import static java.lang.System.*;public class X{public static void main(String[]x){new Thread(){public void run(){try{Thread.sleep(10000L);}catch(Exception e){}out.print("no input recieved");exit(0);}}.start();new java.util.Scanner(System.in).nextLine();out.print("input recieved");}}

Ungolfed:

import static java.lang.System.*;

public class InputAndWait {
    public static void main(String[] x) {
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(10000L);
                } catch (Exception e) {
                }
                out.print("no input recieved");
                exit(0);
            }
        }.start();
        new java.util.Scanner(System.in).nextLine();
        out.print("input recieved");
    }
}

Please don't suggest Version-specific Java improvements, this is a generic Java answer that works in all currently stable Java Environments (1.4 and above).


Very freaking wordy... The catch is required, can't throw it. System import shaves off like 5 bytes... Overloading is also wordy, so it ends up a wordy poorly-golfed-looking mess.


Does it have to be 10000L and not 10000? I thought ints cast to longs automatically.
Pavel


0

SmileBASIC, 74 73 bytes

M=MAINCNT
WHILE!I*M>MAINCNT-600I=INKEY$()>"
WEND?"no "*!I;"input received

Takes 1 character of input.

And a 39 byte solution which probably isn't valid (doesn't actually accept text input, just has an OK button that you can press)

?"no "*!DIALOG("",,,10);"input received
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.