인용 된 모든 문자의 총 길이를 인쇄하십시오.


13

규칙

이 과제에서는 "quotes"의 정의를 약간 재정의하겠습니다.

  • 따옴표 (AKA quotes )는 다양한 작문 시스템에서 한 쌍으로 사용되어 직접 음성, 인용 또는 문구를 설정 하는 동일한 문자 입니다. 쌍은 시작 인용 부호와 닫는 인용 부호로 구성되며, 동일한 문자 (대소 문자 구분)입니다.

  • 서로 겹치는 따옴표 쌍이 있으면

    • 한 쌍이 다른 쌍을 중첩하더라도 두 쌍 모두 여전히 유효합니다.
    • 쌍이 다른 쌍을 중첩하지 않으면 첫 번째 시작 쌍은 계속 유효합니다. 다른 하나는 더 이상 쌍으로 간주되지 않습니다.
  • 인용 문자 (따옴표 쌍의 길이)를 세는 경우

    • 따옴표 자체는 포함되지 않습니다.
    • 각 쌍의 길이는 독립적으로 계산됩니다. 겹치는 것은 다른 것에 영향을 미치지 않습니다.

당신의 목표는 유효한 모든 따옴표의 총 길이를 인쇄하는 것입니다. 이것은 코드 골프이므로 가장 적은 바이트를 가진 코드가 승리합니다.

Legend:
    <foo>: Valid quotes
    ^    : Cannot be paired character

Input   : ABCDDCBA
`A`  (6): <BCDDCB>
`B`  (4):  <CDDC>
`C`  (2):   <DD>
`D`  (0):    <>
Output  : 12

Input   : ABCDABCD
`A`  (3): <BCD>
`B`  (0):  ^   ^
`C`  (0):   ^   ^
`D`  (0):    ^   ^
Output  : 3

Input   : AABBBBAAAABA
`A`  (0): <>    <><> ^
`B`  (0):   <><>    ^
Output  : 0

Input   : ABCDE
Output  : 0

Input   : Print the total length of all "quoted" characters
`r` (40):  <int the total length of all "quoted" cha>
`n` (14):    <t the total le>
`t` (15):     < >   <o>       <h of all "quo>
` `  (7):      ^   <total>      <of>   ^        ^
`h`  (0):        ^             ^                  ^
`e`  (8):         < total l>                 ^          ^
`o`  (0):            ^           ^         ^
`a`  (0):              ^            ^              ^ ^
`l`  (0):               ^ ^          <>
`"`  (0):                               ^      ^
`c`  (0):                                        ^    ^
Output  : 84

Input   : Peter Piper picked a peck of pickled peppers
`P`  (5): <eter >
`e`  (9):  <t>     ^      <d a p>           <d p>  ^
`r`  (0):     ^     ^
` `  (3):      ^     ^      <a>    <of>       ^
`i`  (5):        <per p>
`p`  (3):         <er >        ^       ^       ^ <>
`c`  (8):               <ked a pe>       ^
`k`  (7):                ^        < of pic>
`d`  (0):                  ^                 ^
Output  : 40

Input   : https://www.youtube.com/watch?v=dQw4w9WgXcQ
`h` (27): <ttps://www.youtube.com/watc>
`t`  (0):  <>            ^          ^
`/`  (0):       <>               ^
`w` (14):         <><.youtube.com/>         <4>
`.`  (7):            <youtube>
`o`  (0):              ^       ^
`u`  (1):               <t>
`c`  (0):                     ^      ^             ^
`Q`  (8):                                  <w4w9WgXc>
Output  : 57

@NickKennedy 규칙을 실제 인용과 비슷하게 수정했습니다. 나는 이것이 당신이 기대 한 것이라고 생각합니다. 이것을 검토 할 수 있습니까?
user2652379 9

1
좋아 보인다! 의견을 보내 주셔서 감사합니다.
Nick Kennedy

답변:



4

APL (Dyalog Unicode) , 36 바이트 SBCS

전체 프로그램. stdin에서 입력하라는 메시지를 표시합니다.

≢∊t⊣{t,←'(.)(.*?)\1'S'\2'⊢⍵}⍣≡⍞⊣t←⍬

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

t←⍬ 어큐뮬레이터 설정 t(대 t otal)를

⍞⊣ stdin의 문자열 입력을 선호하여 버립니다 (기호 : 콘솔의 인용문)

