Quando lampeggiano le luci?


10

Immagina di avere due luci. Queste spie si accendono e si spengono a una velocità specifica:

Light 0: Delay 0ms and then blink every 1000ms
Light 1: Delay 500ms and then blink every 1000ms

Simuliamo queste luci per i primi 2000ms:

0ms:    Light 0 on
500ms:  Light 1 on
1000ms: Light 0 off
1500ms: Light 1 off
2000ms: Light 0 on

La sfida

Dato un elenco di coppie ordinate che rappresentano i tempi per le luci, scrivere un programma o una funzione per emettere la sequenza per quando lampeggiano.

Ingresso

L'input dovrebbe essere nel seguente formato:

TimeToSimulate
Light0Delay,Light0Period
Light1Delay,Light1Period
...

In questo formato, l'esempio sopra sarebbe:

2000
0,1000
500,1000

Produzione

L'output dovrebbe essere una serie di triple ordinate:

Time,LightNum,LightStatus

LightStatus è un valore vero se la luce si accende e un valore falso se la luce si spegne.

L'output dell'esempio precedente sarebbe:

0,0,True
500,1,True
1000,0,False
1500,1,False
2000,0,True

Se due spie lampeggiano contemporaneamente, la luce con il numero inferiore dovrebbe essere visualizzata per prima nell'output.

Altre cose

  • I formati di input e output non sono rigorosi
  • Il codice non dovrebbe produrre errori
  • La soluzione non dovrebbe fare affidamento sulle condizioni di gara
  • Nessuna scappatoia standard
  • Questo è , quindi vince la soluzione più breve!

Casi test

Input:

2000
0,1000
500,1000

Output:

0,0,True
500,1,True
1000,0,False
1500,1,False
2000,0,True

----

Input:

2
0,1
0,1

Output:

0,0,True
0,1,True
1,0,False
1,1,False
2,0,True
2,1,True

----

Input:

500
100,50
200,100
300,150

Output:

100,0,True
150,0,False
200,0,True
200,1,True
250,0,False
300,0,True
300,1,False
300,2,True
350,0,False
400,0,True
400,1,True
450,0,False
450,2,False
500,0,True
500,1,False

----

Input:

1000
23,345
65,98
912,12
43,365

Output:

23,0,True
43,3,True
65,1,True
163,1,False
261,1,True
359,1,False
368,0,False
408,3,False
457,1,True
555,1,False
653,1,True
713,0,True
751,1,False
773,3,True
849,1,True
912,2,True
924,2,False
936,2,True
947,1,False
948,2,False
960,2,True
972,2,False
984,2,True
996,2,False

Snippet della classifica:


Quanta produzione è sufficiente?
aschepler

@aschepler Cosa intendi? L'input specifica un periodo di tempo per "simulare"
Daniel M.

Risposte:


3

JavaScript, 98 97 byte

a=>b=>[...Array(a+1)].map((_,i)=>b.map((d,j)=>d[0]--||c.push([i,j,d[d[0]=d[1]-1,2]^=1])),c=[])&&c

Provalo online

Salvataggio di un byte grazie a Shaggy : utilizzare la sintassi di input del curry.


Salvare un byte con accattivarsi: a=>b=>.
Shaggy

@Shaggy. Sei così veloce, stavo preparando una modifica.

Regola empirica: se ci sono 2 ingressi, curry sempre!
Shaggy


2

Gelatina ,  26  25 byte

Ḣrm⁸ð€µ;€€"J;"J$€€ẎẎḂ0¦€Ṣ

Un collegamento diadico che prende un elenco di elenchi di delay, periodnumeri e un numero di intervallo di tempo e restituisce un elenco di time, light, actionnumeri interi.

Le luci sono 1-indicizzate e 0rappresentano l'azione "off", mentre 1rappresenta l'azione "on".

Provalo online!

Come?

Ḣrm⁸ð€µ;€€"J;"J$€€ẎẎḂ0¦€Ṣ - Link: [[delay, period],...], time-frame 
    ð€                    - for €ach [delay, period]:
Ḣ                         -   head (get the delay and modify the item to [period])
 r                        -   inclusive range to time-frame = [delay,delay+1,...,time-frame]
   ⁸                      -   chain's left argument = [period]
  m                       -   modulo slice = [delay, delay+period, delay+2*period, ...]
      µ                   - monadic chain separation, call that v
           J              - range(length(v)) = [1,2,...,nLights]
          "               - zip with:
       ;€€                -   concatenate for €ach for €ach (add light indexes to times)
               $€€        - last two links as a monad for €ach for €ach:
              J           -   range (length(switch-times-for-a-light))
             "            -   zip with:
            ;             -     concatenation (i.e. append a 1-based index)
                  ẎẎ      - tighten & tighten again (flatten by 2 to a list of triples)
                      |€  - sparse application of (for €ach):
                     0    - ...to indexes: 0 (=last entry)
                    Ḃ     - ...action: modulo by 2 (even appended indexes ->0s; odds -> 1s)
                        Ṣ - sort the resulting list of triples

