CHIAVE BLOCCATA FIASCO


25

Alcuni dei tuoi dipendenti hanno le chiavi maiuscole rotte e sei troppo economico per sostituirle. Aiutali creando il programma più breve possibile per correggere il loro lavoro! Converti semplicemente ogni carattere in una determinata stringa da maiuscolo a minuscolo e viceversa ... ma c'è una svolta!

Sei anche molto eccitato per Natale! Quindi lascerai un piccolo "bug" che non corregge le lettere che si trovano nelle sequenze di Christmas(senza distinzione tra maiuscole e minuscole).

Ingresso

Per l'input utilizzerai una singola stringa (o matrice di byte) che può contenere newline e ascii tra 0x20 e 0x7e ( - ~). Non devi preoccuparti dei ritorni a capo o di altri caratteri nella stringa.

Produzione

L'output dovrebbe contenere solo la stringa fornita con i caratteri maiuscoli e minuscoli scambiati (e il bug natalizio ovviamente!). Può contenere fino a un ulteriore spazio bianco finale.

Bug di Natale

Spieghiamo questo con un esempio:

Input: i CAN HARDLY WORK LIKE THIS please GET ME A NEW KEYBOARD FOR cHRISTMAS
Output: I Can HaRdly work lIke thiS PLEASE geT Me A new keyboard for ChriStmas

cancontiene "c" che è la prima lettera di Natale, quindi non è cambiata. La lettera successiva in Christmasè "h", che è in hardly(che contiene anche la "r"), quindi non è cambiata, ecc. ChristmasStessa ha solo una lettera invariata perché quando il codice arriva lì, sta effettivamente cercando "s", non "c".

Una volta trovata la sequenza, dovrebbe ricominciare tutto da "c" e ricominciare da capo Christmas. Quindi ChristmasChristmasrimarrebbe invariato.

Casi test

Input: Hello World!
Output: hELLO wORLD!

Input: I like pie :)
Output: i LIKE PIE :)

Input: hELP my KeYboarD
       iS BROKEN
Output: Help MY kEyBOARd
        Is broken

Input: cHRISTMAS IS COMING REALLY SOON!
Output: cHRISTMAS is Coming really soon!

Input: C is the first letter in cHRISTMAS
Output: C IS ThE FIrST LETTER iN ChriSTMAS

Vincitore

Questo è quindi vince la risposta più breve!


5
Il fatto che "nessuna soluzione integrata risolva la maggior parte della sfida" è una restrizione piuttosto strana. E il "caso di scambio" causerà davvero così tanti problemi quando metà della sfida è identificare quali lettere non sono in "Natale"?
ATaco,


@ATaco, l'ho aggiunto all'ultimo minuto a causa del feedback sulla sandbox, sono d'accordo, quindi l'ho rimosso.
redstarcoder,

Inoltre, Test case 3, hai scambiato la prima h, quando è Natale.
ATaco,

@ATaco, cerca in Christmassequenza, quindi "h" viene ignorato finché non trova "c", quindi cerca "h", quindi "r", ecc.
redstarcoder

Risposte:


9

05AB1E , 16 byte

Grazie a Emigna per aver salvato un byte e risolto un bug!

vyÐl'ŒÎ¾èQi¼ëš}?

Spiegazione:

vy                # For each character in the string...
  Ð               #   Triplicate that character
   l              #   Convert to lowercase
    'ŒÎ           #   Compressed version of "christmas"
       ¾          #   Push the counting variable (let's call this N)
        è         #   Get the nth character of "christmas", with modular indexing
         Qi   }   #   If equal...
           ¼      #      N += 1
            ë     #   Else...
             š    #      Swapcase
               ?  #   Print that character

Utilizza la codifica CP-1252 . Provalo online!


1
Funziona con le newline?
redstarcoder

@redstarcoder Oops, non è così. Ora è riparato.
Adnan,

2
Sembra proprio tinsel. : D
Tito

1
L'output non è corretto (prova ad esempio a Natale come input), ma se lo rimuovi udovrebbe funzionare.
Emigna,

1
@Izzy 05ab1e esiste da molto, molto tempo.
Pavel,

5

V , 38 , 36 byte