{}⍣≡ 안정 될 때까지 다음 익명 람다를 적용하십시오 (수정 점; 이전 ≡ 다음)

⊢⍵ 논쟁에

 ... ⎕S'\2' PCRE S는 각 경기에 대한 그룹 2를 반환, 다음에 대한 earch :

  (.) 모든 문자 (이 그룹 1이라고 함)
  (.*?) 가능한 한 적은 문자 (이 그룹 2라고 함)
  \1 그룹 1 문자

t,←현재 값 t에 추가하여  업데이트t

t⊣ 찬성하여 (일치하지 않는 최종 목록)을 버립니다. t

 그 문자의 수를 센다



1

자바 스크립트 (ES6), 64 바이트

f=([c,...a],i=a.indexOf(c))=>c?(~i&&i+f(a.splice(0,i+1)))+f(a):0

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

댓글

f = (                       // f is a recursive function taking either the input string
                            // or an array of characters, split into
  [c, ...a],                // c = next character and a[] = all remaining characters
  i = a.indexOf(c)          // i = index of the 1st occurrence of c in a[] (-1 if not found)
) =>                        //
  c ?                       // if c is defined:
    ( ~i &&                 //   if i is not equal to -1:
      i +                   //     add i to the final result
      f(a.splice(0, i + 1)) //     remove the left part of a[] up to i (included) and
    )                       //     do a recursive call on it
    + f(a)                  //   add the result of a recursive call on a[]
  :                         // else:
    0                       //   stop recursion

1

자바 스크립트 (Node.js) , 65 64 62 바이트

f=s=>(s=/(.)(.*?)\1(.*)/.exec(s))?f(s[3])+f(s=s[2])+s.length:0

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

원래 접근 방식 (64 바이트) :

f=(s,r=/(.)(.*?)\1/g,t=r.exec(s))=>t?f(t=t[2])+t.length+f(s,r):0

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

f=s=>                              // Main function:
 (s=/(.)(.*?)\1(.*)/.exec(s))?     //  If a "quoted" segment can be found:
  f(s[3])                          //   Return the recursive result outside this segment,
  +f(s=s[2])                       //   plus the recursive result of this segment,
  +s.length                        //   plus the length of this segment
 :0                                //  If not: no quoted segment, return 0.

1

Brain-Flak , 100 바이트

({{<({}<>)<>(({<>(({}({})<>[({}<>)]))(){[{}()](<>)}{}}{}){(<>)})<>{}>{<>({}<<>({}<>)>)<>}<>[{}]}{}})

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

댓글

# Loop over each character in input and sum iterations:
({{

  # Evaluate matching quote search as zero
  <

    # Move opening "quote" to right stack
    ({}<>)<>

    # Until match or end of search string found:
    # Note that the character to search for is stored as the sum of the top two entries in the right stack.
    (

      ({

        <>((

          # Character to search for
          {}({})

          # Subtract and move next character
          <>[({}<>)]

        # Push difference twice
        ))

        # Add 1 to evaluation of this loop
        ()

        # If no match, cancel out both 1 and pushed difference to evaluate iteration as zero (keep one copy of difference for next iteration)
        # (compare to the standard "not" snippet, ((){[()](<{}>)}{}) )
        # Then move to other stack
        {[{}()](<>)}{}

        # If a match was found, this will instead pop a single zero and leave a zero to terminate the loop, evaluating this iteration as 0+1=1.

      # Push 1 if match found, 0 otherwise
      }{})

      # If match found, move to left stack and push 0 denote end of "quoted" area.
      {(<>)}

    # Push the same 1 or 0 as before
    )

    # Remove representation of opening "quote" searched for
    # The closing quote is *not* removed if there is a match, but this is not a problem because it will never match anything.
    <>{}

  >

  # Move searched text back to left stack, evaluating each iteration as either the 1 or 0 from before.
  # This counts characters enclosed in "quotes" if a match is found, and evaluates as 0 otherwise.
  {<>({}<<>({}<>)>)<>}

  # Remove 0/1 from stack; if 1, cancel out the 1 added by the closing "quote"
  <>[{}]

# Repeat until two consecutive zeroes show up, denoting the end of the stack.
# (Because closing quotes are not removed, it can be shown that all other zeroes are isolated on the stack.)
}{}})

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