Breaking Bad - ize any string (compressione) [duplicate]

Aug 17 2020

La serie TV "Breaking Bad" ha sostituito le lettere Br e Ba con una rappresentazione simile a una tavola periodica, la stampa [Br35]eaking [Ba56]d.

Crea un programma che accetta una stringa di input, fa una sostituzione e stampa un output. La sostituzione deve sovvenzionare qualsiasi sottostringa che corrisponda a un simbolo di elemento con la notazione dimostrata in [Br35]eaking [Ba56]d. Cioè, aggiungi il numero atomico al simbolo dell'elemento e racchiudi tra parentesi quadre.

Tutti gli elementi iniziano con una lettera maiuscola e sono composti da una o due lettere. L'elemento più alto da considerare è Og118. Da wikipedia:

1 H, 2 He, 3 Li, 4 Be, 5 B, 6 C, 7 N, 8 O, 9 F, 10 Ne, 11 Na, 12 Mg, 13 Al, 14 Si, 15 P, 16 S, 17 Cl , 18 Ar, 19 K, 20 Ca, 21 Sc, 22 Ti, 23 V, 24 Cr, 25 Mn, 26 Fe, 27 Co, 28 Ni, 29 Cu, 30 Zn, 31 Ga, 32 Ge, 33 As, 34 Se, 35 Br, 36 Kr, 37 Rb, 38 Sr, 39 Y, 40 Zr, 41 Nb, 42 Mo, 43 Tc, 44 Ru, 45 Rh, 46 Pd, 47 Ag, 48 Cd, 49 In, 50 Sn, 51 Sb, 52 Te, 53 I, 54 Xe, 55 Cs, 56 Ba, 57 La, 58 Ce, 59 Pr, 60 Nd, 61 Pm, 62 Sm, 63 Eu, 64 Gd, 65 Tb, 66 Dy, 67 Ho , 68 Er, 69 Tm, 70 Yb, 71 Lu, 72 Hf, 73 Ta, 74 W, 75 Re, 76 Os, 77 Ir, 78 Pt, 79 Au, 80 Hg, 81 Tl, 82 Pb, 83 Bi, 84 Po, 85 At, 86 Rn, 87 Fr, 88 Ra, 89 Ac, 90 Th, 91 Pa, 92 U, 93 Np, 94 Pu, 95 Am, 96 Cm, 97 Bk, 98 Cf, 99 Es, 100 Fm, 101 Md, 102 No, 103 Lr, 104 Rf, 105 Db, 106 Sg, 107 Bh, 108 Hs, 109 Mt, 110 Ds, 111 Rg, 112 Cn, 113 Nh, 114 Fl, 115 Mc, 116 Lv, 117 Ts , 118 Og

Regole aggiuntive:

  • Poiché questa sfida riguarda la compressione tanto quanto il golf di codice, è necessario fornire l'elenco degli elementi da soli. Non è necessario utilizzare alcuna build nelle tabelle periodiche fornite dal nostro linguaggio.
  • Fa distinzione tra maiuscole e minuscole. Ciò significa che "Breaking Bad" ha 2 sostituzioni, "Breaking Bad" ne ha una. L'input può essere arbitrario e non segue sempre la grammatica inglese. fOoBar diventerà f [O8] o [Ba56] r.
  • Cerca avido, [He] ha la precedenza su [H].

Il codice più breve in byte vince.

Risposte

6 Arnauld Aug 17 2020 at 22:57

JavaScript (ES6), 327 byte

s=>s.replace(RegExp([...a="HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg".match(/.[a-z]?/g)].sort(s=>-!!s[1]).join`|`,'g'),s=>`[${s+-~a.indexOf(s)}]`)

Provalo online!

Come?

La stringa di dati è composta da tutti i simboli degli elementi concatenati insieme, dal numero atomico più basso al più alto.

"HHeLiBeBCNOFNeNaMg...LvTsOg"

Lo abbiamo diviso in un elenco a[]di 118 voci con la seguente espressione regolare:

 +------> any character (always a capital letter)
 |   +--> optionally followed by a letter in lower case
 | __|_
 |/    \
/.[a-z]?/g

Creiamo una copia di a[], mettiamo tutti gli elementi di un carattere alla fine della lista e uniamo con pipe:

[...a].sort(s => -!!s[1]).join('|')

Che dà:

"Og|Ts|Lv|Mc|Fl|Nh|...|He|H|B|C|N|O|F|P|S|K|V|Y|I|W|U"

Trasformiamo questa stringa in un'espressione regolare e la applichiamo alla stringa di input. Ogni sottostringa abbinata sviene sostituita con il modello:

`[${s + -~a.indexOf(s)}]`
4 Noodle9 Aug 17 2020 at 23:20

Python 3.8 , 454 \$\cdots\$409 385 byte

Ho salvato ben 38 40 45 69 byte (e corretto un bug) grazie a ovs !!!

eval("lambda s:_]and_<b][-1]".replace('_',"[(s:=re.sub(f'(?<!\[){b}',f'[{b}{e}]',s))for e,b in p if b[1:]"))
import re
p=[*enumerate(re.split("(?=[A-Z])","HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg"))][1:]

Provalo online!

Prima passa attraverso tutte e due le sostanze chimiche per lettere e poi quelle singole.

4 Neil Aug 18 2020 at 03:17

Carboncino , 217 byte