ÄVumaOchristmasòÉf2x`a@"maj~HòHdjV~

Provalo online! (contiene input e output previsti per il confronto)

Quando l'ho visto per la prima volta, ho pensato che sarebbe stato estremamente facile. Infatti, se non fosse per il bug "natale", questo sarebbe solo 2 byte: V~. Il bug natalizio lo rende significativamente più difficile, per una risposta molto confusa.

Come al solito, ecco un hexdump:

00000000: c456 756d 614f 6368 7269 7374 6d61 731b  .VumaOchristmas.
00000010: f2c9 6632 7860 6140 226d 616a 7e48 f248  ..f2x`a@"maj~H.H
00000020: 646a 567e                                djV~

Mi piacerebbe saperne di più su V.
ckjbgames,

@ckjbgames Fantastico, sarei felice di rispondere a tutte le tue domande! Puoi sempre chiamarmi nella sala da golf . In questo momento sto lavorando per rendere V un po 'più facile da imparare / creare un tutorial.
DJMcMayhem

4

PHP, 113 110 102 byte

while($o=ord($c=$argv[1][$i++]))echo chr(32|$o==ord(christmas[$k%9])?$o|0&$k++:ctype_alpha($c)*32^$o);

accetta input dal primo argomento della riga di comando. Corri con -r.

abbattersi

while($o=ord($c=$argv[1][$i++]))// loop through string characters
    echo chr(
        32|$o==ord(christmas[$k%9]) // if $c equals next character in "christmas"
            ?$o|0&$k++              // no change, increase "christmas" index
            :ctype_alpha($c)        // else if $c is a letter
                    *32^$o          // toggle bit 5 of the ascii code
        );

2

MATL , 36 30 byte

"@tk'schristma'H)=?HQXHx}Yo]&h

Le stringhe con newline devono essere definite concatenando con il codice ASCII 10(vedere esempio nel collegamento con i casi di test).

Provalo online! Oppure verifica tutti i casi di test .

Spiegazione

"              % Implicit input of a string. For each character in that string
  @            %   Push current character
  tk           %   Duplicate and convert to lowercase
  'schristma'  %   Push string. This is 'Christmas' in lowercase and circularly
               %   shifted such that the 'c' is in the second position
  H            %   Push contents of clipboard H, which is initiallized to 2.
               %   This value will be gradually increased when a new character
               %   from the the sequence is found
  )            %   Get character from 'schristma' at that (modular) position
  =            %   Are they equal?
  ?            %   If so
    HQ         %     Push contents of clipboard H and add 1
    XHx        %     Copy into clipboard K and delete
  }            %   Else
    Yo         %     Change case
  ]            %   End
  &h           %   Concatenate stack contents horizontally. This gives a string 
               %   with all characters processed up to now
               % Implicit end. Implicit display


2

Perl 6 , 84 byte

{my $i=0;[~] (.lc~~"christmas".comb[$i%9]??(++$i&&$_)!!.ord>90??.uc!!.lc for .comb)}

2

C # 197 byte

Non vincerò con questo, ma speriamo che la più piccola implementazione C # che funzioni ...

string C(string s){int i=0,j=0;var r="";for(;i<s.Length;){char c=s[i++],o=(char)32;if(c=="christmas"[j]|c=="CHRISTMAS"[j])j=j>7?0:j+1;else if(c>64&c<91)c+=o;else if(c>96&c<123)c-=o;r+=c;}return r;}

Spiegazione:

string C(string s)
{
    // define our two index ints
    // i for indexing across the input string
    // j for indexing across christmas
    int i = 0, j = 0;

    // r is our return string
    var r = "";

    // declare our loop
    // skip the initialisation and afterthought
    for (; i < s.Length;)
    {
        // get our current character c, and increment index i
        // initial our offset char o (difference between upper and lower case)
        char c = s[i++], o = (char)32;

        // check if c is the current character in our christmas bug
        if (c == "christmas"[j] | c == "CHRISTMAS"[j])
            // increment j (or reset to 0)
            j = j > 7 ? 0 : j + 1;

        // else if c is an upper case char
        else if (c > 64 & c < 91)
            // add our offset to make it lower case
            c += o;

        // else if c is lower case
        else if (c > 96 & c < 123)
            // subtract our offset to make it upper case
            c -= o;

        // append c to our return string r
        r += c;
    }

    return r;
}

