Numeronimi o N8?


10

Un numeronimo (noto anche come "contrazione numerica") è quando una parola viene abbreviata utilizzando i numeri. Un metodo di contrazione comune consiste nell'utilizzare la lunghezza della sottostringa sostituita per sostituire tutti tranne il primo e l'ultimo carattere. Ad esempio, utilizzare i18ninvece di internationalizationo L10ninvece dilocalization . (La lettera Lmaiuscola è minuscola poiché è troppo simile alla 1.)

Naturalmente, diverse parole nella stessa frase possono avere la stessa forma abbreviata, quindi il tuo compito è convertire un gruppo di parole nei loro numeronimi, o nel caso in cui esistano parole diverse con lo stesso numeronimo, il tuo programma dovrebbe dare un risultato di A7s R4t, abbreviazione di Ambiguous Result(sì, so che questo risultato è esso stesso un risultato ambiguo.)

Regole:

  • Utilizzare un programma o una funzione e stampare o restituire il risultato.
  • L'input è preso come una singola stringa.
  • L'output è una singola stringa di parole delimitate da spazi.
  • Il tuo programma non ha bisogno di convertire parole con lunghezza 3 e non deve convertire parole più brevi.
  • Se un l(ell maiuscolo) si verificasse prima di un 1(uno), dovrebbe essere reso maiuscolo.
  • Se si verifica un I(occhio maiuscolo) prima di un 1(uno), dovrebbe essere reso minuscolo.
  • L'input sarà ASCII e spazi stampabili. Le parole sono separate da spazi.
  • Il codice più corto vince.

Esempi:

