Breaking Bad - ize qualquer string (compressão) [duplicado]

Aug 17 2020

A série de TV "Breaking Bad" substituiu as letras Br e Ba por uma representação semelhante a uma tabela periódica, impressão [Br35]eaking [Ba56]d.

Crie um programa que receba uma string de entrada, substitua e imprima uma saída. A substituição deve subsidiar qualquer substring que corresponda a um símbolo de elemento com a notação demonstrada em [Br35]eaking [Ba56]d. Ou seja, adicione o número atômico ao símbolo do elemento e coloque-o entre colchetes.

Todos os elementos começam com uma letra maiúscula e consistem em uma ou duas letras. O elemento mais alto a ser considerado é 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

Regras adicionais:

  • Como esse desafio é tanto sobre compressão quanto sobre golfe de código, você mesmo deve fornecer a lista de elementos. Você não deve usar nenhuma compilação em tabelas periódicas fornecidas por nosso idioma.
  • Trabalho com distinção entre maiúsculas e minúsculas. Isso significa que "Breaking Bad" tem 2 substituições, "Breaking Bad" tem uma. A entrada pode ser arbitrária e nem sempre seguirá a gramática inglesa. fOoBar se tornará f [O8] o [Ba56] r.
  • Busca ganancioso, [Ele] tem precedência sobre [H].

O código mais curto em bytes vence.

Respostas

6 Arnauld Aug 17 2020 at 22:57

JavaScript (ES6), 327 bytes

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

Experimente online!

Quão?

A string de dados consiste em todos os símbolos de elemento concatenados, do menor ao maior número atômico.

"HHeLiBeBCNOFNeNaMg...LvTsOg"

Nós o dividimos em uma lista a[]de 118 entradas com a seguinte expressão regular:

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

Criamos uma cópia de a[], colocamos todos os elementos de um único caractere no final da lista e unimos com barras verticais:

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

Que dá:

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

Transformamos essa string em uma expressão regular e a aplicamos à string de entrada. Cada subcadeia correspondente sé substituída pelo padrão:

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

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

Salvou 38 40 45 69 bytes (e corrigiu um bug) graças ao 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:]

Experimente online!

Primeiro analisa todos os produtos químicos de duas letras e, em seguida, os de uma única letra.

4 Neil Aug 18 2020 at 03:17

Carvão , 217 bytes

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⊕⌕υι]»ι

Experimente online! O link é para a versão detalhada do código. Explicação:

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

Divida uma lista de nomes de elementos em pares de letras e exclua os espaços.

≔⪪⮌S¹θ

Inverta a entrada e divida-a em caracteres.

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

Enquanto ainda houver entrada, remova os últimos 2 caracteres se houver um elemento correspondente, caso contrário, remova o último caractere.

¿№υι«

Se houver uma correspondência na matriz, então ...

[ιI⊕⌕υι]

... imprime a correspondência e seu número atômico dentro de []s.

»ι

Caso contrário, apenas imprima o caractere atual.

1 KevinCruijssen Aug 20 2020 at 18:56

05AB1E , 183 181 bytes

.œʒ.•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

Muito lento para entradas longas.

Experimente online ou verifique mais alguns casos de teste curtos .

Explicação:

.œ               # 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)

Veja este 05AB1E ponta do meu (seção Como cordas compressa não fazem parte do dicionário? ) Para entender por que .•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 bytes

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

Experimente online!