2

JavaScript, 122 118 114 107 104 93 byte

f=
s=>s.replace(/./g,c=>(k=c.toLowerCase())=='christmas'[i%9]?++i&&c:k!=c?k:c.toUpperCase(),i=0)


F=s=>console.log(f(s))
F(`Hello World!`)
F(`I like pie :)`)
F(`hELP my KeYboarD
       iS BROKEN`)
F(`cHRISTMAS IS COMING REALLY SOON!`)
F(`C is the first letter in cHRISTMAS`)

  • 11 byte di sconto grazie @Neil.

Non puoi usare k!=c?k:c.toUpperCase()per salvarti qualche byte?
Neil,

1

Perl 6 , 80 byte

{my$i=0;S:g{.?<!{'christmas'.comb[$i%9]eq$/.lc&&++$i}>}=$/eq$/.lc??$/.uc!!$/.lc}

Provalo

{   # bare block lambda with implicit parameter 「$_」

  my $i = 0;             # counter

  S                      # substitute and return ( implicitly against 「$_」 )
  :global
  {
    .                    # any char
    ?                    # work around a bug where 「$/」 doesn't get set

    <!{                  # fail this match if this block returns True
      'christmas'.comb\  # a list of the characters of 「christmas」
      [ $i % 9 ]         # grab a char from the list
      eq                 # is it equal to
      $/.lc              # the lowercase version of the char
      &&                 # if so
      ++$i               # increment 「$i」 ( result is True )
    }>

  }

  =                      # for each matched char

  $/ eq $/.lc            # is it lowercase?
  ?? $/.uc               # the uppercase it
  !! $/.lc               # otherwise lowercase it
}

Non credo che omettere lo spazio my $i=0;sia legale. E non sarei sorpreso se ci fossero più errori di sintassi relativi agli spazi bianchi.
bb94

1
@ bb94 Ho letteralmente incluso un collegamento a un sito che eseguirà il codice. Se non credi che funzionerà, perché non provarlo. Voglio dire, ho scritto $/ eq $/.lcpiuttosto che in $/.lc eq $/modo da poter rimuovere lo spazio prima eq.
Brad Gilbert b2gills,

@ bb94 Posso confermarlo lavorando sul compilatore collegato.
redstarcoder,

1

Java 7, 200 byte

String c(char[]a){String r="";int i=0,s;Character l='a';for(char c:a)if((s="christma".indexOf(l=l.toLowerCase(c)))==i|i>7&s==4){r+=c;i=i>7?0:i+1;}else r+=l.isUpperCase(c)?l:l.toUpperCase(c);return r;}

Brutto, ma funziona .. Sicuramente senza dubbio si può giocare a golf di più .. Sono arrugginito ..

Ungolfed:

String c(char[] a){
  String r = "";
  int i = 0,
      s;
  Character l = 'a';
  for(char c : a){
    if((s = "christma".indexOf(l = l.toLowerCase(c))) == i) | i > 7 & s == 4){
      r += c;
      i = i > 7
           ? 0
           : i+1;
    } else{
      r += l.isUpperCase(c)
       ? l
       : l.toUpperCase(c);
    }
  }
  return r;
}

Codice di prova:

Provalo qui.

class M{
  static String c(char[]a){String r="";int i=0,s;Character l='a';for(char c:a)if((s="christma".indexOf(l=l.toLowerCase(c)))==i|i>7&s==4){r+=c;i=i>7?0:i+1;}else r+=l.isUpperCase(c)?l:l.toUpperCase(c);return r;}

  public static void main(String[] a){
    System.out.println(c("i CAN HARDLY WORK LIKE THIS please GET ME A NEW KEYBOARD FOR cHRISTMAS".toCharArray()));
    System.out.println(c("Hello World!".toCharArray()));
    System.out.println(c("I like pie :)".toCharArray()));
    System.out.println(c("hELP my KeYboarD\niS BROKEN".toCharArray()));
    System.out.println(c("cHRISTMAS IS COMING REALLY SOON!".toCharArray()));
    System.out.println(c("C is the first letter in cHRISTMAS".toCharArray()));
  }
}

