Gara numerica verso il basso


10

Il tuo compito è quello di creare un programma che aggiunge numeri casuali alle somme precedenti nello showdown di corse di numeri definitivi.

Ogni corridore (colonna) inizia da 0 e aggiunge 1 o 0 alla somma precedente in ogni fase della gara fino a quando tutti i corridori raggiungono il punteggio richiesto per vincere. 1 o 0 dovrebbero essere scelti a caso (la definizione standard di random può essere trovata qui ). L'output mostrerà il risultato della gara, con ogni colonna che rappresenta un pilota, in questo formato:

>> racers:5,score needed:2

0 0 0 0 0 # all racers start at 0
+ + + + + # add
1 0 0 0 1 # random 1 or 0
= = = = = # equals
1 0 0 0 1 # sum
+ + + + +
0 0 0 0 1
= = = = =
1 0 0 0 2 # winner!
+ + + +  
1 1 1 1  
= = = =  
2 1 1 1  
  + + +  
  1 1 1  
  = = =  
  2 2 2   # losers

Nota: solo i numeri, + e = devono essere inclusi nell'output.

Ingresso

Il tuo programma accetterà i seguenti due parametri come input:

  1. il numero di corridori (colonne), che deve essere maggiore di due
  2. il punteggio richiesto per vincere, che deve essere maggiore di uno

Questo è code-golf - vince il programma con il minor numero di byte.

Modifica: c'è un punteggio massimo non esecutivo di 9 - questo per preservare l'integrità della colonna. Inoltre, gli spazi tra le colonne possono essere omessi nell'output.


Qual è il numero massimo di colonne e il punteggio massimo che dovrebbe essere supportato?
nanofarad,

Non esiste un massimo definito, quindi sarebbe uguale al minimo: almeno tre colonne e un punteggio di due.
atlanteologo il

3
Il punteggio richiesto avrà due cifre?
Leaky Nun,

4
"solo i numeri, + e = devono essere inclusi nell'output." che dire degli spazi?
Leaky Nun,

Gli spazi non devono essere preservati, sono nell'esempio per chiarezza. Buona domanda sulle due cifre - suppongo che ci sia un punteggio massimo, che è nove. Modificherò la domanda.
atlanteologo,

Risposte:


5

Gelatina, 37 36 33 byte

,‘X
0Ç<³$пµżIFµ“+=”ṁṖ⁸żF
ÇСḊz⁶G

3 byte grazie a Dennis.

Provalo online

Spiegazione

,‘X                    Helper link. Argument: n. Radomly return n or n+1.

 ‘                     Increment n
,                      Pair. Yield [n, n+1]
  X                    Return a random item from the pair.

0Ç<³$пµżIFµ“+=”ṁṖ⁸żF   Monadic link. Argument: s. Generate one racer.

0                       Start with value 0.
  <³$пµ                While value is less than s:
 Ç                        Use helper link to increment current value.
                        Collect intermediate results in a list.
         I              Compute consecutive differences.
        ż               Zip intermediate results with their next increment value 0 or 1.
          Fµ            Flatten. Let's call the current list A.
                        Odd items of A are racer state and even items are random 0 or 1.
            “+=”        Yield "+=".
                 Ṗ      Yield A without its last element.
                ṁ       Mold i.e Repeat the characters of the string until it contains length(A)-1 characters.
                  ⁸ż    Zipwith. Pair the elements of A with the correponding characters
                    F   Flatten.