F⪪”}∨"²Q/QH▷⊕Ff←SγG¤º&ρωVφ∨]›¶⁻Nr*Sψ⦄π⁶&U⊞jεJκκH‹ι7◧"↷⌊Rι¦◧◧‽3▷↨↑´^@➙⊙×π+sQ⌈⊙▷TQ|ⅉB{_Π"⪪η(⁵AxQWW/⁻∨8▶u…κ¹*ITλ_⟧‽Hj.⊞;r⬤|›∧7ψjêÞζp⸿⊖¿⊖Q℅↷Hb↨“↔=bY⁵⌈↷¬δ⎚⪫:D₂↓;≦?⁺[‴.t4r±,s^)↗τ”²⊞υΦι›κ ≔⪪⮌S¹θW∧θ⭆⊕№υ⭆²§⮌θκ⊟θ¿№υι«[ιI⊕⌕υι]»ι

Provalo online! Il collegamento è alla versione dettagliata del codice. Spiegazione:

F⪪”...”²⊞υΦι›κ 

Dividi un elenco di nomi di elementi in coppie di lettere ed elimina gli spazi.

≔⪪⮌S¹θ

Invertire l'input e dividerlo in caratteri.

W∧θ⭆⊕№υ⭆²§⮌θκ⊟θ

Mentre è ancora presente un input, rimuovere gli ultimi 2 caratteri se è presente un elemento corrispondente, altrimenti rimuovere l'ultimo carattere.

¿№υι«

Se c'è una corrispondenza nell'array, allora ...

[ιI⊕⌕υι]

... stampa la corrispondenza e il suo numero atomico all'interno di []s.

»ι

Altrimenti stampa semplicemente il carattere corrente.

1 KevinCruijssen Aug 20 2020 at 18:56

05AB1E , 183 181 byte

.œʒ.•2вy>ÖΘZθÒ7ßΩ¨ÑÝ
(Îiþ∍ćf=ÆΛ}’.мιoiFδC¸Γ=¢`Ÿíнp»ΛÑzðÿ®ÄÄ‘Â@Âη+(Óûò‘8нKKK#â<Ù#<“râµ5£”м}ÓæuüåÈZµ-ΔÈ;VzeY¯õnK§ÁÚ¡[θƶη„Gp©6›mðÿāε1ΛÎíγJò~܉cT¢Œƶʒ˜•2ô™ðм©såüαP}Σ€g{ygš}θ®DεN>«…[ÿ]}‡J

Abbastanza lento per input lunghi.

Provalo online o verifica alcuni casi di test più brevi .

Spiegazione:

.œ               # Get all partitions of the (implicit) input-string
  ʒ              # Filter these list of parts by:
   .•2вy...ƶʒ˜•  #  Push compressed string "h helibeb c n o f nenamgalsip s clark casctiv crmnfeconicuzngageassebrkrrbsry zrnbmotcrurhpdagcdinsnsbtei xecsbalaceprndpmsmeugdtbdyhoertmybluhftaw reosirptauhgtlpbbipoatrnfrraacthpau nppuamcmbkcfesfmmdnolrrfdbsgbhhsmtdsrgcnnhflmclvtsog"
     2ô          #  Split it into parts of size 2: ["h ","he","li","be","b "...]
       ™         #  Titlecase each string: ["H ","He","Li","Be","B ",...]
        ðм       #  Remove all spaces from each string: ["H","He","Li","Be","B",...]
          ©      #  Store this list in variable `®` (without popping)
           s     #  Swap so the current partition is at the top of the stack
            å    #  Check for each inner part whether it's in the element-list
                 #  (1 if truthy; 0 if falsey)
             ü   #  For each overlapping pair:
              α  #   Get the absolute difference
               P #  Get the product of those to check if all are truthy (1)
                 #  (partitions in the form of [0,1,0,1,...] or [1,0,1,0,...] are left)
  }Σ             # After the filter: sort any remaining partition by:
    €            #  Map each part in the list to:
     g           #   Pop and push its length
      {          #  Sort this list of lengths
       y         #  Push the current partition again
        g        #  Pop and push its length to get the amount of parts in this partition
         š       #  And prepend it at the front of the other lengths
   }θ            # After the sort by: only leave the last partition,
                 # which will have the most parts, as well as the longest individual parts
     ®           # Push the list of elements from variable `®` again
      D          # Duplicate it
       ε         # Map the copy to:
        N>       #  Push the 0-based map index, and increase it by 1
          «      #  Append it to the element-string
           …[ÿ]  #  Push string "[ÿ]", where the `ÿ` is automatically filled with the
                 #  element name and number
       }‡        # After the map: transliterate all elements to the formatted elements in
                 # the partition
         J       # And join it back together to a single string
                 # (after which it is output implicitly as result)

Vedi questo mio suggerimento 05AB1E (sezione Come comprimere le stringhe non fa parte del dizionario? ) Per capire perché lo .•2вy>ÖΘZθÒ7ßΩ¨ÑÝ\n(Îiþ∍ćf=ÆΛ}’.мιoiFδC¸Γ=¢`Ÿíнp»ΛÑzðÿ®ÄÄ‘Â@Âη+(Óûò‘8нKKK#â<Ù#<“râµ5£”м}ÓæuüåÈZµ-ΔÈ;VzeY¯õnK§ÁÚ¡[θƶη„Gp©6›mðÿāε1ΛÎíγJò~܉cT¢Œƶʒ˜•è "h helibeb c n o f nenamgalsip s clark casctiv crmnfeconicuzngageassebrkrrbsry zrnbmotcrurhpdagcdinsnsbtei xecsbalaceprndpmsmeugdtbdyhoertmybluhftaw reosirptauhgtlpbbipoatrnfrraacthpau nppuamcmbkcfesfmmdnolrrfdbsgbhhsmtdsrgcnnhflmclvtsog".

Xcali Aug 21 2020 at 02:20

Perl 5 -p , 313 byte

map$k{$_}=++$j,HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg=~/.[a-z]?/g;for$a(sort{$b=~y///c-length$a}keys%k){s/(?<!\[)$a/[$a$k{$a}]/g}

Provalo online!