Produzione:

I Can HaRdly work lIke thiS PLEASE geT Me A new keyboard for ChriStmas
hELLO wORLD!
i LIKE PIE :)
Help MY kEyBOARd
Is broken
cHRISTMAS is Coming really soon!
C IS ThE FIrST LETTER iN ChriSTMAS

2
Java batte Haskell e C #!
Pavel,

1

Python 100 byte

def a(s,i=0,g=''):
 for c in s:a=c.lower()=='christmas'[i%9];i+=a;g+=[c.swapcase(),c][a]
 return g

1

Rubino, 63 + 1 = 64 byte

Usa la -pbandiera.

i=0;gsub(/./){|c|c=~/#{"christmas"[i%9]}/i?(i+=1;c):c.swapcase}

0

C # 239 caratteri

var s=Console.ReadLine().ToCharArray();int j=0,i=0;var c="christmas";for(;j<s.Length;j++)if(s[j]==c[i%9]|s[j]==(c[i%9]-32))i++;else if(s[j]>64&s[j]<91)s[j]=(char)(s[j]+32);else if(s[j]>96&s[j]<123)s[j]=(char)(s[j]-32);Console.WriteLine(s);

versione più esplicita:

var s = Console.ReadLine().ToCharArray();
int j = 0,i = 0;
var c = "christmas";
for (var j = 0; j < s.Length; j++)
   if (s[j] == c[i%9]|s[j] == (c[i%9] - 32))// non case sensitive compare with c 
      i++;//next char in christmas
   else
      if (s[j] > 64 & s[j] < 91)//if between A and Z
         s[j] = (char)(s[j] + 32);//convert to a-z
      else
         if (s[j] > 96 & s[j] < 123)//if between a and z
            s[j] = (char)(s[j] - 32);//convert to A-Z
Console.WriteLine(s);

questa è una soluzione abbastanza ingenua e probabilmente può essere migliorata (forse possiamo consentire la conversione implicita in char?).

presuppone di essere all'interno di una funzione, legge dalla console (stdin) e scrive su di essa (stdout).

modifica: Char.IsUpper (s [j]) è 2 byte più lungo di s [j]> 64 && s [j] <91, Char.ToUpper è anche più lungo della mia versione.


0

Haskell, 222 207 byte

import Data.Char
s=(+(-65)).ord
f=(`divMod`32).s
l=[['a'..'z'],['A'..'Z']]
c=cycle$map s"CHRISTMAS"
k _[]=[]
k(a:b)(x:y)|isAlpha x=let(d,m)=f x in if(m==a)then(x:k b y)else(l!!d!!m:k(a:b)y)|1>0=x:k(a:b)y
main=interact$k c

aggiornamento:

import Data.Char
s=(+(-65)).ord
k _[]=[]
k(a:b)(x:y)|isAlpha x=let(d,m)=s x`divMod`32 in if(m==a)then(x:k b y)else([['a'..'z'],['A'..'Z']]!!d!!m:k(a:b)y)|1>0=x:k(a:b)y
main=interact$k$cycle$map s"CHRISTMAS"

Come funziona:

s=(+(-65)).ord

sx = valore ASCII di x - valore ASCII di 'A'

f=(`divMod`32).s

f (sx) = (0, sx) per le maiuscole, (1, (s x-32)) per le lettere minuscole

l=[['a'..'z'],['A'..'Z']]

elenco parallelo di lettere, indicizzabile per f (minuscolo-> 1-> maiuscolo, maiuscolo-> 0-> minuscolo)

c = cycle $ map s "CHRISTMAS"

elenco infinito dei valori ascii del natale maiuscolo ripetuto

k _ []=[]

caso base

k (a:b) (x:y) | isAlpha x = let (d,m) =f x
                             in if m == a
                                then x : k b y
                                else (l!!d)!!m : k (a:b) y
              | 1 > 0 = x : k (a:b) y

restituisce caratteri non alfanumerici e conserva la lettera se il suo valore s è lo stesso della lettera di Natale corrente (passando alla lettera successiva), altrimenti convertilo nell'altro caso e procedi

main=interact$k c

IO

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.