2

Python 2 , 206 214 byte

  • Aggiunti otto byte per conformarsi alle regole (prendendo input tramite stdin).
Q=input();D,T=Q[0],[map(int,q.split(","))for q in Q[1:]];O,l=[],len(T)
for j in range(l):
	t,b=T[j][0],9>8
	while t<=int(D):O+="%0*d,%0*d,%s"%(len(D),t,len(str(l)),j,b),;b=not b;t+=T[j][1]
print"\n".join(sorted(O))

Provalo online!

Questo codice genera un elenco non ordinato contenente i tempi di commutazione di ciascuna luce, inserisce quei tempi e l'identificatore della luce, ordina tale elenco e lo emette.


In base alle regole standard devi prendere input che non puoi aspettarti che preesistano in una variabile. Probabilmente troverete che l'utilizzo input()vi permetterà di tagliare loro byte-count down troppo (senza parsing della stringa sarà richiesto dal Python 2 di input()si eval(raw_input())) :).
Jonathan Allan il

... anche se usi numeri piuttosto che stringhe, Oli ordineranno, il che probabilmente taglierebbe anche il conteggio dei byte,
Jonathan Allan

@JonathanAllan Grazie per aver notato la discrepanza della regola; Non includerò i tuoi suggerimenti in quanto esiste ormai una risposta Python 2 significativamente più breve.
Jonathan Frech,

1

Perl 5 , 106 + 1 (-n) = 107 byte

($a[$i],$b[$i++])=eval for<>;for$i(0..$_){for(0..$#a){$a[$_]+=$b[$_],say"$i,$_,".($s[$_]^=1)if$i==$a[$_]}}

Provalo online!


1

Haskell, 121 byte

import Data.List
t!l=sort$(zip[0..]l)>>=takeWhile(\(a,_,_)->a<=t).(\(i,(d,w))->iterate(\(t,i,s)->(t+w,i,not s))(d,i,2>1))

Provalo online.

Questo è il programma da cui ho iniziato:

import Data.List

type LightId = Int
type Time = Int
type State = Bool
type LightEvent = (Time, LightId, State)

lightSimulation :: Time -> Time -> [(Time, State)]
lightSimulation delay interval = iterate step (delay, True)
  where step (time, state) = (time+interval, not state)

addId :: LightId -> (Time, State) -> LightEvent
addId id (t, s) = (t, id, s)

simulate :: Time -> [(Time, Time)] -> [LightEvent]
simulate timeLimit lights = sort $ concatMap lightSim (zip [0..] lights)
  where withinTimeLimit = ((<=timeLimit) . fst)
        lightSims (id, (delay, interval)) = map (addId id) $ takeWhile withinTimeLimit (lightSimulation delay interval)

E prima del golf finale l'ho abbreviato in:

import Data.List

light (id,(delay,interval)) = iterate step (delay, id, True)
  where step (time, id, state) = (time+interval, id, not state)

simulate timeLimit lights = sort $ concatMap lightSims (zip [0..] lights)
  where lightSims l = takeWhile(\(a,b,c)->a<=timeLimit)$light l

1

Röda , 105 87 85 byte

{|t|enum|[([_+_]*(t-_1[0]+1))()|enum|(_+_)]|{[[_+_4,_3,_4//_2%2=0]]if[_4%_2=0]}|sort}

Provalo online!

Spiegazione:

{|t| /* Declare a lambda with one parameter */
/* The input stream contains arrays */
enum| /* For each array in the input, push an ascending number after it */
/* [1] (for stream content in this point, see below) */
[ /* For each array-number pair in the stream: */
    (
        [_+_] /* Create a copy of the array with the number as the last element */
        *(t-_1[0]+1) /* Create copies of the array for every ms simulated */
    )()| /* Push all copies to the stream */
    enum| /* After each copy, push an ascending number to the stream */
    (_+_) /* Append the number to each array before */
]|
/* [2] (for stream content in this point, see below) */
{
    /* Push an on or off event to the stream: */
    [[
        _+_4,      /* delay + time = actual time */
        _3,        /* light-id */
        _4//_2%2=0 /* does the light go on or off? */
    ]] 
    if[_4%_2=0] /* if the light goes on or off (time%period=0) */
}|
/* [3] (for stream content in this point, see below) */
sort /* Sort the events */
}

Lo stream contiene i [1]valori dei punti nel seguente ordine:

[delay, period], light-id
 _1[0]  _1[1]    _2

Lo stream contiene i [2]valori dei punti nel seguente ordine:

delay, period, light-id, time
_1     _2      _3        _4

Lo stream contiene [3]array di punti con la seguente struttura:

[time, light-id, on_or_off]
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.