Le tue istruzioni "per"


38

Le tue istruzioni "per"

Supponendo che tu abbia il seguente input: a, b, c, d

L'ingresso può essere su una riga usando qualsiasi formato "a / b / c / d" o "a, b, c, d" ecc.

Puoi anche avere 4 ingressi.

È necessario codificare il seguente comportamento (pseudo-codice qui):

var i = <a>
while (i <b> <c>)
    print i
    i = i + <d>
    print "\n"

Ecco alcuni casi di test:

input : 1,<,10,1
output :
1
2
3
4
5
6
7
8
9

Ancora uno:

input : 20,>,10,1
output :
20
21
22
23
24
25
26
27
...
infinite loop / program crashes
  • aè un numero intero , il valore iniziale di i.

  • bè una stringa o un carattere , non può essere qualcos'altro, il comparatore utilizzato nella condizione finale del forciclo.

    bpuò e deve essere una delle seguenti stringhe:

    - ">"
    - "<"
    
  • cè un numero intero , il numero utilizzato nella condizione finale del for ciclo.

  • dè un numero intero che viene aggiunto a ogni ciclo.

Questo è code-golf, vince la risposta più breve!


1
I numeri possono essere restituiti da una funzione come elenco / sequenza, anziché essere stampati su stdout?
smls

@smls No scusa, l'output deve essere come negli esempi!
Sygmei,

1
Dice che il mio codice dovrebbe seguire lo pseudo-codice e c'è un print "\n", ma sto usando l'avviso javascript per ogni riga. Sarebbe accettabile o dovrei usare console.log invece di allungare la mia risposta?

2
È possibile utilizzare la funzione di avviso come metodo di uscita ma non è possibile utilizzare più avvisi. Qualcosa del genere alert("23\n24\n25");avrebbe funzionato mentre alert("23"); alert("24"); alert(25);non lo sarebbe
Sygmei,

Risposte:


25

JavaScript (ES6),  44  43 56 byte

Salvato 1 byte grazie a ETHproductions
Edit: risolto per soddisfare i requisiti di output

(a,b,c,d)=>{for(s='';eval(a+b+c);a+=d)s+=a+`
`;alert(s)}

Test


Bel uso dell'ambito!
ETHproductions

Penso che puoi riorganizzare il evalper salvare un byte:(a,b,c,d)=>{for(;eval(a+b+c);a+=d)alert(a)}
ETHproductions

@ETHproductions Ah, sì. Ben fatto!
Arnauld,

5
Sono 44 con un tutu!
aross

Questo non segue le specifiche in cui l'output è riga per riga con U + 000A dopo ogni riga.
Joey,

17

Javascript (ES6), 47 42 48 byte

Volevo realizzare la versione for ma qualcuno era più veloce, quindi ecco la versione ricorsiva.

(b,c,d)=>F=a=>eval(a+b+c)&&console.log(a)|F(a+d)

Devi aggiungere f=prima e chiamarlo come f(b,c,d)(a).

Mille grazie ad Arnauld per il fantastico golf.

alertmodificato in a console.logcausa delle specifiche di output


@Arnauld Grazie, è un bel golf. Gliel'ho appena chiesto, quindi vediamo se lo accetta.

Sono contento di vederlo accettato. ;)
Arnauld il

Questo non segue le specifiche in cui l'output è riga per riga con U + 000A dopo ogni riga.
Joey,

@Joey Questo è solo uno pseudo-codice, ma chiederò a OP di questo.

@Masterzagh: c'era già una domanda sui formati di output alternativi che era stata negata.
Joey,


13

Gelatina , 12 byte

Ṅ+⁶µ⁴;⁵¹vµ¿t

Provalo online!

