표시등이 언제 깜박입니까?


10

두 개의 조명이 있다고 상상해보십시오. 이 표시등은 특정 속도로 깜박입니다.

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

처음 2000ms 동안 이러한 조명을 시뮬레이트합시다 :

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

도전

조명의 타이밍을 나타내는 순서화 된 쌍의 목록이 주어지면 깜박이는 경우 시퀀스를 출력하는 프로그램이나 함수를 작성하십시오.

입력

입력은 다음 형식이어야합니다.

TimeToSimulate
Light0Delay,Light0Period
Light1Delay,Light1Period
...

이 형식에서 위의 예는 다음과 같습니다.

2000
0,1000
500,1000

산출

출력은 일련의 순서가 지정된 트리플이어야합니다.

Time,LightNum,LightStatus

LightStatus는 표시등이 켜지면 정확한 값이고, 표시등이 꺼지면 잘못된 값입니다.

위 예제의 결과는 다음과 같습니다.

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

두 개의 표시등이 동시에 깜박이면 번호가 낮은 표시등이 먼저 출력에 표시됩니다.

다른 것들

  • 입력 및 출력 형식이 엄격하지 않습니다
  • 코드에서 오류가 발생하지 않아야 함
  • 솔루션은 경쟁 조건에 의존해서는 안됩니다
  • 표준 허점 없음
  • 이것은 이므로 가장 짧은 솔루션이 승리합니다!

테스트 사례

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

리더 보드 스 니펫 :


얼마나 많은 출력이 충분합니까?
aschepler

@aschepler 무슨 뜻인가요? 입력은 "시뮬레이션"할 시간을 지정합니다
Daniel M.

답변:


3

자바 스크립트, 98 97 바이트

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

온라인으로 사용해보십시오

Shaggy 덕분에 바이트를 절약했습니다 . 카레 입력 구문을 사용하십시오.


카레와 함께 바이트를 저장하십시오 a=>b=>.
Shaggy

@얽히고 설킨. 당신은 너무 빨리 편집을 준비하고있었습니다.

경험 법칙 : 입력이 2 개인 경우 항상 카레!
Shaggy


2

젤리 ,  26  25 바이트

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

delay, period숫자 목록과 시간 프레임 번호 목록을 time, light, action가져와 정수 목록을 반환하는 2 진 링크 .

조명은 1- 색인이며 0'꺼짐'동작을 1나타내는 반면 '켜짐'동작을 나타냅니다.

온라인으로 사용해보십시오!

어떻게?

Ḣ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

파이썬 (2) , 206 (214) 바이트

  • 규칙을 준수하기 위해 8 바이트를 추가했습니다 (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))

온라인으로 사용해보십시오!

이 코드는 각 조명의 전환 시간을 포함하는 비 순차 목록을 생성하고, 해당 시간과 조명 식별자를 채우고, 해당 목록을 정렬하여 출력합니다.


표준 규칙에 따라 입력을 가져와야 변수에 미리 존재할 수 없습니다. 당신은 아마 사용하는 것을 찾을 수 있습니다 input()당신은 그들이 바이트 계산도 줄일 수 있습니다 (어떤 문자열 구문 분석 이후 파이썬 2 개의 요구되지 않습니다 input()됩니다 eval(raw_input()):)).
Jonathan Allan

... 또한 문자열이 아닌 숫자를 사용하면 O정렬됩니다. 아마도 바이트 수를 줄일 수도 있습니다.
Jonathan Allan

@JonathanAllan 규칙 불일치에 주목 해 주셔서 감사합니다. 지금까지 Python 2 답변이 훨씬 짧아서 귀하의 제안을 통합하지 않을 것입니다.
Jonathan Frech


1

하스켈, 121 바이트

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))

온라인으로 사용해보십시오.

이것은 내가 시작한 프로그램입니다.

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)

그리고 마지막 골프 전에 나는 그것을 짧게 만들었다 :

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

로다 , 105 87 85 바이트

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

온라인으로 사용해보십시오!

설명:

{|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 */
}

스트림 [1]은 다음 순서 로 포인트 값을 포함합니다.

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

스트림 [2]은 다음 순서 로 포인트 값을 포함합니다.

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

스트림에는 [3]다음 구조의 포인트 배열이 포함됩니다 .

[time, light-id, on_or_off]
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.