실신 찾기


33

q4 분 음표를 e나타내는 s 와 8 분 음표를 나타내는 s 로 구성된 문자열 입력이 주어지면, 동기화 된 4 분 음표의 색인을 출력하십시오.

Syncopation 은 복잡하지만이 과제의 목적 상 "syncopated"에 대한 정의는 매우 간단합니다. "오프 비트"에서 시작하는 1/4 음표, 즉 n / 4에서 "and"로 카운트 된 비트 시각.

이것은 홀수의 여덟 번째 음표가 앞에 오는 임의의 1/4 음표로 정의 될 수도 있습니다. 예를 들어, *아래 표시된 메모 는 실신으로 간주되며 해당 인덱스도 표시됩니다.

eqqeqqeqqe
 **    **
 12    78
Output: 1 2 7 8

입력은 항상 4/4 시간의 전체 측정 단위로 구성됩니다 (4 분 음표는 측정 값의 1/4이고 8 분 음표는 측정 값의 8 분의 1입니다). (입력도 비어 있지 않습니다.) 출력은 숫자가 포함되지 않은 구분 기호로 구분 된 요소 또는 배열 / 목록 / 등이 포함 된 단일 문자열 일 수 있습니다. 원하는 경우 출력은 1을 기준으로 할 수 있습니다 (예 : 첫 번째 인덱스는 0 대신 1이 됨). 또한 숫자 기반 (단항, 소수 등) 일 수도 있습니다.

이것이 이므로 바이트 단위의 가장 짧은 코드가 이깁니다.

테스트 사례 :

In                        Out
-----------------------------------------------
eqqqe                     1 2 3
qeqeq                     2
qqqeqqeeeeqeqeqeqqeqqeqq  4 5 10 14 19 20
eeeeeqeeqeeqqqqeqeqeeqe   5 8 11 12 13 14 18 21
qqqq                      <none>
eeeeeeee                  <none>

1
출력은 1 기반 일 수 있습니까?
— Luis Mendo

1
인덱스가 어떻게 작동하는지 보여주기 위해 예제를 만들 수 있습니까?
— 피터 테일러

1
코드가 짧아지면 @LuisMendo 물론입니다.
— Doorknob

@PeterTaylor 좋아요, 당신이 생각한 것과 같은 것입니까?
— Doorknob

입력 값이 따옴표를 포함하는 문자열 일 수 있습니까? 'eqqqe'대신eqqqe
— Luis Mendo

답변:


12

젤리 , 12 9 바이트

=“e”µ<^\O

프로그램으로서, 위의 코드는 입력 주위에 따옴표가 필요합니다. 이것이 허용되지 않기 때문에 이것은 기능 제출입니다. 출력은 1 기반입니다. 온라인으로 사용해보십시오!

작동 원리

=“e”µ<^\O    Monadic link. Argument: s (string)

=“e”         Check each character for equality with 'e'. Yields a Boolean array.
    µ        Start a new, monadic chain.
      ^\     Compute the array of partial reductions by XOR, i. e., the parities
             of all prefixes of the Boolean array.
     <       Check if the Booleans are strictly smaller than the parities.
             A truthy outcome indicates an off-beat quarter note.
        O    Yield all indices of 1's.

최신 정보

최신 버전의 Jelly에서는 위의 코드가 더 이상 작동하지 않습니다. 문자 e 가 필요하기 때문입니다. 하지만 “e”문자열을 생성하기 때문입니다. 총 8 바이트 동안 바이트를 저장하는 수정 .

=”eµ<^\O

이것은 전체 프로그램으로 작동합니다. 온라인으로 사용해보십시오!


7

루비, 46

i=e=0
gets.bytes{|n|e^=n
e&4|n>114&&p(i)
i+=1}

stdin에 입력하십시오. 줄 바꿈으로 구분하여 stdout으로 출력합니다.

댓글

i=e=0               #i keeps index, e keeps track of 8ths.
gets.bytes{|n|      #iterate through bytes in the input
e^=n                #xor e with input. We're interested in the 4's bit, which is only affected by ascii e, not ascii q
e&4|n>114&&p(i)     #e&4 evaluates to 4 or 0. OR with n and if the value is greater than ascii code for q, print index
i+=1}               #increment index

