È IL GIORNO DI BLOCCO DELLE CAPS


29

22 OTTOBRE È IL GIORNO DI BLOCCO INTERNAZIONALE DELLE CAPS ! Sfortunatamente, ALCUNI NON RICONOSCONO LA GLORIA DEL BLOCCO MAIUSCOLO DELLE CAPS. DICONO DI ESSERE "OVOSIOSI" O "COME GRIDARE" O ALCUNI SENSI. PER CONFORMARSI A QUESTI RECLAMI ILLOGICI E INANEO OVVOLOSAMENTE, PER FAVORE SCRIVIMI UN PROGRAMMA CHE TRASFORMA IL TESTO NORMALE IN TESTO "SENSIBILE" O "RAGIONABILE" PER FERMARE LE RECLAMI DELLE PERSONE.

Descrizione

L'input e l'output per la tua soluzione saranno entrambi stringhe che contengono solo caratteri ASCII stampabili.

La stringa di input conterrà zero o più sequenze di blocchi maiuscole . Una corsa di blocco maiuscole (o CLR in breve) è definita come la seguente:

  • Il CLR non deve contenere lettere minuscole ( a-z), ad eccezione del primo carattere di una parola .

    • Una parola , ai fini di questa sfida, è una sequenza di non spazi. Così, PPCG, correcthorsebatterystaple, e jkl#@_>00()@#__f-023\f[sono tutti considerati parola s.
  • Il CLR deve contenere anche almeno uno spazio; quindi, deve essere almeno due parole s.

  • Ciascuna delle parole s nel CLR deve contenere almeno due lettere ( A-Za-z).

    • Si noti che questo si riferisce al CLR preso da solo, senza caratteri circostanti che potrebbero non essere stati inclusi nel CLR. Ad esempio, non è un CLR perché la stringa da sola ha una parola s con meno di due lettere.foO BarO B

I CLR dovrebbero essere analizzati "avidamente", ovvero dovresti sempre trovare i CLR più lunghi possibili.

Dopo aver identificato tutti i CLR nella stringa di input, scambiare il caso di tutte le lettere all'interno dei CLR e generare la stringa risultante.

Casi test

Viene immessa la prima riga e viene emessa la seconda. Le parti in grassetto dell'input sono sottostringhe che sono considerate CLR.

CAPS LOCK IS THE BEST!
caps lock is the best!
I really LOVE pROGRAMMING pUZZLES AND cOde Golf!
I really love Programming Puzzles and Code Golf!
This is a challenge on PPCG. This is a test CASE. TEST
This is a challenge on PPCG. This is a test case. test
LorEM iPSUM DOLoR sIT amet, conSECTETur ADIPISciNG eLIT. MAECENAS iD orci
Lorem Ipsum doloR sIT amet, conSECTETur ADIPIScing Elit. maecenas Id orci
;'>}{/[]'"A*(389971(*(#$&B#@*(% c'>#{@D#$! :,>/;[e.[{$893F
;'>}{/[]'"a*(389971(*(#$&b#@*(% C'>#{@d#$! :,>/;[e.[{$893F
iT'S cAPS lOCK DAY!!! cELebraTE THis WONDERFUL key
It's Caps Lock day!!! Celebrate this WONDERFUL key
aBcDE fGHIj KLmNO pQrST (uVwXY) ZZ___Zz__Z
aBcde Fghij KLmno PqrST (uVwxy) zz___zz__Z
#aA# aA
#aA# aA

Regole

  • Si può presumere che l'input non conterrà mai due o più spazi in una riga e che non conterrà mai uno spazio iniziale o finale.

  • Bonus del 20% (moltiplicare la lunghezza del codice per .8) se l'intero codice è un CLR. ;) (principalmente solo per divertimento, dal momento che è improbabile che la presentazione vincente abbia questo bonus)

  • Questo è , quindi vince il codice più breve in byte.


16
Per favore, smetti di urlare.
TheDoctor,

4
Inoltre, per il caso di test n. 3, il PPCG maiuscolo non verrebbe mai messo in minuscolo? ( PPCG. Tcontiene uno spazio)
TheDoctor


2
@Dennis L'ho letto con la voce di Morty (da Rick e Morty), b / c sta parlando con "Rick".
mbomb007,

1
"punti bonus per il tuo codice essendo un CLR" mi fa venir voglia di farlo in LOLCODE ...
cat

Risposte:


4

CJam, 100 86 83 81 byte