Jelly ha molti modi per eseguire ripetutamente iterazione, creare intervalli, ecc. Tuttavia, rispecchiare esattamente il comportamento di C ++ è abbastanza difficile, a causa di casi speciali come l'incremento è 0, il ciclo termina prima di iniziare (a causa della disuguaglianza al contrario ) e l'incremento va nella direzione sbagliata (il che significa che le condizioni di uscita del loop non possono essere soddisfatte in modo naturale). Come tale, questa soluzione è fondamentalmente una traduzione diretta del C ++, anche se ciò lo rende piuttosto più basso livello rispetto a un normale programma Jelly. Fortunatamente, C ++ ha un comportamento indefinito sull'overflow di numeri interi con segno (la domanda usa int), il che significa che un programma può fare qualsiasi cosa in quel caso, e quindi non è necessario cercare di imitare il comportamento dell'overflow.

Spiegazione

Ṅ+⁶µ⁴;⁵¹vµ¿t
   µ     µ¿   While loop; while ((⁴;⁵¹v) counter) do (counter = (Ṅ+⁶)counter).
    ⁴;⁵       Second input (b) appended to third input (c), e.g. "<10"
        v     Evaluate, e.g. if the counter is 5, "<10" of the counter is true
       ¹      No-op, resolves a parser ambiguity
Ṅ             Output the counter, plus a newline
 +⁶           Add the fourth input (d)
           t  Crashes the program (because the counter is not a list)

Arrestare il programma è il modo più semplice per disattivare l'output implicito di Jelly (altrimenti, produrrebbe il valore finale del contatore); genera un sacco di messaggi di errore su stderr, ma normalmente lo consideriamo permesso.

Per inciso, il contatore di loop viene inizializzato con il valore corrente prima dell'inizio del loop. Quando il ciclo appare all'inizio del programma, quello sarà il primo input.


È possibile passare ta non avere crash. Il dequeue risulta in un elenco vuoto per il quale la stampa implicita di Jelly non produce nulla.
Jonathan Allan,

@JonathanAllan: No, quello che fa in realtà è creare un intervallo da 2 al valore dato, che è sicuramente visibile su una stampa implicita.

Ah, devo aver provato quella teoria con un ciclo che termina in territorio negativo; in effetti un intervallo viene creato implicitamente.
Jonathan Allan,

Uhm, questo è di 12 caratteri, ma non è di 12 byte giusto?
Cruncher,

@Cruncher: Jelly utilizza la propria codifica in cui ogni carattere utilizzato dalla lingua è rappresentato da un singolo byte (utilizza solo 256 caratteri diversi). Il motivo per cui non usa qualcosa di meglio noto come code page 437 è per rendere più facile la digitazione (voglio dire, non è così facile da scrivere, ma è più facile di un linguaggio come gs2). Un hexdump di questo programma sarebbe lungo 12 byte.



9

Java, 58 byte

(a,b,c,d)->{for(;b>61?a>c:a<c;a+=d)System.out.println(a);}

14
C'è un motivo per creare i? Potresti saltare la parte di inizializzazione e usare solo a? Inoltre, usando il valore ASCII di '>' (62) si salva un byte.
Riley,

6
Dopo il commento di Riley, puoi fareb>61
Kritixi Lithos il

Non credo che questo compili.
Capo Due Matite

@ChiefTwoPencils È una funzione. Devi scrivere un programma di test attorno ad esso per compilarlo.
wizzwizz4,

@ wizzwizz4, ovviamente. Ma non funziona ancora. Dagli Un colpo. Inoltre, la mia comprensione è che tutti i byte necessari per eseguirlo contano.
ChiefTwoPencils

7

05AB1E , 22 20 byte

[D²`'>Q"‹›"è.V_#D,³+

Provalo online!

Spiegazione

[                       # start loop
 D                      # copy top of stack (current value of a)
  ²`                    # push b,c to stack
    '>Q                 # compare b to ">" for equality
       "‹›"             # push this string
           è            # index into the string with this result of the equality check
            .V          # execute this command comparing a with c
              _#        # if the condition is false, exit loop (and program)
                D,      # print a copy of the top of the stack (current value of a)
                  ³+    # increment top of stack (a) by d

1
Si accetta qualsiasi formato di input, quindi la seconda versione va bene :)
Sygmei,

7

SmileBASIC, 53 byte

INPUT A,B$,C,D
S=ASC(B$)-61WHILE S*A>S*C?A
A=A+D
WEND

