Stampa la lunghezza totale di tutti i caratteri "tra virgolette"


12

Regole

In questa sfida, ridefinirò un po 'la definizione di "virgolette".

  • Le virgolette ( virgolette AKA ) sono qualsiasi carattere identico utilizzato in coppia in vari sistemi di scrittura per attivare la parola diretta, una citazione o una frase. La coppia è composta da virgolette di apertura e virgolette di chiusura, che ha lo stesso carattere (distinzione tra maiuscole e minuscole).

  • Se ci sono coppie di virgolette sovrapposte,

    • Se una coppia nidifica un'altra, entrambe le coppie sono ancora valide.
    • Se una coppia non nidifica un'altra, la prima coppia iniziale rimane valida. L'altro non è più considerato come una coppia.
  • Quando si contano i caratteri tra virgolette (lunghezza di una coppia di virgolette),

    • Le citazioni stesse non contano.
    • La lunghezza di ogni coppia viene conteggiata in modo indipendente. La sovrapposizione non influisce su un altro.

Obbiettivo

Il tuo obiettivo è stampare la lunghezza totale di tutte le citazioni valide. Questo è il codice golf, quindi vince il codice con il minor numero di byte.

Esempi

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 Ho corretto le regole in modo che fossero più simili alle citazioni effettive. Penso che sia quello che ti aspettavi. Puoi rivedere questo?
user2652379

1
sembra buono! Grazie per aver ascoltato il mio feedback.
Nick Kennedy,

Risposte:



4

APL (Dyalog Unicode) , 36 byte SBCS

Programma completo. Richiede input da stdin.

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

Provalo online!

t←⍬ impostare un accumulatore t(per t otale)

⍞⊣ scartalo a favore dell'input di stringa da stdin (simbolo: citazione nella console)

{... }⍣≡ applica il seguente lambda anonimo fino a stabile (punto fisso; precedente ≡ successivo)

⊢⍵ sull'argomento

 ... ⎕S'\2' PCRE S earch per il seguente, gruppo 2 di ritorno per ogni partita:

  (.) qualsiasi personaggio (chiameremo questo gruppo 1) il
  (.*?) minor numero possibile di personaggi (chiameremo questo gruppo 2)
  \1 il personaggio del gruppo 1

t,← aggiorna taggiungendo quello al tvalore corrente

t⊣ scartare quello (l'elenco finale di nessuna corrispondenza) a favore di t

 contare il numero di caratteri in quello


2

Rubino , 49 byte

Soluzione ricorsiva. Trova gruppi di preventivi, conta le loro lunghezze, quindi cerca ricorsivamente le lunghezze dei sottogruppi e somma tutto insieme.

f=->s{s.scan(/(.)(.*?)\1/).sum{|a,b|b.size+f[b]}}

Provalo online!


1

JavaScript (ES6), 64 byte

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

Provalo online!

Commentate

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

JavaScript (Node.js) , 65 64 62 byte

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

Provalo online!

Approccio originale (64 byte):

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

Provalo online!

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 byte

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

Provalo online!

Commentate

# 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.)
}{}})

1

Gelatina , 17 byte

œṡḢẈṖ$Ḣ+ɼṛƲ)Ẏ$F¿®

Provalo online!

Un programma completo che accetta un singolo argomento, la stringa di input racchiusa in un elenco e restituisce il numero di virgolette come numero intero.

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.