6

자바 스크립트 ES7, 50 48 바이트

당신이 저에게 묻는다면 JS를 위해 아주 짧습니다. [for...of]기본적으로 맵과 필터가 결합 된 구문은이 문제에 유용합니다.

s=>[for(c of(i=f=0,s))if(++i&&c>'e'?f%2:f++&0)i]

1 인덱스 배열을 출력하는 익명 함수를 정의합니다.

테스트 스 니펫

이것은 ungolfed, es7'd 버전의 코드를 사용합니다.

a = function(s) {   // Create a function a that takes in a parameter s and does these things:
  var r = [],       // Set variable r to an empty array,
  i = 0, f = 0;     // i to 0, and f to 0.
  for(c of s) {     // For each character c in s:
    i++;            //  Increment i by 1.
    if(             //  If
      c == 'q' ?    //   if c == 'q',
      f%2 === 1 :   //    f is even; otherwise,
      f++ && false) //    increment f and don't execute this:
      r.push(i);    //   Add i to the end of r.
  } return r;       // Return r.
}
<input type="text" value="eqqqe" id=O />
<button onclick="P.innerHTML='['+a(O.value)+']'">Try it</button>
<p id=P />


3
아주 좋은 설명입니다! ES7의 새로운 [For ... of] 👍
— Aᴄʜᴇʀᴏɴғᴀɪʟ

그렇다면 "ECMAScript 7의 골프 팁"이라는 새로운 질문이 필요합니까?
— Neil

@Neil ES6 게시물을 ES6 / 7로 업데이트하려고했지만 OP가 편집을 롤백했습니다. 한편, codegolf.stackexchange.com/a/61489/42545
— ETHproductions

5

J, 20 19 17 바이트

=&'e'(I.@:<~:/\@)

바이트를 저장 한 randomra와 2를 저장 한 Dennis에게 감사합니다. 이것은 다음과 같이 사용되는 명명되지 않은 monadic 동사입니다.

  f =: =&'e'(I.@:<~:/\@)
  f 'eqqqe'
1 2 3

여기에서 시도하십시오.

설명

=&'e'(I.@:<~:/\@)
=&'e'               Replace every 'e' with 1, other chars with 0
     (         @)   Apply the verb in parentheses to the resulting 0-1 vector
           ~:/\     Cumulative reduce with XOR (parity of 'e'-chars to the left)
          <         Element-wise less-than with original vector
      I.@:          Positions of 1s in that vector

5

GNU grep, 3 + 17 = 20 3 + 15 = 18 바이트

이 프로그램에는 옵션이 필요합니다 boP. 코드는

q(?!(q|eq*e)*$)

로 저장 synco한 다음로 실행 하십시오 grep -boPf synco.

출력 구분 기호 :q뒤에 줄 바꿈이옵니다. 의 출력 예 eqqqeIS를

1:q
2:q
3:q

플래그의 의미는 다음과 같습니다.

  • P: PCRE 정규식을 사용하십시오.
  • o: 이것은 정규 표현식과 일치하는 줄의 일부만 인쇄하는 것을 의미하지만 이것이 중요한 이유는 아닙니다. o한 줄에 여러 개의 일치 항목을 허용하는 효과가 있으므로 사용됩니다.
  • b: 파일의 시작부터 각 일치의 시작에 대한 오프셋을 바이트 단위로 인쇄합니다.

패턴은 4 분 음표 뒤에 짝수 번째 8 음표가 없는지 확인합니다.


않는 grep그 자체의 언어로 자격? 그럼에도 불구하고 훌륭한 답변
— Digital Trauma

@DigitalTrauma 왜 그런지 모르겠습니다 ... PCRE 정규식을 사용할 수 있으므로 적어도 Turing-complete이어야하며 여기에 표시된 것처럼 파일에서 코드를 실행할 수 있습니다.
— feersum

I이었다 인상을 PCRE가 완료 튜링이 입증되지 않았는지 확인합니다. 어쨌든 귀하의 표현은 요구 사항을 충족하므로 괜찮습니다. 그러나 이론적 근거에 불만이있는 다른 사람들도있을 수 있습니다.
— Digital Trauma