Spiegazione:

INPUT A,B$,C,D
IF B$=="<" THEN S=-1 ELSE S=1 'get comparison direction
I=A
WHILE S*I>S*C 'loop while I is less than/greater than the end
 PRINT I
 INC I,D
WEND

Questo utilizza il fatto che X<Yè lo stesso di-X>-Y


Mi fiderò di te per questo, non ho un 3DS da testare :)
Sygmei,

Ho Petit Computer, così bella idea! Proverò qualcosa del genere prima o poi ...
python-b5,

È possibile utilizzare READun'istruzione, salvando 1 byte.
ckjbgames,

@ckjbgames come?
Me21,

@ 12Me21 Controlla i manuali di SmileBASIC. Dovrebbe essere nell'elenco delle istruzioni per SmileBASIC.
ckjbgames,

6

Impilato , 34 byte

@d@c@b[show d+][:c b tofunc!]while

Provalo online! (Test incluso.) Questa è una funzione che si aspetta che lo stack assomigli a:

a b c d

Per esempio:

1 '<' 10 2
@d@c@b[show d+][:c b tofunc!]while

Spiegazione

@d@c@b[show d+][:c b tofunc!]while
@d@c@b                               assign variables
               [............]while   while:
                :c                   duplicate "i" and push c
                   b tofunc!         convert b to a function and execute it
      [.......]                      do:
       show                          output "i" without popping
            d+                       and add the step to it

4

C ++, 80

Spiacenti, C++non lo è C. Era un po 'confuso dalla domanda.

void f(int a,char b,int c,int d){for(;b==62?a>c:a<c;a+=d)cout<<a<<endl;}

Questo è C o C ++?
Betseg,

10
Quale implementazione di C ++? (Sono curioso di sapere come stai ottenendo qualcosa di simile using namespace stdgratuitamente).
H Walters,

Non ideve iniziare da a, no 0? Puoi semplicemente usare ae saltare del itutto e usare il valore ASCII di '>'. for(;b==62?a>c:a<c;a+=d)
Riley,

Non funziona perf(1,'<'3,1);
Roman Gräf, il

Ack ... sì, richiede la matematica su entrambi i lati; for(b-=61;b*a>b*c;a+=d)funziona per un singolo byte; ma anche così for(;b-62?a<c:a>c;a+=d).
H Walters,



4

Pip , 14 byte

W Va.b.ca:d+Pa

Accetta quattro argomenti della riga di comando. Supporta numeri negativi e in virgola mobile e operatori di confronto < > = <= >= !=. Provalo online!

                a,b,c,d are cmdline args
W               While loop with the following condition:
  Va.b.c          Concatenate a,b,c and eval
            Pa  Print a with newline (expression also returns value of a)
        a:d+    Add d to that and assign back to a

4

Gelatina , 8 byte

ḢṄ+⁹;µV¿

Questo è un collegamento diadico che prende a, b, c come argomento sinistro e d come diritto. L'output può essere infinito e passa a STDOUT.

Provalo online!

Come funziona

ḢṄ+⁹;µV¿  Dyadic link.
          Left argument:  a,b,c (integer, character, integer)
          Right argument: d     (integer)

       ¿  While...
      V     the eval atom applied to a,b,c returns 1:
     µ       Combine the links to the left into a chain and apply it to a,b,c.
Ḣ              Head; pop and yield a from a,b,c.
 Ṅ             Print a, followed by a linefeed.
  +⁹           Add a and the right argument (d) of the dyadic link.
    ;          Concatenate the result and the popped argument of the chain,
               yielding a+d,b,c.

Gli argomenti della riga di comando usano la sintassi di Python e non sono in grado di distinguere tra un carattere e una stringa singleton. Se si desidera utilizzare i CLA, è necessario inserire un Fper appiattire l'array.
Dennis,

2
Ora voglio eliminare metà del mio commento poiché è obsoleto, mantenendo l'altra metà. Immagino che ripeterò solo la metà pertinente ed eliminerò il resto: "Oh, bleh, l'hai definita come una funzione in modo da poter ignorare l'output implicito secondo le regole PPCG. Avrei dovuto pensarci."

