Stringhe numeriche nidificate con analisi ridotta


16

L'obiettivo

Una stringa Sviene costruita con il seguente processo:

  1. Inizia con l' Sessere la stringa vuota.
  2. Inserisci in una posizione di Suna stringa del modulo ds, dove si dtrova una cifra diversa da zero ed sè una stringa di dlettere ASCII minuscole. Diciamo che dsè un componente di S.
  3. Andare al passaggio 2 o interrompere.

Il tuo compito è prendere una stringa come input e produrre i suoi componenti concatenati in una singola stringa, nell'ordine di comparsa delle loro cifre iniziali. L'output deve essere una singola stringa e non possono esserci delimitatori (comprese le nuove righe) tra i componenti. Puoi scegliere se le stringhe di input e output hanno virgolette. Si noti che l'input e l'output non saranno mai vuoti.

Esempio

Costruiamo una stringa con il processo sopra. La struttura dei componenti è evidenziata nel risultato finale.

S = ""              // Insert "3abc"
S = "3abc"          // Insert "2gh" after 'a'
S = "3a2ghbc"       // Insert "1x" before '3'
S = "1x3a2ghbc"     // Insert "3tty" after '3'
S = "1x33ttya2ghbc" // Final result
     └┘│└┴┴┘│└┴┘││
       └────┴───┴┘

L'output si ottiene concatenando i componenti nell'ordine delle loro cifre. In questo caso, l'output corretto è

"1x3abc3tty2gh"

Regole e punteggio

È possibile scrivere un programma completo o una funzione. vince il conteggio di byte più basso e non sono consentite scappatoie standard.

Casi test

1k -> 1k
4asdf -> 4asdf
111xyz -> 1z1y1x
8whatever3yes -> 8whatever3yes
8what3yesever -> 8whatever3yes
1x33ttya2ghbc -> 1x3abc3tty2gh
63252supernestedstrings2ok -> 6trings3eds2st5perne2su2ok
9long3yes4lo2ngwords11here -> 9longrdsre3yes4lowo2ng1e1h
9abc8de7fg6hi5jk4lm3o2pq1rstuvwxyzabcdefghijklmnopqrst -> 9abcopqrst8deijklmn7fgdefgh6hizabc5jkwxy4lmuv3ost2pq1r

Risposte:


2

JavaScript (ES6), 68 byte

f=s=>s&&f(s.replace(/\d\D+$/,m=>(s=m.slice(0,i=++m[0]),m.slice(i))))+s

Spiegazione

Basato su un concetto semplice:

  • Abbina l'ultima cifra nseguita dalle nlettere nella stringa di input
  • Rimuoverlo dalla stringa di input e aggiungerlo all'inizio della stringa di output
  • Ripetere fino a quando la stringa di input è vuota

La ricorsione era il modo più breve per farlo in JavaScript.

f=s=>
  s&&                        // if the input string is empty, return the empty string
  f(                         // prepend the constituent before it
    s.replace(/\d\D+$/,m=>(  // match the last digit followed by every remaining letter
      s=m.slice(0,n=++m[0]), // set s to the constituent (n followed by n letters)
                             // (we must use s because it is our only local variable)
      m.slice(n)             // replace the match with only the letters after it
    ))
  )+s                        // append the constituent
<input type="text" id="input" value="9long3yes4lo2ngwords11here" />
<button onclick="result.textContent=f(input.value)">Go</button>
<pre id="result"></pre>


0

Haskell , 89 byte

fst.p
p(d:s)|(h,(g,r))<-p<$>span('9'<)s,(a,b)<-splitAt(read[d])$h++r=(d:a++g,b)
p e=(e,e)

Provalo online! Esempio di utilizzo: fst.p $ "1x33ttya2ghbc"rese "1x3abc3tty2gh".


0

Python 3 , 173 159 byte

k='123456789';y='';i=0
for t in x:
 i+=1
 if t in k:
  y+=t;n=int(t);m=0
  for z in x[i:]:
   if n:  
    if z in k:m+=int(z)+1
    if m<1:y+=z;n-=1
    m-=m>0

Provalo online!

Probabilmente non l'implementazione Python più golfistica.