Ml{_,),{1$<_S/(4$!>\1f>s+_eu=*S%_{'[,_el^:Af&s,2<},!*1>},_{W=/(AA26m>er}{;(}?\s}h

Prova questo violino nell'interprete CJam o verifica tutti i casi di test contemporaneamente .

Algoritmo

  1. Identifica il CLR più lungo possibile che inizia con il primo carattere.

  2. Se esiste, scambia la custodia, stampala e rimuovila dall'inizio della stringa.

    Altrimenti, rimuovi un singolo carattere dall'inizio della stringa e stampalo senza modifiche.

  3. Se sono rimasti più caratteri, tornare al passaggio 1.

Come funziona

Ml         e# Push an empty string and a line from STDIN.
{          e# Do:
  _,       e#   Copy the string on the stack and compute its length (L).
  ),       e#   Push [0 ... L].
  {        e#   Filter; for each integer I in that array:
    1$<    e#     Copy the string and keep its first I characters.
    _S/    e#     Push a copy and split at spaces.
    (      e#     Shift out the first word.
    4$!    e#     Push the logical NOT of the fifth topmost item of the stack.
           e#     This pushes 1 for the empty string on the bottom, and 0
           e#     for non-empty strings and printable characters.
    >      e#     Remove that many characters from the beginning of the first word.
           e#     This will remove the first character iff the string on the
           e#     stack is the entire input. This is to account for the fact that
           e#     the first word is not preceded by a space.
    \1f>   e#     Remove the first character of all remaining words.
    s+     e#     Concatenate all of them.
    _eu=   e#     Convert a copy to uppercase and check for equality.
    *      e#     Repeat the I characters 1 or 0 times.
    S%_    e#     Split at runs of spaces, and push a copy.
    {      e#     Filter; for each non-empty word:
      '[,  e#       Push the string of all ASCII characters up to 'Z'.
      _el  e#       Push a copy and convert to lowercase.
      ^    e#       Perform symmetric difference, pushing all letters (both cases).
      :A   e#       Store the result in A.
      f&s  e#       Intersect A with each character of the word. Cast to string.
      s    e#       This removes all non-letters from the word.
      ,2<  e#       Count the letters, and compare the result to 2.
    },     e#     If there are less than 2 letters, keep the word.
    !      e#     Push the logical NOT of the result.
           e#     This pushes 1 iff all words contain enough letters.
    *      e#     Repeat the array of words that many times.
    1>     e#     Remove the first word.
  },       e#   Keep I if there are still words left.
  _{       e#   If at least one I was kept:
    W=     e#     Select the last (highest) one.
    /      e#     Split the string on the stack into chunks of that length.
    (      e#     Shift out the first chunk.
    AA26m> e#     Push "A...Za...z" and "a...zA...Z".
    er     e#     Perform transliteration to swap cases.
  }{       e#   Else:
    ;      e#     Discard the filtered array.
    (      e#     Shift out the first character of the string on the stack.
  }?       e#
  \s       e#   Swap the shifted out chunk/character with the rest of the string.
}h         e# If the remainder of the string is non-empty, repeat.

5
Come funziona: suona 20 note E # al pianoforte.
kirbyfan64sos,

Ho aggiunto qualche dettaglio in più. : P
Dennis,

2

Perl, 96 82 80 byte

-pe'$y=qr/[^a-z ]{2,}|\b\S[^a-z ]+/;s#$y( $y)+#join$,,map{uc eq$_?lc:uc}$&=~/./g#eg'

Supera tutti i test. Presuppone input da STDIN, stampa a STDOUT.

Come funziona:

  • imposta un regex ( $y) che corrisponde

    • almeno due caratteri non minuscoli e non bianchi O
    • un limite di parole, seguito da un carattere non bianco, seguito da uno o più caratteri non minuscoli, non bianchi
  • abbina più istanze di stringhe separate da spazio che corrispondono $y, usa s///per invertire il caso

Sono sicuro che c'è spazio per miglioramenti. Se c'è un modo per sbarazzarsi dell'intero join-map-splitaffare, potrebbe esserci ancora la possibilità di qualificarsi per il bonus :)


1
È possibile salvare alcuni byte utilizzando a-zinvece di [:lower:]. Inoltre, -peviene in genere conteggiato come 1 byte e le virgolette singole come zero byte.
Dennis,

@Dennis: grazie per il suggerimento! Ciò mi ha permesso di semplificare un po 'il codice - fino a 81 secondo le vostre linee guida sui battiti del Perl
Zaid,

Questa risposta non è valida, poiché non supera l'ultimo caso di test (recentemente aggiunto per gentile concessione di Dennis).
Maniglia della porta

2

Javascript, 193

decapslock =

a=>a.replace(/(^[a-z][^a-z ]+|[^a-z ]{2,})( [a-z][^a-z ]+| [^a-z ]{2,})+/g,b=>b.split` `.some(f=>f.split(/[a-z]/i).length<3)?b:b.split``.map(e=>e==(E=e.toUpperCase())?e.toLowerCase():E).join``)
<!-- Snippet UI -->
<input placeholder='sAMPLE tEXT' oninput="document.getElementsByTagName('p')[0].innerText=decapslock(this.value)" />
<p></p>

Spiegazione:

a=>a.replace(/* giant regex */,
  b=>
    b.split` `.some(
      f=>
        f.split(/[a-z]/i).length < 3   // check for 2+ letters
    )
      ? b                              // .some() immediately returns true if it's invalid
      : b.split``.map(                 // otherwise it's valid, so flip case
          e=>
            e == (E = e.toUpperCase()) // is it uppercase?
              ? e.toLowerCase()        // change it to LC
              : E                      // change it to UC, which was already done for
                                       // the case check
            ).join``
        )
(
^[a-z][^a-z ]+ // check for a CLR starting at the beginning with LC
|
[^a-z ]{2,}    // check for a CLR that begins in the middle of a word or starts at the
               // beginning with UC
               // in both cases, 2+ letters are required
)
(
 [a-z][^a-z ]+ // check for the next word of the CLR, starting with LC
|
 [^a-z ]{2,}   // check for the next word of the CLR, starting with UC
)+             // check for 1 or more next words

Questa risposta non è valida, poiché non supera l'ultimo caso di test (recentemente aggiunto per gentile concessione di Dennis).
Maniglia della porta

Argh, la correzione ha aggiunto tonnellate di byte a questo. Ma è stato risolto
DankMemes il
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.