4

Python 2 , 45 byte

exec"i=%d\nwhile i%c%d:print i;i+=%d"%input()

Provalo online!

Un'implementazione molto letterale delle specifiche. Prende il modello di codice, sostituisce gli input tramite la formattazione delle stringhe e lo esegue.


4

TeX semplice, 88 byte

\newcount\i\def\for#1 #2 #3 #4 {\i#1\loop\the\i\endgraf\advance\i#4\ifnum\i#2#3\repeat} 

Il comando \forfornisce la funzione richiesta. Salvarlo come for.texe quindi eseguirlo e immettere i valori delle variabili nella riga di comando: pdftex '\input for \for 1 < 5 1 \bye'I valori delle variabili devono essere separati da spazi.


4

Python 3, 61 byte

Una fodera:

e=input;exec(f'i={e()}\nwhile i{e()}{e()}:print(i);i+={e()}')

Benvenuti nel sito! Buon uso della nuova funzione di interpolazione letterale delle stringhe. Penso che potresti essere in grado di salvare un byte sostituendolo \tcon uno spazio.
0

Grazie ancora della stessa dimensione dopo aver rimosso il \ n \ t dopo la terza e ()
G-Ox7cd,


3

Bash (+ Unix Tools), 29 byte

golfed

bc<<<"for(x=$1;x$2$3;x+=$4)x"

Test

./forloop 1 '<' 10 1
1
2
3
4
5
6
7
8
9

1
Ha. Ero sul punto di pubblicare il esatto stessa cosa! +1
Trauma digitale il


3

Lisp comune, 82 80 79 73 64 byte

(defmacro f(a b c d)`(do((i,a(+ i,d)))((not(,b i,c)))(print i)))

Test

(f 1 < 10 1)

1 
2 
3 
4 
5 
6 
7 
8 
9 
NIL
CL-USER> 

-9 byte grazie a PrzemysławP.


Forse puoi salvare 9 byte, definendo una macro. (defmacro f(a b c d)<insert backqoute here>(do((i,a(+ i,d)))((not(,b i,c)))(print i)))Utilizzo:(f 1 < 10 1)

@ PrzemysławP Grazie ancora!
coredump,

3

PHP, 69 65 byte

for(list(,$i,$b,$c,$d)=$argv);$b<"="?$i<$c:$i>$c;$i+=$d)echo"$i
";

Esegui con '-r'; fornire argomenti della riga di comando come input.

Per un solo byte più 4 byte in più, posso prendere ogni operatore:

for(list(,$i,$b,$c,$d)=$argv;eval("return $i$b$c;");$i+=$d)echo"$i
";

Sì, malvagia valutazione. Sapevi che può restituire qualcosa?


La destrutturazione abbreviata [,$i,$b,$c,$d]=$argv;risparmierebbe altri 4 byte;
ma PHP 7.1 postdatizza la sfida.


Pulito! Non ero sicuro durante la creazione della sfida se avessi dovuto includere tutti gli operatori comuni, quindi mi sono ricordato che non sono tutti uguali (~ = per! = Ad esempio in Lua)
Sygmei,

Woah, eval IS evil.
cyberbit

It seems to me that you can use PHP 7.1 to make it shorter. If it is not so the use of list saves 4 Bytes plus 4 Bytes with short syntax
Jörg Hülsermann

@PHP 7.1 postdates the challenge; but thanks for list().
Titus

2

Perl 6, 44 bytes

{.say for $^a,*+$^d...^*cmp$^c!= $^b.ord-61}

How it works

{                                          }  # A lambda.
          $^a                                 # Argument a.
             ,*+$^d                           # Iteratively add d,
                   ...^                       # until (but not including the endpoint)
                       *cmp$^c                # the current value compared to c
                                              # (less=-1, same=0, more=1)
                              != $^b.ord-61.  # isn't the codepoint of the b minus 61.
 .say for                                     # Print each number followed by a newline.

If it's okay to return a (potentially infinite) sequence of numbers as a value of type Seq, instead of printing the numbers to stdout, the .say for part could be removed, bringing it down to 35 bytes.


2

Clojure, 66 63 bytes

#(when((if(= %2"<")< >)% %3)(println %)(recur(+ % %4)%2 %3 %4))

-3 bytes by factoring out the loop. I'm "abusing" the init parameter to act as the running accumulator.

Recursive solution (with TCO). See comments in pregolfed code. I tried a non-TCO recursive solution, and it ended up being 67 bytes.

I'd love to see this beat in Clojure! I think this is the smallest I can get it.

(defn my-for [init-num com-str com-num inc-num]
  (let [op (if (= com-str "<") < >)] ; Figure out which operator to use
    (when (op init-num com-num) ; When the condition is true, print and recur
      (println init-num)
      (recur (+ init-num inc-num) com-str com-num inc-num))))
    ; Else, terminate (implicit) 

Oh I didn't notice this answer. #(when(({">">"<"<}%2)% %3)(println %)(recur(+ % %4)%2 %3 %4)) would be 61 bytes, combining your when with my ({">">"<"<}%2).
NikoNyrh

2

Groovy, 51 bytes

{a,b,c,d->while(Eval.me("$a$b$c")){println a;a+=d}}

This is an unnamed closure. Try it Online!

Caution - If you want to test this with groovy console, make sure you kill the entire process when the input causes an infinite loop. I noticed this after it consumed ~5 gigs of RAM.


2

QBIC, 51 40 bytes

:;::{?a┘a=a+c~A=@<`|~a>=b|_X]\~a<=b|_X

