Facey McFaceface


47

Qualcuno ricorda Boaty ?

Potresti totalmente fare una vecchia parola, giusto?

  • Scrivi una funzione per trasformare una stringa in Somethingy McSomethingface.
  • Dovrebbe accettare una stringa come input. Ignora il caso dell'input.
  • Se la parola termina con 'y', la tua funzione non dovrebbe aggiungere una 'y' aggiuntiva alla prima istanza, ma dovrebbe rimuoverla nella seconda istanza.
  • Se la parola termina in 'ey', non dovrebbe essere aggiunta una 'y' aggiuntiva nella prima istanza, ma dovrebbe rimuovere entrambe nella seconda istanza.
  • L'output dovrebbe contenere solo lettere maiuscole nel primo carattere, la "M" di "Mc" e il primo carattere dopo "Mc".
  • deve funzionare solo con stringhe di 3 o più caratteri.

Esempi:

boat                  =>  Boaty McBoatface
Face                  =>  Facey McFaceface
DOG                   =>  Dogy McDogface
Family                =>  Family McFamilface
Lady                  =>  Lady McLadface
Donkey                =>  Donkey McDonkface
Player                =>  Playery McPlayerface
yyy                   =>  Yyy McYyface
DJ Grand Master Flash =>  Dj grand master flashy McDj grand master flashface

Che dire degli spazi nella stringa, li lasciamo intatti? Esempi: ' y'e' '
— tocca il mio corpo il

2
Ho intenzione di implementare un suggerimento da @Arnauld e renderlo minimo di tre caratteri. Tratta gli spazi bianchi proprio come un'altra lettera.
— AJFaraday,


Possiamo supporre che l'input conterrà solo lettere maiuscole e minuscole?
— Kevin Cruijssen,

@KevinCruijssen Non ho inserito nessuna non lettera nei casi di test, quindi non sono effettivamente interessati.
— AJFaraday,

Risposte:


7

Stax , 26 byte

ëO╛εh╕⌠î&!}∞┌C^U╟«äδ◙Bg⌠└¿

Esegui ed esegui il debug

^           convert input to upper case                     "FACE"
B~          chop first character and push it back to input  70 "ACE"
v+          lowercase and concatenate                       "Face"
c'yb        copy, push "y", then copy both                  "Face" "Face" "y" "Face" "y"
:]          string ends with?                               "Face" "Face" "y" 0
T           trim this many character                        "Face" "Face" "y"
+           concatenate                                     "Face" "Facey"
p           output with no newline                          "Face"
"e?y$"z     push some strings                               "Face" "e?y$" ""
" Mc`Rface  execute string template; `R means regex replace " Mc Faceface"
            result is printed because string is unterminated

Esegui questo


15

V , 27 28 30 byte

Vu~Ùóe¿y$
Hóy$
ÁyJaMc<Esc>Aface

Provalo online!

<Esc> Rappresenta 0x1b

  • Golfato due byte dopo aver appreso che non era necessario supportare input con meno di 3 caratteri.

  • 1 byte salvato grazie a @DJMcMayhem lavorando sulla seconda riga prima della prima, rimuovendo così il G

L'input è nel buffer. Il programma inizia convertendo tutto in minuscolo

Vseleziona la linea e la mette in uminuscolo

~ attiva o disattiva il caso del primo carattere (convertendolo in maiuscolo)

e Ùduplica questa riga sopra, lasciando il cursore sulla riga inferiore

óe sostituisce e¿y$, forma compressa di e\?y$(opzionale ee ya alla fine della riga), con nulla (accade sulla seconda riga)

H va alla prima riga

ósostituisce y$( yalla fine della riga) con nulla sulla prima riga

Áaggiunge ya alla fine della prima riga

J e unisce l'ultima riga alla prima con uno spazio nel mezzo e il cursore viene spostato in questo spazio

aaggiunge Mc( <Esc>torna alla modalità normale)

Ainfine, aggiunge facealla fine della linea



13

Python, 144 byte

def f(s):
 s=s[0].upper()+s[1:].lower()
 y=lambda s:s[:-1]if s[-1]=='y'else s
 t=y(s)
 u=s[:-2]if s[-2:]=='ey'else y(s)
 return t+'y Mc%sface'%u