A7s R4t -> A7s R4t (OR: A1s R1t, etc)
Ambiguous Result -> A7s R4t
Billy goats gruff -> B3y g3s g3f
Thanks for the Memories -> T4s f1r the M6s (one possible answer, NOT: Thnks fr th Mmrs)
Programming Puzzles & Code Golf -> P9g P5s & C2e G2f
globalization -> g11n
localizability -> L12y
Internationalization or antidisestablishmentarianism -> i18n or a26m
Internationalization or InternXXXXXalization -> A7s R4t
what is this fiddle and faddle -> A7s R4t
A be see -> A be s1e (OR: A be see)
see sea -> s1e s1a (OR: see sea)
2B or not 2B -> 2B or not 2B (OR: 2B or n1t 2B. 2 letters, don't change, don't count as ambiguous)
this example is this example -> t2s e5e is t2s e5e (same words aren't ambiguous)
l1 -> l1 (2 letters, don't change.)
I1 -> I1 (2 letters, don't change.)

Modifica: se qualcuno non ha ricevuto il riferimento: Thnks fr th Mmrs


Anche l'input può contenere numeri? In tal caso, un input di l1diventa L1o rimane come l1?
Maniglia della porta

Presumo dall'enfasi su ciò che sarebbe diverso , ma sarebbe bene includere un caso di prova che copra questo. example examplee5e e5e
Peter Taylor,

Aggiunti casi di test per entrambe le domande ( 2B or not 2Be successive)
mbomb007,

Risposte:


1

J, 92 byte

(' 'joinstring(<&(]`(rplc&('I1';'i1')&(rplc&('l1';'L1'))&({.,([:":#-2:),{:))@.(#>3:))&>&;:))

Una catena di chiamate composte. La prima parte è solo un fork: un letterale joinstring, e una funzione (in J, 1 (10 + +) 2è (10 + (1 + 2))). La seconda parte è la funzione. Le due rplcchiamate devono sostituire l'I / I quando potrebbero essere confuse. &è la composizione e la composizione di un operatore con un valore curry. (quindi 3&+fornisce una funzione che prevede l'aggiunta del secondo argomento). Infine, l'ultima parte è la funzione che accetta la prima, la lunghezza-2 (composta con stringificazione) e l'ultima. il &>&;:bit alla fine compone questa funzione (che dovrebbe essere applicata a ogni argomento) in >(unboxing), perché ;:(parole divise) restituisce un elenco in box (in modo che ogni elemento possa avere una lunghezza diversa).

esempio:

     (' 'joinstring(<&(]`(rplc&('I1';'i1')&(rplc&('l1';'L1'))&({.,([:":#-2:),{:))@.(#>3:))&>&;:)) 'hey you baby Iooooooooneey I1'
hey you b2y i11y I1

4

Cache ObjectScript , 231 byte

r(a,b) s o=$REPLACE(o,a,b) q
z(s) f i=1:1:$L(s," ") s u=$P(s," ",i),l=$L(u),o=$S(l<4:u,1:$E(u)_(l-2)_$E(u,l)) d:l>3 r("I1","i1"),r("l1","L1") d  g:r z+4
    . i '(l<4!(v(o)=u!'$D(v(o)))) s r=1 q
    . s v(o)=u,t=t_o_" "
    q t
    q "A7s R4t"

Questo sarebbe un buon MUMPS conforme agli standard se non fosse per quella fastidiosa $REPLACEchiamata, che non fa parte dello standard. La reimplementazione in M ​​puro richiede ben 80 byte, quindi non ho seguito quella strada.

Il punto di ingresso è $$z("your string here"), che ritorna "y2r s4g h2e", e così via.


3
Potresti forse collegarti alla lingua? Non ne ho sentito parlare.
mbomb007,

Voglio dire, è la cosa che ti viene in mente quando vai su Google ( docs.intersystems.com/cache20152/csp/docbook/… ) - un sapore proprietario di MUMPS.
senshin,

3

C #, 280 274 byte

Giocatore di golf per la prima volta qui! Mi sono divertito a leggere questi ultimamente e quindi ho pensato di provarne qualcuno! Probabilmente non è la soluzione migliore, ma vabbè!

class B{static void Main(string[] a){string[] n=Console.ReadLine().Split(' ');string o="";int j,i=j=0;for(;j<n.Length;j++){int s=n[j].Length;n[j]=((s<4)?n[j]:""+n[j][0]+(s-2)+n[j][s-1])+" ";o+=n[j];for(;i<j;i++)if(n[j]==n[i]){o="A7s R4t";j=n.Length;}}Console.WriteLine(o);}}

Stessa cosa non golfata:

class B
{
    static void Main(string[] a)
    {            
        string[] n = Console.ReadLine().Split(' ');
        string o = "";
        int j, i = j = 0;
        for(; j < n.Length;j++)
        {
            int s = n[j].Length;

            n[j] = ((s<4) ? n[j] : "" + n[j][0] + (s - 2) + n[j][s - 1]) + " ";
            o += n[j];
            for (; i < j; i++)
            {
                if (n[j] == n[i]) { o = "A7s R4t"; j=n.Length;}
            }                              
        }
        Console.WriteLine(o);
    }
}

Grazie ragazzi!


Benvenuti in PPCG! c:
Deusovi,

2

Perl, 131 120 byte

Ho aggiunto un byte per l'utilizzo dello -pswitch:

s/\B(\w+)(\w)/length($1)."$2_$1"/ge;$_="A7s R4t\n"if/(\w\d+\w)(\w+)\b.*\1(?!\2)/;s/_\w+//g;s/I1\w/\l$&/g;s/l1\w/\u$&/g;

Spiegazione

# Replace internal letters with count, but keep them around for the next test.
s/\B(\w+)(\w)/length($1)."$2_$1"/ge;
# Detect ambiguous result
$_ = "A7s R4t\n" if
    # Use negative look-ahead assertion to find conflicts
    /(\w\d+\w)(\w+)\b.*\1(?!\2)/;
# We're done with the internal letters now
s/_\w+//g;
# Transform case of initial 'I' and 'l', but only before '1'
s/I1\w/\l$&/g;
s/l1\w/\u$&/g;

Non sono sicuro se sia corretto, ma mi aspettavo che la "l" in "mi piace" non venisse capitalizzata quando trasformata in "l2e", poiché non è seguita da "1".
arte

Testato solo un paio di casi, ma sembra funzionare: s/(\w)(\w+)(\w)/$1.length($2)."$3_$2"/ges/\B(\w+)(\w)/length($1)."$2_$1"/ge.
arte

Grazie, @manatwork. Ho trascurato il requisito di casewap [Il]solo prima 1, risparmiando anche un paio di byte!
Toby Speight,

1

JavaScript (ES6), 165 byte

s=>(r=s.replace(/\S+/g,w=>(m=w.length-2)<2?w:(i=d.indexOf(n=((m+s)[0]<2&&{I:"i",l:"L"}[w[0]]||w[0])+m+w[m+1]))>=0&d[i+1]!=w?v=0:d.push(n,w)&&n,v=d=[]),v?r:"A7s R4t")

Spiegazione

s=>(                         // s = input string
  r=s.replace(               // r = result of s with words replaced by numeronyms
    /\S+/g,                  // match each word
    w=>                      // w = matched word
      (m=w.length-2)         // m = number of characters in the middle of the word
        <2?w:                // if the word length is less than 4 leave it as it is
      (i=d.indexOf(          // check if this numeronym has been used before
        n=                   // n = numeronymified word
          ((m+s)[0]<2&&      // if the number starts with 1 we may need to replace
            {I:"i",l:"L"}    //     the first character with one of these
              [w[0]]||w[0])+ // return the replaced or original character
          m+w[m+1]
      ))>=0&d[i+1]!=w?       // set result as invalid if the same numeronym has been
        v=0:                 //     used before with a different word
      d.push(n,w)&&n,        // if everything is fine return n and add it to the list
    v=                       // v = true if result is valid
      d=[]                   // d = array of numeronyms used followed by their original word
  ),
  v?r:"A7s R4t"              // return the result
)

Test


1

JavaScript ES6, 162

w=>(v=(w=w.split` `).map(x=>(l=x.length-2+'')>1?((l[0]>1||{I:'i',l:'L'})[x[0]]||x[0])+l+x[-~l]:x)).some((a,i)=>v.some((b,j)=>a==b&w[i]!=w[j]))?'A7s R4t':v.join` `

Meno golf

// Less golfed
f=w=>{
  w = w.split` ` // original text splitted in words
  v = w.map(x=> { // build modified words in array v

    l = x.length - 2 // word length - 2
    if (l > 1) // if word length is 4 or more
    {
      a = x[0] // get first char of word
      l = l+'' // convert to string to get the first digit
      m = l[0] > 1 || {I:'i', l:'L'} // only if first digit is 1, prepare to remap I to i and l to L
      a = m[a] || a // remap
      return a + l + x[-~l] // note: -~ convert back to number and add 1
    }
    else
      return x // word unchanged
  })
  return v.some((a,i)=>v.some((b,j)=>a==b&w[i]!=w[j])) // look for equals Numeronyms on different words
  ? 'A7s R4t' 
  : v.join` `
}  

Test


1

Python 2, 185 byte

d={}
r=''
for w in input().split():
 l=len(w);x=(w[0]+`l-2`+w[-1]).replace('l1','L1').replace('I1','i1')
 if l<4:x=w
 if d.get(x,w)!=w:r='A7s R4t';break
 d[x]=w;r+=x+' '
print r.strip()

1

Python 3, 160

Mi piacerebbe trovare un buon modo per sostituire quelle chiamate di sostituzione.

def f(a):y=[(x,(x[0]+str(len(x)-2)+x[-1]).replace('l1','L1').replace('I1','i1'))[len(x)>3]for x in a.split()];return('A7s R4t',' '.join(y))[len(set(y))==len(y)]

Con alcuni casi di test:

assert f('Billy goats gruff') == 'B3y g3s g3f'
assert f('Programming Puzzles & Code Golf') == 'P9g P5s & C2e G2f'
assert f('Internationalization or InternXXXXXalization') == 'A7s R4t'

1

Fattore, 48 35 byte, non competitivo

È una lambda che va in pila, che tecnicamente non soddisfa i requisiti davvero fastidiosi che inizialmente sono riuscito a trascurare.

[ " " split [ a10n ] map " " join ]

Usa il englishvocabolario.

Oppure, se incorporiamo la a10nparola della libreria, quindi 131 byte (con importazioni automatiche):

: a ( b -- c ) " " split [ dup length 3 > [ [ 1 head ] [ length 2 - number>string ] [ 1 tail* ] tri 3append ] when ] map " " join ;

Questo gestisce le cose I / L e A7s R4t?
Robert Fraser,

@RobertFraser Ne sono certo, anche se non sono un compilatore di Factor in questo momento; Aggiungerò i test unitari di passaggio quando lo sono. : D
cat

Sì, scusa per i requisiti. Una settimana dopo aver finito la domanda, ero tipo "oh no, cosa ho fatto", ma era troppo tardi. Potrei fare una versione più semplice come una sfida separata.
mbomb007,
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.