And three minutes after posting I realised I could simplify the terminator logic...

:;::      Consecutively read a, A$, b and c from the command line
{?a┘      Start an infinite loop; print a, add a newline to the source
a=a+c     increment a
~A=@<`|   If we are in LESS THAN mode
  ~a>=b   and IF we are no longer LESS
    |_X]  THEN QUIT, end if.
  \       ELSE (we're in GREATER THAN mode)
    ~a<=b IF we are no longer GREATER
    |_X   THEN QUIT
          The last IF and the loop are auto-closed

2

Batch, 94 bytes

@set i=%1
@set o=gtr
@if "%~2"=="<" set o=lss
:g
@if %i% %o% %3 echo %i%&set/ai+=%4&goto g

If it wasn't for the second parameter behaviour, it could be done in 53 bytes:

@for /l %%i in (%1,%4,%n%)do @if not %%i==%3 echo %%i

This simply does nothing if the step has the wrong sign. The extra test is because Batch's for loop allows the loop variable to equal the end value.


2

Clojure, 66 bytes

#(loop[i %](if(({">">"<"<}%2)i %3)(do(println i)(recur(+ i %4)))))

This could have been 55 bytes as< and > are functions in Clojure:

(def f #(loop[i %](if(%2 i %3)(do(println i)(recur(+ i %4))))))
(f 1 < 10 1)

I like the use of the map here. I would have never thought that that would have beaten my way. Also interesting that both of our initial counts were the same, despite slightly different approaches.
Carcigenicate

Allowing b to be a function would give an unfair advantage to some languages :)
Sygmei

True, but I think most languages I know of wouldn't benefit much from allowing < instead of "<", except Clojure.
NikoNyrh

@Sygmei True. It would be freakin sweet though. Can't blame you making that call.
Carcigenicate

OP said characters are fine instead of strings for the comparison operators btw. That should save a couple bytes.
Carcigenicate

2

TI-Basic, 41 34 bytes

Prompt A,Str2,Str3,D
While expr("A"+Str2+Str3
Disp A
A+D->A
End

1
The way that a TI calculator works, many symbols are stored as a single byte. Prompt , Str2, Str3, While , expr(, Disp , ->, and End are all single-byte symbols. I count 29 bytes.
Pavel

@Pavel Thanks for your interest! Although it's true that TI-Basic is tokenized, not all tokens are one byte. For example, Str2, Str3, and expr( are all two-byte tokens. To see a list of one-byte tokens, check out tibasicdev.wikidot.com/one-byte-tokens
Timtech
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.