Provalo online qui


2
il mio primo tentativo di golf in codice ...
— tocca il mio corpo il

3
benvenuto in PPCG! potrei suggerire di aggiungere un link per provarlo online! per la verifica della correttezza?
— Giuseppe

1
f("Face")non è conforme ai casi di test attuali ( TIO ).
— Jonathan Frech,

Post modificato per correttezza, aggiunto anche un Provalo online! link
— tocca il mio corpo il


12

Excel, 204 144 137 165 byte

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(REPT(REPLACE(LOWER(A1),1,1,UPPER(LEFT(A1)))&"~",2),"~","y Mc",1),"yy ","y "),"ey~","~"),"y~","~"),"~","face")

Dall'interno verso l'esterno:

REPLACE(LOWER(A1),1,1,UPPER(LEFT(A1)))      Replaces PROPER to handle space-delimited cases
REPT(%&"~",2)                   Duplicate.                    Donkey~Donkey~
SUBSTITUTE(%,"~","y Mc",1)      Replace first ~.              Donkeyy McDonkey~
SUBSTITUTE(%,"yy ","y ")        Handle words ending in 'y'.   Donkey McDonkey~
SUBSTITUTE(%,"ey~","~")         Handle words ending in 'ey'   Donkey McDonk~
SUBSTITUTE(%,"y~","~")          Handle words ending in 'y'    Donkey McDonk~
SUBSTITUTE(%,"~","face")        Adding face.                  Donkey McDonkface

Vecchia risposta, creando tutti i bit separatamente e quindi concatenando (176 byte). Non gestisce correttamente i casi delimitati da spazi.

=PROPER(A1)&IF(LOWER(RIGHT(A1,1))="y",,"y")&" Mc"&IF(LOWER(RIGHT(A1,2))="ey",LEFT(PROPER(A1),LEN(A1)-2),IF(LOWER(RIGHT(A1,1))="y",LEFT(PROPER(A1),LEN(A1)-1),PROPER(A1)))&"face"

Sfortunatamente, a causa del requisito di gestione dei casi delimitati da spazi, PROPER(A1)non è valido (vedere il DJ Grand Master Flashcaso di input), la migliore sostituzione che ho potuto trovare mentre lavoravo sulla mia soluzione VBA è stata LEFT(UPPER(A1))&MID(LOWER(A1),2,LEN(A1)): per favore fatemi sapere se finite per giocare a golf.
— Taylor Scott,

1
Grazie @TaylorScott. Trovato 'REPLACE (LOWER (A1), 1,1, UPPER (LEFT (A1))) `che è più corto di 2 byte.
— Wernisch,


9

C # (.NET Core) , 122 108 139 175 180 179 154 byte

Grazie mille, Lee!

s=>((s.EndsWith("y")?s:s+"y")+" Mc"+(s+"$").Replace("ey$","")+"face").Replace(s,s.ToUpper()[0]+s.Substring(1).ToLower()).Replace("y$","").Replace("$","");

Provalo online!

C # (.NET Core, con LINQ), 152 byte

s=>((s.Last()=='y'?s:s+"y")+" Mc"+(s+"$").Replace("ey$","")+"face").Replace(s,s.ToUpper()[0]+s.Substring(1).ToLower()).Replace("y$","").Replace("$","");

Provalo online!


3
Benvenuti nel sito! :)
— DJMcMayhem


7

Rubino , 61 49 byte

->s{s.capitalize=~/(e)?y$|$/;"#$`#$1y Mc#$`face"}

Provalo online!

Risparmiato 12 byte dolci grazie a @MartinEnder:


1
Usando il regex dalla mia risposta Retina e facendo un po 'più di interpolazione delle stringhe si arriva a 49: tio.run/##DcxBCsIwEEDRqwxJBF3Y4lpSN0U3igcQwTQmGFptMVNkTOLVY3bvb/…
— Martin Ender

@MartinEnder Wow, questa è una bella differenza. Non credo di aver visto l'interpolazione di stringhe senza parentesi. Lo prenderò se non vuoi usarlo per la tua risposta su Ruby.
— Ripristina Monica iamnotmaynard il