@DigitalTrauma Huh, Turing-completeness에 대해 자랑스러워 한 것 같습니다.
— feersum

5

MATL , 12 14 16 바이트

j101=tYs2\<f

2 바이트를 제거하고 멋진 온라인 플랫폼에서 MATL을 호스팅 해 준 Dennis에게 감사합니다.

이 사용하는 최신 버전 (9.3.0) 언어 / 컴파일러를.

입력 및 출력은 stdin 및 stdout을 통해 이루어집니다. 결과는 1을 기준으로합니다.

예 :

>> matl j101=tYs2\<f
> eeeeeqeeqeeqqqqeqeqeeqe
6  9 12 13 14 15 19 22

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

설명

j             % input string
101=          % vector that equals 1 at 'e' characters and 0 otherwise
t             % duplicate
Ys2\          % cumulative sum modulo 2
<             % detect where first vector is 0 and second is 1
f             % find (1-based) indices of nonzero values

3

파이썬 2, 94 85 79 75 66 바이트

편집 : Thanks Doorknob과 Alex A.

편집 : 감사합니다 Alex A.

편집 : 이제 input ()을 사용하므로 입력은 따옴표가있는 문자열이어야합니다.

편집 : 열거 형을 사용하도록 권장 해 주셔서 감사합니다 Zgarb.

단순히 e의 수를 세고 q이면 e가 홀수인지 확인한 다음 색인을 인쇄하십시오.

e=0
for j,k in enumerate(input()):
 if"q">k:e+=1
 elif e%2:print j

여기 사용해보십시오


두 번째 바이트는 8 바이트를 절약하기 위해 if ...그냥로 대체 할 수 있습니다 else.
— Doorknob

print1 바이트 이후의 공백을 제거 할 수도 있습니다
— Alex A.

난 당신이를 변경할 수 있다고 생각 else: if e%2:단지에 elif e%2:.
— Alex A.

i[j]<"q"대신 확인하여 하나 이상의 바이트를 저장할 수 있습니다 i[j]=="e".
— Alex A.

2
@TanMath Doorknob에게 따옴표로 입력을하기 위해 2 바이트를 절약 할 수 있기 때문에 물었습니다. 그러나 그것은 불가능하다
— Luis Mendo

3

하스켈, 58 51 바이트

f x=[i|(i,'q')<-zip[0..]x,odd$sum[1|'e'<-take i x]]

사용 예 : f "eeeeeqeeqeeqqqqeqeqeeqe"-> [5,8,11,12,13,14,18,21].

홀수의 경우 목록을 살펴보고 i모든 문자에 대한 현재 색인 을 출력하십시오.'q''e' .


2

Minkolang 0.15 , 28 바이트

(o"q"=7&z1+$z8!z2%,2&iN$I$).

여기에서 시도하십시오.

설명

(                        Open while loop
 o                       Read in character from input
  "q"                    Push the character "q"
     =                   1 if the top two items on stack are equal, 0 otherwise
      7&                 Pop and jump 7 spaces if truthy

        z                Push register value on stack
         1+              Add one
           $z            Pop top of stack and store in register
             8!          Jump eight spaces

        z                Push register value on stack
         2%              Modulo by 2
           ,             boolean not
            2&           Pop and jump two spaces if truthy
              i          Push loop counter
               N         Output as number

                $I       Push length of input
                  $).    Close while loop when top of stack is 0 and stop.

2

C (기능), 65

추가 골프를위한 @Dennis에 감사합니다!

i,n;f(char*m){for(i=n=0;*m;i++)*m++&4?++n:n%2?printf("%d ",i):0;}

1
나는 i,n;f(char*m){for(i=n=0;*m;m++,i++)*m&4?++n:n%2?printf("%d ",i):0;}작동해야 한다고 생각 합니다.
— Dennis

2

파이썬 3, 109 95 80 90 88 76 68 67 66 64 바이트

카운트 수 q의 및 es와 현재의 인덱스를 추가하는 q경우 앞의 수e 의 홀수이다.

편집 : 이제 s의 색인 목록과 그 앞에 q홀수 의 s 색인을 인쇄 e합니다. 8 바이트는 덕분에 저장된 손잡이 하고 두 개 더 감사 feersum을 .