La logica è quasi semplice: scansiona la stringa. Quando trova una cifra inizia ad aggiungere i caratteri che seguono, quanti ne richiedono (cioè fino a quando il conteggio corrisponde alla cifra). Se rileva cifre prima di completare l'attività, le aggiunge a un contatore corrispondente al numero di caratteri da saltare. Quando il contatore raggiunge lo zero, torna ad aggiungere caratteri (cioè fino a quando il conteggio corrisponde alla cifra iniziale).

Nota: salvato 14 byte grazie a Wheat Wizard e HyperNeutrino


1
Per una riga se le istruzioni non sono necessarie ad esempio un avanzamento riga if z in k:m+=N(z)+1.
Post Rock Garf Hunter,

1
La rimozione di N=inteffettivamente consente di risparmiare 2 byte. La ridenominazione intè utile solo dopo 4 utilizzi.
HyperNeutrino,

0

Java 8, 152 byte

s->{String t=s,r="";for(char c;!s.isEmpty();c=t.charAt(0),s=s.replace(t=c+(t.substring(1,c-47)),""),r=t+r)t=s.replaceAll(".*(\\d\\D+$)","$1");return r;}

Spiegazione:

Provalo qui.

s->{                        // Method with String as both parameter and return-type
  String t=s,               //  Temp-String, starting at the input-String
         r="";              //  Result-String, starting empty
  for(char c;!s.isEmpty();  //  Loop as long as the input-String `s` is not empty
                            //    After every iteration:
      c=t.charAt(0),        //     Get the leading digit from `t` as character
      s=s.replace(t=c+(t.substring(1,c-47))
                            //     Set `t` to the last substring (digit + `c` letters),
                  ,""),     //     and remove that sub-string from String `s`
      r=t+r)                //     And add the substring at the start of result-String `r`
    t=s.replaceAll(".*(\\d\\D+$)","$1");
                            //   Get the last digit + everything after it,
                            //   and set this substring to `t`
                            //  End of loop (implicit / single-line body)
  return r;                 //  Return result-String
}                           // End of method

0

Python 2 , 151 147 135 byte

d,D=[],[]
for c in input():
 if'/'<c<':':x=[[c]];d=x+d;D+=x
 else:y=d[0];y+=c;d=d[len(y)>int(y[0]):]
print''.join(''.join(w)for w in D)

Provalo online!

Spiegazione:

Il codice conserva due elenchi di gruppi costituenti, d and D.

Ogni carattere della stringa viene quindi scansionato:

  • Se è una cifra, un nuovo gruppo viene aggiunto a entrambi gli elenchi
  • Altrimenti, il personaggio viene aggiunto all'ultimo gruppo in d

Quando un gruppo ha la stessa lunghezza della sua cifra, il gruppo viene rimosso da d.

Alla fine, Dviene concatenato, poiché i gruppi Dsono nell'ordine originale.

Esempio:

Input = '1121xwyzv'
d = [], D = []
Loop each character in the input

c='1'
    d=[[1]], D=[[1]]
c='1'
    d=[[1], [1]], D=[[1], [1]]
c='2'
    d=[[2], [1], [1]], D=[[1], [1], [2]]
c='1'
    d=[[1], [2], [1], [1]], D=[[1], [1], [2], [1]]
c='x'
    d=[[1x], [2], [1], [1]], D=[[1], [1], [2], [1x]]
latest group in d is full:
    d=[[2], [1], [1]], D=[[1], [1], [2], [1x]]
c='w'
    d=[[2w], [1], [1]], D=[[1], [1], [2w], [1x]]
c='y'
    d=[[2wy], [1], [1]], D=[[1], [1], [2wy], [1x]]
latest group in d is full:
    d=[[1]], D=[[1], [1], [2wy], [1x]]
c='z'
    d=[[1z], [1]], D=[[1], [1z], [2wy], [1x]]
latest group in d is full:
    d=[[1]], D=[[1], [1z], [2wy], [1x]]
c='v'
    d=[[1v]], D=[[1v], [1z], [2wy], [1x]]
latest group in d is full:
    d=[], D=[[1v], [1z], [2wy], [1x]]
print D in order:
    '1v1z2wy1x'
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.