No, va bene, non mi sarei mai inventato di usare =~e costruire l'intera stringa invece di usarla sub. L'interpolazione di stringhe può essere utilizzata senza parentesi se la variabile è una variabile globale, di istanza o di classe.
— Martin Ender,

Puoi farlo scendere a 44 + 1 byte usando la -pbandiera e usando sub: tio.run/…
— Giordania

7

Python 3 , 80 byte

Avido lettore da molto tempo, finalmente la mia prima presentazione!

lambda y:re.sub("([\w ]+?)((e)?y)?$",r"\1\3y Mc\1face",y.capitalize())
import re

Provalo online


1
Benvenuto in PPCG, e bellissimo primo post!
— Zacharý,



5

Java 8, 121 112 107 106 byte

s->(s=(char)(s.charAt(0)&95)+s.toLowerCase().substring(1)).split("y$")[0]+"y Mc"+s.split("e?y$")[0]+"face"

-1 byte grazie a @ OliverGrégoire .

Spiegazione:

Provalo online.

s->                         // Method with String as both parameter and return-type
  (s=                       //  Replace and return the input with:
     (char)(s.charAt(0)&95) //   The first character of the input as Uppercase
     +s.toLowerCase().substring(1))
                            //   + the rest as lowercase
  .split("y$")[0]           //  Remove single trailing "y" (if present)
  +"y Mc"                   //  Appended with "y Mc"
  +s.split("e?y$")[0]       //  Appended with the modified input, with "y" or "ey" removed
  +"face"                   //  Appended with "face"

Cosa succede se il primo carattere non è alfabetico? O forse possiamo aggiungere una regola al riguardo ...
— streetster

1
@streetster Ho appena chiesto a OP e sembra che l'input contenga solo lettere maiuscole e / o minuscole.
— Kevin Cruijssen,

1
~32-> 95per 1 byte salvato
— Olivier Grégoire

@ OlivierGrégoire Ho davvero bisogno di iniziare a imparare qualcosa in più sulle operazioni bit per bit ..>.>
— Kevin Cruijssen,

4

JavaScript, 103 96 94 byte

Primo passaggio abbastanza ingenuo in questo.

s=>(g=r=>s[0].toUpperCase()+s.slice(1).toLowerCase().split(r)[0])(/y$/)+`y Mc${g(/e?y$/)}face`

Provalo online


s =>${s=s[0].toUpperCase()+s.slice(1).toLowerCase().replace(/y$/,``)}y Mc${s.replace(/e?y$/,``)}face
— Benjamin Gruenbaum,

Uno in meno: s =>${s=s[0].toUpperCase()+s.slice(1).toLowerCase().replace(/y$/,'')}y Mc${s.replace(/e$/,``)}face
— Benjamin Gruenbaum,

Grazie, @BenjaminGruenbaum, ma il primo fallisce Donkeye il secondo per Face.
— Shaggy,


@Shaggy sono riuscito a ridurre la funzione g di alcuni caratteri :). puoi vedere la mia soluzione
— DanielIndie,

3

vim, 35 34 byte

Vu~Yp:s/ey$
:%s/y$
kgJiy Mc<ESC>Aface<ESC>

<ESC> è 0x1b

Ungolfed

Vu~                      # Caseify McCaseface
Yp                       # dup line
:s/ey$ 
:%s/y$                   # Get the suffixes right
kgJiy Mc<ESC>Aface<ESC>  # Join lines and add the extra chars

Provalo online!

Salvato 1 byte grazie a DJMcMayhem


1
Puoi fare Yinvece diyy
— DJMcMayhem


3

C ++ 14 (g ++), 181 171 148 147 134 byte

[](auto s){s[0]&=95;int i=1,b;for(;s[i];)s[i++]|=32;b=s[--i]-'y';return s+(b?"y":"")+" Mc"+(b?s:s.substr(0,s[i-1]-'e'?i:i-1))+"face";}

Nota che clang non lo compilerà.

Il merito va a Kevin Cruijssen e Olivier Grégoire per il &95trucco.

Grazie a Chris per aver giocato a golf 11 byte.

Provalo online qui .

Versione non golfata:

[] (auto s) { // lambda taking an std::string as argument and returning an std::string
    s[0] &= 95; // convert the first character to upper case
    int i = 1, // for iterating over the string
    b; // we'll need this later
    for(; s[i] ;) // iterate over the rest of the string
        s[i++] |= 32; // converting it to lower case
    // i is now s.length()
    b = s[--i] - 'y'; // whether the last character is not a 'y'
    // i is now s.length()-1
    return s + (b ? "y" : "") // append 'y' if not already present
    + " Mc"
    + (b ? s : s.substr(0, s[i-1] - 'e' ? i : i-1)) // remove one, two, or zero chars from the end depending on b and whether the second to last character is 'e'
    + "face";
}

Non conosco bene il C ++, ma puoi giocare a golf a 9 byte: provalo online 172 byte. Riepilogo delle modifiche: s[0]=s[0]&~32;a s[0]&=~32;; s[i++]=s[i]|32;a s[i++]|=32; e int i=1,n=s.length()-1,b;quindi hai solo bisogno di 1 int.
— Kevin Cruijssen,

Oh, e un altro byte rimuovendo lo spazio in#include<string>
— Kevin Cruijssen il

@KevinCruijssen grazie per averlo colto! Ho modificato.
— OOBalance,

È possibile salvare 11 byte non definendo ne semplicemente utilizzando il valore di iafter the while loop. Provalo online!
— Chris

@Chris Grazie! Sono riuscito a radere altri 2 byte.
— OOBalance

2

V , 38 36 32 byte

-5 byte grazie al quack @Cows

Vu~hy$ó[^y]$/&y
A Mc<esc>póe¿y$
Aface