lambda s:[x for x,m in enumerate(s)if("e"<m)*s[:x].count("e")%2]

언 골프 드 :

def f(s):
    c = []
    for index, item in enumerate(s):
        if item == "q":
            if s[:index].count("e")%2 == 1:
                c.append(index)
    return c

1
inputand print문을 불필요하게 만들기 위해 이것을 람다로 만들 수 없습니까?
— Doorknob

enumerate보다 사용하는 것이 더 짧아야합니다 range(len(....
— feersum

2

자바 스크립트 ES6, 63 60 58 바이트

x=>[...x].map((e,i)=>e>'e'?n%2&&a.push(i):n++,a=[],n=0)&&a

배열을 출력하는 익명 함수 2 바이트를 절약 한 user81655에게 감사합니다. 더 나은 지원 구문을 사용하는 ungolfed 버전은 다음과 같습니다.

f=function(x) {
  a=[] // Indeces of syncopated notes
  n=0 // Number of e's encountered so far
  x.split('').map(function(e,i) { // For each letter...
    e>'e'? // If the letter is q...
      n%2&& // ...and the number of e's is odd...
        a.push(i): // ...add the current index to the array
      n++ // Otherwise, it is e so increment the counter
  })
  return a
}

run=function(){document.getElementById('output').textContent=f(document.getElementById('input').value)};document.getElementById('run').onclick=run;run()
<input type="text" id="input" value="qqqeqqeeeeqeqeqeqqeqqeqq" /><button id="run">Run</button><br />
<samp id="output"></samp>


0

수학, 76 바이트

Flatten[Range[#+1,#2-1]&@@@StringPosition[#,"e"~~"q"..~~"e",Overlaps->1<0]]&

내가 흥미로운 것을 발견했다. syncopated 부분은 모두 형태 eqqq..qqe이므로, 나는 그것들을 감지하고 qs 의 색인을 제공합니다 .


0

apt, 29 23 21 바이트

더 이상 경쟁하지 않습니다!

0+U ¬®¥'e} å^ ä© m© f

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

작동 원리

         // Implicit: U = input string, e.g.    "eqqeqeq"
0+U      // Add a 0 to the beginning.           "0eqqeqeq"
¬        // Split into chars.                   ['0,'e,'q,'q,'e,'q,'e,'q]
®¥'e}    // Map each item X to (X == 'e).       [F, T, F, F, T, F, T, F]
å^       // Cumulative reduce by XOR'ing.       [0, 1, 1, 1, 0, 0, 1, 1]
ä©       // Map each consecutive pair with &&.  [0, 1, 1, 0, 0, 0, 1]
m©       // Map each item with &&. This performs (item && index):
         //                                     [0, 1, 2, 0, 0, 0, 6]
f        // Filter out the falsy items.         [   1, 2,          6]
         // Implicit output                     [1,2,6]

비경쟁 버전, 18 바이트

U¬m¥'e å^ ä©0 m© f

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


0

펀칭, 43 바이트

:~:0\`#@_5%2/:99p1++\>2%#<9#\9#.g#:*#\_\1+\

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

설명

스택에서 두 개의 암시 적 0 (음표 번호 및 비트 수)으로 시작합니다.

:               Make a duplicate of the beat count.
~               Read a character from stdin.
:0\`#@_         Exit if it's less than zero (i.e. end-of-file).
5%2/            Take the ASCII value mod 5, div 2, translating q to 1 and e to 0.
:99p            Save a copy in memory for later use.
1+              Add 1, so q maps to 2 and e to 1.
+               Then add that number to our beat count.
\               Get the original beat count that we duplicated at the start.
2%              Mod 2 to check if it's an off-beat.
99g*            Multiply with the previously saved note number (1 for q, 0 for e).
_               Essentially testing if it's a quarter note on an off-beat.
       \.:\     If true, we go turn back left, get the beat count, and output it.
         >2     Then push 2 onto the stack, and turn right again.
2%              That 2 modulo 2 is just zero.
99g*            Then multiplied by the saved note number is still zero.
_               And thus we branch right on the second pass.
\1+\            Finally we increment the note number and wrap around to the start again.
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.