ÇСṫ2z” G               Main link. Arguments: s (score needed), r (#racers)

ÇС                     Call the link above r times.
                        Generate a list of r racers.
   Ḋ                    Remove first element of the list (its a garbage s value)
    z⁶                  Transpose with space as fill value.
      G                 Grid. Format the result.

Puoi sostituire il primo collegamento helper con ,‘X(accoppia con n incrementato , scelta casuale). Nel collegamento principale ṫ2può essere sostituito con (dequeue) e con la variabile .
Dennis,


2

TSQL, 367 345 341 byte

golfed

DECLARE @r int=20, -- racers
        @g char=2  -- goal

DECLARE @ varchar(99)=REPLICATE('0',@r)a:PRINT @
DECLARE @A varchar(99)='',@s varchar(99)='',@i int=0WHILE @i<@r
SELECT
@i+=1,@A+=char(43-x*11),@s+=IIF(x=1,' ',LEFT(y,1)),@=RIGHT(@,@r-1)+IIF(x=1,' ',REPLACE(LEFT(@,1)+y,@g+1,' '))FROM(SELECT
IIF(LEFT(@,1)IN('',@g),1,0)x,ROUND(RAND(),0)y)z
PRINT @A+'
'+@s+'
'+REPLACE(@A,'+','=')IF @>''goto a

Provalo online

Ungolfed:

DECLARE @r int=10, -- racers
        @g char=2  -- goal

DECLARE @ varchar(99)=REPLICATE('0',@r)
a:
PRINT @
DECLARE @A varchar(99)='',@s varchar(99)='',@i int=0

WHILE @i<@r
  SELECT
    @i+=1,
    @A+=char(43-x*11),
    @s+=IIF(x=1,' ',LEFT(y,1)),
    @=RIGHT(@,@r-1)+IIF(x=1,' ',REPLACE(LEFT(@,1)+y,@g+1,' '))
  FROM(SELECT IIF(LEFT(@,1)IN('',@g),1,0)x,ROUND(RAND(),0)y)z

PRINT @A+'
'+@s+'
'+REPLACE(@A,'+','=')

IF @>''GOTO a

Si noti che il seme casuale sul sito di test sarà sempre lo stesso, dando lo stesso risultato ogni volta, nella gestione dello studio darà risultati diversi. Può usare valori diversi per i corridori e l'obiettivo per ottenere un'immagine diversa


1

Python 3, 237 byte

from random import*
def f(n,t):
 x='0'*n,;i=j=0;y=''
 while' '*n!=x[i]:
  if j==n:j=0;x+=y,;y='';print(x[i]);i+=1
  y+=' 'if x[i][j]in(' ',str(t))else eval(["'+'","str(randint(0,1))","'='","str(int(x[i-3][j])+int(x[i-1][j]))"][i%4]);j+=1

Una funzione che accetta input tramite argomento e stampa su STDOUT. Questo approccio sfrutta il fatto che l'output segue un ciclo del periodo quattro, della forma "+ valore = valore", per tutti i corridori. Usando un contatore modulo quattro, un elenco contenente il valore desiderato per ogni passaggio come una stringa può essere indicizzato in, e il risultato valutato usando la funzione di valutazione di Python.

Come funziona

from random import*                       Import Python's random module to access the
                                          randint function
def f(n,t):                               Function with input number of racers n and target
                                          number t
x='0'*n,;i=j=0;y=''                       Initialise return tuple storage x, state number
                                          i, racer number j and append string y for x
while' '*n!=x[i]:                         Loop through all j for some i. If the current
                                          state consists only of spaces, all racers have
                                          finished, so stop
y+=...eval([...][i%4])...                 Index into list, using i mod 4, to find the
                                          desired process for the cycle step, and append to
                                          y
(If first step of cycle)
...+...                                   Plus sign
(If second step of cycle)
...str(randint(0,1))...                   Random number from (0,1)
(If third step of cycle)
...=...                                   Equals sign
(If fourth step of cycle)
...str(int(x[i-3][j])+int(x[i-1][j]))...  Addition of random number to previous racer
                                          'score'
...' 'if x[i][j]in(' ',str(t))...         But append space if the racer has previously
                                          finished, or has reached the target
...j+=1                                   Increment j
if j==n:j=0;x+=y,;y='';print(x[i]);i+=1   If j=n, all j must have been looped through.
                                          Reset j, append new state y to x, reset y, print
                                          current state to STDOUT and increment i. When
                                          this first executes, x contains only the initial
                                          state, meaning that this is printed and the cycle
                                          starts with the second state.

Provalo su Ideone


1

Python 2 , 191 byte

from random import*
def c(p,w,r=[],l=0):
 while p:
	p-=1;s='0'
	while`w`>s[-1]:s+="+%s="%randint(0,1);s+=`eval(s[-4:-1])`;l+=2
	r+=[s]
 for z in map("".join,zip(*(t+l*' 'for t in r))):print z

Provalo online!


Python 3 , 200 byte

from random import*
def c(p,w,r=[],l=0):
 while p:
  p-=1;s='0'
  while str(w)>s[-1]:s+="+%s"%randint(0,1);s+="=%s"%eval(s[-3:]);l+=2
  r+=[s]
 for z in map("".join,zip(*(t+l*' 'for t in r))):print(z)

Provalo online!


0

Python 2, 278 byte

import random
r=5
w=2
s=(0,)*r
while s.count(w)<len(s):
    print ''.join(map(lambda a:str(a),s))+"\n"+'+'*len(s)
    s = tuple(map(lambda x: x<w and x+random.randrange(2) or x,s))
    print ''.join(map(lambda a:str(a), s))+"\n"+'='*len(s)
    s = tuple([x for x in s if x!= w])

dove r è il no. di corridori e w è il punteggio da vincere

Provalo qui!


2
Ho testato il tuo programma, non mostra il risultato come descritto nella domanda, tutto è stato spostato a sinistra.
t-clausen.dk,

0

Perl 5 , 150 byte

$,=$";say@n=(0)x(@e=('=')x(@p=('+')x<>));$t=<>;while(grep$_<$t,@n){@r=map{$_+=($g=0|rand 2);$g}@n;for$l(p,r,e,n){say map{$n[$_]>$t?$":$$l[$_]}0..$#n}}

Provalo online!

Il primo input è il numero di corridori, il secondo è il punteggio necessario.

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.