<esc>è un carattere letterale di escape ed [^è codificato come\x84

Provalo online!


gu$può diventareVu
— Kritixi Lithos il

2
Poiché [^è un collegamento regex (vedi qui ), puoi usare 0x84 invece di [^salvare un byte. Allo stesso modo, \?può essere semplificato <M-?>per salvare un altro byte. E $a=>A
— Kritixi Lithos il


2

Python 3 , 117 114 byte

-3 byte grazie a Dead Possum

def f(s):s=s.title();return s+'y'*(s[-1]!='y')+' Mc'+([s,s[:-1],0,s[:-2]][(s[-1]=='y')+((s[-2:]=='ey')*2)])+'face'

Provalo online!


Il terzo elemento dell'elenco [s,s[:-1],'',s[:-2]può essere modificato in 0per salvare 1 byte.
— Dead Possum,

In 'y'*1 *1non è necessario. Altri 2 byte
— Dead Possum

Il passaggio da Python 3 a Python 2 e la sostituzione returncon printè più breve di 1 byte.
— Kevin Cruijssen,

2

JavaScript (Node.js) , 87 byte

  • grazie a @Shaggy per 5 riducendo 5 byte
s=>(g=r=>Buffer(s.replace(r,"")).map((x,i)=>i?x|32:x&~32))(/y$/)+`y Mc${g(/e?y$/)}face`

Provalo online!


2
Non è necessario nominare funzioni non ricorsive.
— Dennis,

1
Ben fatto. Non penso mai di usare Buffer, dovrò provare a ricordarlo per le sfide future. È arrivato a 87 byte per te.
— Shaggy,

2

K4 , 74 69 68 byte

Soluzione:

{$[r;x;x,"y"]," Mc",_[r:0&1-2/:"ye"=2#|x;x:@[_x;0;.q.upper]],"face"}

Esempi:

q)k)f:{$[r;x;x,"y"]," Mc",_[r:0&1-2/:"ye"=2#|x;x:@[_x;0;.q.upper]],"face"}
q)f each ("boat";"Face";"DOG";"Family";"Lady";"Donkey";"Player")
"Boaty McBoatface"
"Facey McFaceface"
"Dogy McDogface"
"Family McFamilface"
"Lady McLadface"
"Donkey McDonkface"
"Playery McPlayerface"

Spiegazione:

Scopri se gli ultimi caratteri sono uguali "ey", converti il ​​risultato in base-2 in modo da poter ignorare le parole che finiscono "e?". Indicizza in un elenco di numeri di caratteri da tagliare.

Riuscito a radere 5 byte dal mio codice per determinare se gli ultimi due caratteri sono in corso "ey"ma lottano per migliorarlo ...

{$[r;x;x,"y"]," Mc",_[r:0&1-2/:"ye"=2#|x;x:@[_x;0;.q.upper]],"face"} / the solution
{                                                                  } / lambda function
                                                            ,"face"  / join with "face"
                    _[                  ;                  ]         / cut function
                                           @[_x; ;        ]          / apply (@) to lowercased input
                                                0                    / at index 0
                                                  .q.upper           / uppercase function
                                         x:                          / save back into x
                                      |x                             / reverse x
                                    2#                               / take first two chars of x
                               "ye"=                                 / equal to "ye"?
                             2/:                                     / convert to base 2
                           1-                                        / subtract from 1
                         0&                                          / and with 0 (take min)
                       r:                                            / save as r
             ," Mc",                                                 / join with " Mc"
 $[r;x;x,"y"]                                                        / join with x (add "y" if required)

Bonus:

Porta a 67 byte in K (oK) :

{$[r;x;x,"y"]," Mc",((r:0&1-2/"ye"=2#|x)_x:@[_x;0;`c$-32+]),"face"}

Provalo online!


1
Qual è il punto nel K4 se la tua porta oK lo sconfigge?
— Zacharý,

Non pensavo che avrebbe funzionato, e la porta non funziona se il primo carattere non è in ordine alfabetico poiché sottraggo ciecamente 32 dal valore ASCII - non esiste un built-in "superiore".
— streetster

2

Rubino , 69 byte

->s{"#{(s.capitalize!||s)[-1]==?y?s:s+?y} Mc#{s.gsub /e?y$/,""}face"}

Spiegazione:

->s{                                                                } # lambda 
    "#{                                 } Mc#{                }face" # string interpolation
       (s.capitalize!||s) # returns string capitalized or nil, in that case just use the original string
                         [-1]==?y # if the last character == character literal for y
                                 ?s:s+?y # then s, else s + "y"
                                              s.gsub /e?y$/,"" # global substitute
                                                               # remove "ey" from end

Provalo online!


Potresti aggiungere un link TIO? Non conosco Ruby, ma s.capitalizesostituisce il precedente s? In caso contrario, lo fa /e?y$/gestire un banco di prova che termina in Y, EYo Eyin modo corretto?
— Kevin Cruijssen,

1
@KevinCruijssen s.capitalizevs s.capitalize!(diverse funzioni). s.capitalize!distrugge la vecchia versione.
— dkudriavtsev,

@KevinCruijssen Ho aggiunto un link TIO.
— dkudriavtsev,

@KevinCruijssen Anche aggiunta una spiegazione
— dkudriavtsev

Ah ok, grazie per la spiegazione e le informazioni su s.capitalize!. Mai programmato in Ruby, ma aggiungere un segno di spiegazione per sostituire il valore precedente è piuttosto interessante. +1 da me.
— Kevin Cruijssen,

2

Jstx , 27 byte

h</►yT↓►y/◙♂ Mc♀/◄eyg►yg/íå

Spiegazione

      # Command line args are automatically loaded onto the stack
h     # Title case the top of the stack
<     # Duplicate the top value on the stack twice
/     # Print the top value on the stack
►y    # Load 'y' onto the stack
T     # Returns true if the 2nd element on the stack ends with the top
↓     # Execute block if the top of the stack is false
  ►y  # Load 'y' onto the stack
  /   # Print the top value on the stack
◙     # End the conditional block
♂ Mc♀ # Load ' Mc' onto the stack
/     # Print the top value on the stack
◄ey   # Load 'ey' onto the stack
g     # Delete the top of the stack from the end of the 2nd element on the stack if it exists
►y    # Load 'y' onto the stack
g     # Delete the top of the stack from the end of the 2nd element on the stack if it exists
/     # Print the top of the stack
íå    # Load 'face' onto the stack
      # Print with newline is implied as the program exits

Provalo online!


Non ho mai visto questa lingua prima. Sembra interessante C'è documentazione?
— ricorsivo


Caspita, è davvero impressionante. Soprattutto per così poco tempo di sviluppo. Sono entusiasta di vedere dove va.
— ricorsivo

2

Rosso , 143 142 byte

func[s][s: lowercase s s/1: uppercase s/1
w: copy s if"y"<> last s[append w"y"]rejoin[w" Mc"parse s[collect keep to[opt["y"|"ey"]end]]"face"]]

Provalo online!

Ungolfed:

f: func[s][
   s: lowercase s                      ; make the entire string lowercase
   s/1: uppercase s/1                  ; raise only its first symbol to uppercase 
   w: copy s                           ; save a copy of it to w
   if "y" <> last s[append w "y"]     ; append 'y' to w if it doesn't have one at its end
   rejoin[w                            ; assemble the result by joining:
          " Mc"
          ; keep the string until "y", "ey" or its end
          parse s[collect keep to [opt ["y" | "ey"] end]]
          "face"
    ]
]

2

PHP: 132

<?php function f($s){$s=ucfirst(strtolower($s));return $s.(substr($s,-1)=='y'?'':'y').' Mc'.preg_replace('/(ey|y)$/','',$s).'face';}

Spiegazione:

<?php

function f($s)
{
    // Take the string, make it all lowercase, then make the first character uppercase
    $s = ucfirst(strtolower($s));

    // Return the string, followed by a 'y' if not already at the end, then ' Mc'
    // and the string again (this time, removing 'y' or 'ey' at the end), then
    // finally tacking on 'face'.
    return $s
        . (substr($s, -1) == 'y' ? '' : 'y')
        . ' Mc'
        . preg_replace('/(ey|y)$/', '', $s)
        . 'face';
}

2

Gelatina , 77 75 74 73 byte

2ḶNṫ@€⁼"“y“ey”S
ØA;"ØaF
¢y⁸µ¢Uyµ1¦
Çṫ0n”yẋ@”y;@Ç;“ Mc”
⁸JU>ÑTị3Ŀ;@Ç;“face

Provalo online!

Tutti i suggerimenti per il golf sono i benvenuti (e desiderati)!


2

Pyth, 36 34 byte

++Jrz4*\yqJK:J"e?y$"k+" Mc"+K"face

Provalo online!

Spiegazione:

++Jrz4*\yqJK:J"(e)?y$"k+" Mc"+K"face

  Jrz4                                  Set J to the titlecase of z (input)
           K:J"e?y$"k                   Set K to (replace all matches of the regex e?y$ in J with k (empty string))
         qJ                             Compare if equal to J
      *\y                               Multiply by "y" (if True, aka if no matches, this gives "y", else it gives "")
 +                                      Concatenate (with J)
                             +K"face    Concatenate K with "face"
                       +" Mc"           Concatenate " Mc" with that
+                                       Concatenate

Purtroppo questo non funziona, poiché l'ultimo caso di test fallisce.
— Zacharý,

Passa rz3a rz4per farlo funzionare correttamente per l'ultimo caso di test.
— hakr14

Oh spiacenti, lo aggiusterò: P
— RK.

2

Elisir , 112 110 107 106 byte

ora breve come java

fn x->x=String.capitalize x;"#{x<>if x=~~r/y$/,do: "",else: "y"} Mc#{String.replace x,~r/e?y$/,""}face"end

Provalo online!

Spiegazione:

x=String.capitalize x

Ottiene xcon il primo carattere in maiuscolo e tutti gli altri in minuscolo.

#{ code }

Valuta il codice e inseriscilo nella stringa.

#{x<>if x=~ ~r/y$/, do: "", else: "y"}

Concatena x con yse non termina con y(cioè non corrisponde alla regex y$).

#{String.replace x, ~r/e?y$/, "")}

Rimuove il finale eye il finale y.



1

Pyth, 60 59 byte SBCS

K"ey"Jrz4Iq>2JK=<2J=kK.?=k\yIqeJk=<1J))%." s÷   WZÞàQ"[JkJ

Suite di test

Essi non vengono visualizzati qui, ma tre byte, \x9c, \x82, e \x8csono nella stringa imballato tra il se ÷. State tranquilli, il link li include.

Traduzione di Python 3:
K="ey"
J=input().capitalize()
if J[-2:]==K:
    J=J[:-2]
    k=K
else:
    k="y"
    if J[-1]==k:
        J=J[:-1]
print("{}{} Mc{}face".format(J,k,J))
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.