Il gatto miagola"


31

cat va "Meow"

Conosciamo tutti il ​​concetto di catprogramma. L'utente digita qualcosa, viene ripetuto all'utente. Facile. Ma tutti i catprogrammi che ho visto finora hanno perso un fatto: a catdice "Meow". Quindi il tuo compito è quello di scrivere un programma che copi tutto STDINsu A STDOUT MENO che l'input sia cat, nel qual caso il tuo programma dovrebbe produrre cat goes "Meow".

punteggio

Questo è , quindi il tuo punteggio è il conteggio dei byte, con alcuni modificatori:

  • Se il tuo programma funziona con altri animali diversi da cat(ad es. cow: cow goes "Moo"), Per ciascun animale aggiuntivo: -10
  • Se il tuo programma non usa la parola "gatto": -15
  • Se il tuo programma risponde foxcon "Cosa dice la volpe": -25

Animali e suoni che vanno insieme:

cow goes moo duck goes quack sheep goes baa bees go buzz frogs go croak

Nient'altro in questo elencoÈ consentito .

Regole

  • Si applicano scappatoie standard
  • Non devi scrivere nulla a STDERR
  • È possibile utilizzare virgolette singole / senza virgolette anziché doppie virgolette.

Classifica

Ecco uno snippet di stack per generare sia una classifica regolare che una panoramica dei vincitori per lingua.

Per assicurarti che la tua risposta venga visualizzata, ti preghiamo di iniziare la risposta con un titolo, utilizzando il seguente modello Markdown:

## Language Name, N bytes

dov'è Nla dimensione del tuo invio. Se si migliora il punteggio, è possibile mantenere i vecchi punteggi nel titolo, colpendoli. Per esempio:

## Ruby, <s>104</s> <s>101</s> 96 bytes

Se si desidera includere più numeri nell'intestazione (ad es. Perché il punteggio è la somma di due file o si desidera elencare separatamente le penalità del flag dell'interprete), assicurarsi che il punteggio effettivo sia l' ultimo numero nell'intestazione:

## Perl, 43 + 2 (-p flag) = 45 bytes

Puoi anche rendere il nome della lingua un collegamento che verrà quindi visualizzato nello snippet della classifica:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes


16
Per i bonus: cosa dice la volpe?
Stewie Griffin,

1
Per i bonus: ogni animale aggiuntivo può essere singolare o le "api" devono sempre essere plurali, come nella tua lista?
Programma FOX


1
Invece di virgolette doppie, puoi usare quelle singole? Inoltre, puoi eseguire l'output su stderr?
Blu

Risposte:


17

Pyth, 231-255 = -24 byte

-24 * 10 animali extra, -15 per nessuna stringa "gatto"

pzI}zJv.Z"xÚ]Arà E¯âñMOÛ|°
Ø¢mÞ½`&ÉR¯'_ãPÍm1;ñÝ|,F ¹×z#½öÂ÷ÜAPúõMh#Ì©UOC *CѰk%¹ö´qÌzj,å<&{jàRFÖ(¥s    ñ`GÂ:çkô#ù\M+üqíéaw ÑuW6Lã,¶w/'87ö×_r]¢:jkz»ÚFÙ¦ÈcÅËØíëûÖOa¿Þµ´6 ø¡ãEþþ:"jk(" goes "N@JzN

Link al codice

pseudocodice

Auto assign z to input
print z
J = decompress animal-sound dict
if z in J:
    print " goes ", J[z], '"'

Animali che conosce:

{'hare': 'squeak', 'seal': 'bark', 'lion': 'growl', 'rook': 'hiss', 'sheep': 'baa', 'hamster': 'squeak', 'moose': 'bellow', 'grasshopper': 'chirp', 'rhinoceros': 'bellow', 'cat': 'meow', 'tiger': 'growl', 'stag': 'bellow', 'crow': 'caw', 'okapi': 'bellow', 'snake': 'hiss', 'cicada': 'chirp', 'badger': 'growl', 'dog': 'bark', 'cricket': 'chirp', 'tapir': 'squeak', 'bird': 'chirp', 'sparrow': 'chirp', 'lamb': 'baa', "frog": "croak", "raven": "croak"}

16
Sento che il bonus dovrebbe essere -10%, non -10 byte. Ciò darebbe un ritorno decrescente per prevenire abusi come questo. (E questo è il 10% moltiplicato ogni volta, non il 10% dell'originale aggiunto, altrimenti avresti bisogno solo di 10 animali per ottenere un punteggio di 0, non importa quanto tempo fosse il codice ...)
Darrel Hoffman

@DarrelHoffman Lo terrò a mente per tutte le sfide future.

Bene, mi hai fatto esplodere la testa con successo e non so più cosa dice la volpe. +1
kirbyfan64sos,

Il corvo impazzisce?
Magic Octopus Urn,

@carusocomputing Secondo wikipedia lo fa. Penso che vadano da squalksoli
Blue

7

TeaScript , 29-15 = 14 byte

Non usa la stringa cat.

xr(/^c\at$/,'$& goes "Meow"')

"Cosa dice la volpe" (lunghezza = 21) è più lungo del valore del bonus.


Il bonus volpe ora ne vale la pena!

5

CJam, 12 byte

q_:)"dbu"=" goes \"Meow\""*

Il programma è lungo 27 byte e non usa la parola cat( -15 byte ).

Provalo in linea nell'interprete CJam .

Come funziona

q_                e# Read all input and push a copy.
:)                e# Increment all code points of the copy.
"dbu"=            e# Push 1/0 if the result is/isn't "dbu".
" goes \"Meow\""* e# Repeat the string that many times.

10
Mi piace lo smiley:)
ETHproductions

4

APL (Dyalog) , = 13 byte

{⍵,' goes "Meow"'/⍨⍵≡⌽'tac'}

Input seguito da goes "Meow" se input equivale a tacinvertito.

Provalo online!

{...}  funzione anonima

⌽'tac' inverti la stringa (per ottenere il bonus di -15 evitando i personaggi cat )

⍵≡ Booleano per stabilire se l'argomento è identico a quello

' goes "Meow"'/⍨ usalo per filtrare la stringa (cioè restituisce una stringa vuota se falsa)

⍵, aggiungere all'argomento



3

JavaScript, 45-15 = 30/264 - 235 = 29

alert((s=(d='MeowBuzzSongMooMooCawBarkQuackCroakHissOinkBaaSingRoarLowCooCawBarkBaaHissCryRoarSingC\x61tBeeBirdCattleCowCrowDogDuckFrogHorseHogLambLarkLionOxPigeonRookSealSheepSnakeSwanTigerWhale'.split(/(?=[A-Z])/))[d.indexOf(i=prompt())-23])?i+' goes "'+s+'"':i)

Unico inconveniente: devi scrivere il nome dell'animale con la prima lettera in maiuscolo e il resto in minuscolo. Cerca di seguito un'altra versione che risolva questo problema. Questa versione sfugge al agatto con \x61e include il codice per i 22 animali extra da questo elenco (tutti gli animali ammessi che avevano parole abbastanza brevi per valerne la pena):

ronzio dell'ape 7
canto degli uccelli 8
bestiame muggito 9
mucca muggito 6
corvo caw 7
cane abbaia 7
anatra cacca 9
rana gracidola 9
sibilo di cavallo 9
maiale oca 7
agnello baa 7
allodola cantare 8
leone ruggito 8
bue basso 5
piccione coo 9
corvo torre 7
sigillo corteccia 8
pecore baa 8
sibilo di serpente 9
grido di cigno 7
ruggito di tigre 9
balena canta 9

(grazie al mio amico per avermi aiutato con il noioso compito di creare questo elenco)

Codice non golfato:

data = 'MeowBuzzSongMooMooCawBarkQuackCroakHissOinkBaaSingRoarLowCooCawBarkBaaHissCryRoarSingC\x61tBeeBirdCattleCowCrowDogDuckFrogHorseHogLambLarkLionOxPigeonRookSealSheepSnakeSwanTigerWhale'.split(/(?=[A-Z])/);

input = prompt();
index = data.indexOf(input);
sound = data[index-23];
result = sound ? input + ' goes "' + sound + '"' : input;
alert(result);

Prima versione, 45 byte - 15 bonus = 30

alert((i=prompt())=='\x63at'?i+' goes "Meow"':i)

Si, lo so. Sono passato dalle 30 alle 29 con TUTTO quel lavoro extra. È stato divertente!

Versione che consente l'input completo in minuscolo, 294 byte - 235 bonus = 59

alert((s=(d='MeowBuzzSongMooMooCawBarkQuackCroakHissOinkBaaSingRoarLowCooCawBarkBaaHissCryRoarSingC\x61tBeeBirdCattleCowCrowDogDuckFrogHorseHogLambLarkLionOxPigeonRookSealSheepSnakeSwanTigerWhale'.split(/(?=[A-Z])/))[d.indexOf((i=prompt())[0].toUpperCase()+i.slice(1))-23])?i+' goes "'+s+'"':i)

Ho anche provato a rimuovere il case dall'array di dati .join().toLowerCase().split(',')ma alla fine ha preso 297 caratteri.


modifica: virgolette fisse e maiuscole su miao (anche se la domanda non è coerente con le maiuscole)
Domino,

E ... il mio lavoro qui è finito, dimostrando che il bonus di -10 era appena sufficiente :)
Domino,

3

JavaScript, 81-20-15 = 46 byte 50-15 = 35 byte

(o=prompt()=="ca"+"t")&&o+=' goes "Meow"';alert(o)

Puoi rilasciare le doppie virgolette attorno a Meow .
giorno il

no, in realtà fa parte della domanda
Domino,

Che ne dici 'c\at'invece di 'ca'+'t'?
Gustavo Rodrigues,

alert({'c\at':'c\at goes "Meow"',fox:'What does the fox say'}[a=prompt()]||a). Perché non rilasciare nemmeno l'avviso? Restituisce già il risultato alla console.
Gustavo Rodrigues,

2

GNU sed, 37-15 = 22 byte

sed -r 's/^(\x63at)$/\1 goes "Meow"/'

sed '/ ^ c [a] t $ / s / $ / va "Meow" /' salva alcuni byte. Ma il nuovo bonus del 5% è inutile rispetto al bonus originale di 15 byte per non avere "gatto".
Glenn Randers-Pehrson,

@ GlennRanders-Pehrson Non più!

2

MATLAB, 58-15 = 43 byte

Abbastanza semplice, con bonus per non usare catnel codice:

x=input('');if isequal(x,'dbu'-1);x=[x ' goes "Meow"'];end;x

L'input deve essere indicato tra virgolette singole: ' ' .


Nella sua forma attuale, questo non viene emesso correttamente se 'cat' viene fornito come input. Probabilmente hai dimenticato x = all'interno dell'istruzione if.
slvrbld,

Ma ti darò anche un suggerimento per riconquistare questi byte più altri 2: sostituisci la tua intera istruzione if
slvrbld

@slvrbld, grazie per averlo notato, è successo dopo che ho fatto una modifica. A proposito: il tuo suggerimento non funziona per input che non sono 3 caratteri. =)
Stewie Griffin,

Ah, hai ragione. Ero troppo concentrato sul gatto e sulla volpe e mi sono dimenticato del resto.
slvrbld,

2

Javascript, 117 byte

for(c=0,s="bee.Buzz.bird.Song.c\at.Meow.cow.Moo.crow.Caw.dog.Bark.oxen.Low.owl.Who.rook.Caw.sheep.Baa.swan.Cry".split('.'),p=prompt(),a=![];c<s.length;c+=2){if(p==s[c])a=c}if(!a)alert(p=='fox'?'What does the fox say':p);else alert(s[a]+' goes "'+s[a+1]+'"')

Sicuramente non ho vinto qui, ma ho coperto molti animali extra.

Javascript, 31 byte

p=prompt();alert(p=='c\at'?p+' goes "Meow"':p)

2

HALT , 71-15 = 56 byte

1 IF "cat" 2 ELSE 3
2 TYPE "MEOW";HALT
3 SET 0;NEXT
4 INCREMENT;STORE 0

HALT è un linguaggio I (@Downgoat) progettato per l'elaborazione di stringhe, l'unico problema è che è un po 'lungo

formattato

1              IF "cat" 2 ELSE 3
2 TYPE "MEOW"; HALT
3 SET 0      ; GOTO 6
4 INCREMENT  ; STORE 0

2

Python 3, 81 70 55 46-15 = 31 byte

Grazie a Stewie Griffin per aver salvato 15 byte

Grazie a grc per aver salvato 8 byte.

Non usare la stringa catdà -15 byte.

y=input()
print(y+' goes "Meow"'*(y=="ca""t"))

1

JavaScript, 48-15 = 33 byte

Utilizza \x61come sostituto di ain cat.

i=prompt();alert(i=="c\x61t"?i+' goes "Meow"':i)

1

Perl, 46-15 = 31

$_=join'',<>;s/(?<=^ca)t$/t goes "Meow"/;print

1

Ruby, 49 46 50-15 = 35 byte

Abbastanza diretto immagino. Non usare il gatto.

$<.map{|l|puts l==?c+'at
'??c+'at goes "Meow"':l}

Modifica: grazie per @ w0lf per aver salvato 3 byte!


apparentemente non c'è bisogno di chop: ideone.com/lTpShD
Cristian Lupascu

@ w0lf "cat \ n"! = "cat" (almeno non funziona per me) Immagino che lo STDIN di ideone non abbia una nuova riga finale
Peter Lenkefi,

Abbastanza giusto, vedo dove il mio esempio era sbagliato. Allora la vostra potrebbe considerare di fare questo per accorciare il codice.
Cristian Lupascu,

@PeterLenkefi, ci sono ancora alcuni gatti nel tuo codice ... Hai dimenticato di aggiornarlo o ...?
Stewie Griffin,

@StewieGriffin Accidenti ho fatto! Il mio multitasking non è al top oggi. Comunque tra 5 minuti lo aggiornerò di nuovo.
Peter Lenkefi,

1

PHP, 1204 - (10 * 64) - 15-20 = 529 byte

<?php $i = $argv[1];$s = json_decode(gzuncompress(hex2bin("78da555351b2db200cbc8a27dfee057a1b192bc018104f40dcbccebb7b25d9499d8fcc588b10abddcddf1b64e4e8a04c3bd1eac86db7df3774e136dfa0744c5451805688bb400bac1e5900cfb42703ba1e3bc6e3ce82dabe8cef6f2d22af52b910b95ad93b72d173a22c8083f4d0f63bc75c131aa2e332d2ae45886e43ed7769082f438afc52027df46b20182af457b83c24537ad2c199484b99f6fe669dd9afcd6cc70ef67972a03bb8c10915abb12aa995bc7206deac48555818a9e80ea46cf8142020fe0aa0ccd761327e0db00e046f745426d0c531610d22af609d47aea8dade91d998ad447aebcef6aef0b32d7d64b8df4ddd84a0173c436b816a35475efbf8110bc254a3bf6a1420b76e7d1788f1a346ceb14f8e61b98c0bc44ddb0a46afe284582b55ea9087e1af2004236b3999278a452726c8cb8bef3c2d0086b14ad362f1f3b4032fe67b8aa59cae88742744aab26ccff3f47a2583af11ad0f344c0a1119910553b2d864929562270577b14a87d10635ea351a3e0895572ffd11f0f8ac0867fadf36898668249c65a732448e387de481c1c96931272598863c8ed09ec6b17020874c5792ac1e5bea8ee234c7c238df1a42faff449360552b55c05660d3d5426c4dcb0a7c26f874ac75f0d7a7da0e079da7145d74f848418fc71f5a75d652947a4e1edd469715fae023e29e96c3b0c748027e847a87c4ef4cc893820438722f666bc9a6cb69facf3f28e87499")));echo array_key_exists($i,$s)?"$i goes {$s->$i}":($i=="fox"?"What does the $i say":$i);

Uso un array compresso di suoni animali codificato in gz json. Ciò significa che funziona con tutti i 65 animali ammessi, ma la mia sceneggiatura è enorme. Funziona anche con fox e non contiene la parola gatto.


1

MATLAB, 46 byte

regexprep(input(''),'^cat$','cat goes "Meow"')

Certamente banale. L'input deve essere indicato tra virgolette singole.


Non sono sicuro, ma penso che in ans = .. genere non sia accettato, se la sfida è stampare qualcosa. Non sono sicuro che sia un consenso, ma è abbastanza comune da usare dispo qualcosa di simile.
Stewie Griffin,

+1 però, per essere più corto del mio =)
Stewie Griffin,

1

Beam , 208 206-15 = 191 byte

Non una voce competitiva, ma un po 'divertente da fare. Controlla la prima per le lettere dell'input rispetto cat. In caso di mancata corrispondenza, si accederà al programma cat standard. Se corrisponde, verrà aggiuntogoes "Meow"

'''''''''>`\/n@>`)'''>`++\
/++++++++++/r /SP''+(++++/
\+)'PSrn@--S/ \rn@`>`)rn'''''>`++++++)++@P'p++++@'p-----@`p++@'p-@``p@++@'''''>`+++++++++)--@'p++@'p-----@++++++++@``p++@H
/@<  (`<     < `<    ''<
>ruH

1

Java = 222 byte (compresso)

public class A {public static void main(String[] args) {Scanner a=new Scanner(System.in);for(;;){String b=a.nextLine();if(!b.equalsIgnoreCase("cat"))System.out.println(b);else {System.out.println("meow");System.exit(0);}}}

O potrei decomprimerlo.

Lotto = 52 byte

set /p k=
if "k"=="cat" (echo cat) ELSE (echo %k%)

1

Javascript: 48 caratteri, 48 byte

function(s){return (s=="cat")?"cat goes meow":s}

Test

=>"Cane"

<="Cane"

=>"gatto"

<="il gatto miagola"


Good work! You could drop the parentheses around s=="cat". Also, the cat's string is supposed to be cat goes "Meow", so 'function(s){return s=="cat"?'cat goes "Meow"':s} is completely valid.
ETHproductions

If you wanted to save even more, you could use ES6: s=>s=="cat"?s+' goes "Meow"':s (30 bytes)
ETHproductions

@ETHproductions OOooh, that's good! I don't know that kind of syntax though, a link perhaps?
Fuzzyzilla

@Fuzzyzilla it's part of a new version of JavaScript called "ES6", link to the new function syntax and overview. Here are also tips for ES6 and tips for JavaScript in general
Downgoat

1

Haskell, 52-15 = 37 bytes

c"\99at"="\99at goes \"Meow\""
c s=s
main=interact c

Using \99 as a substitute for c in “cat” so as to get the 15 bytes bonus.


1

O, 22 16 14 bytes

29 bytes - 15

Q"tac"`J=J" goes \"Meow\""+Q?

It's long and can be golfed more



1

Pyth, 82-95 = -13 bytes

+z*}zKc."atÜiÃ'4ãl¾Eªîiû<-È&e"\jjk[d"goes"dNr@c."bw««[áÅ3ÏB"\c%x`Kz3 3N

I finally got around to converting my new functional Python 2 entry to Pyth. It doesn't beat the top contender. Turns out zipping together more animals into a larger dictionary reduces score faster than cleverly associating animals with sounds. This supports 8 animals in addition to cat: rhino, okapi, moose, lion, tiger, badger, hippo, and stag.

Try it online


1

Japt, 25-15=10 24-15 = 9 bytes

First time trying Japt:

N¦`¯t`?N:`¯t goƒ \"´ow\"

ƒ should be replaced with unprintable character U+0083 Compiles to:

N!="cat"?N:"cat goes \"meow\""

Old solution:

N¥`¯t`?`¯t goƒ \"´ow\"`:N

Try it here


Pretty nice! Sorry the backslashes are necessary, I thought I had fixed that.
ETHproductions

Since the code contains an unprintable character, which Markdown discards, could you please add a link?
ETHproductions

Added the link, also why does U+0083 get replace U+0192 or ƒ when you run this snippet: "\u0083".charCodeAt()
Generic User

I have no clue. I can't seem to reproduce this.
ETHproductions

1

Pyth, 26-15 (no "cat") = 11 bytes

My first ever Pyth program!

Iqz_"tac"+z" goes meow";Ez

Try it here

Explaination

   _"tac"                   # Reverse the string "tac"
Iqz                         # If the input equals "tac" reversed
         +z" goes meow";    # Append " goes meow"
                        Ez  # Else, use the input.
                            # Implicit: print the input, if it's used.

1

C++11, 316 - 11*10 - 15 = 191 bytes

#include <map>
#define t(a,b){#a,#b},
using s=std::string;int main(){std::map<s,s>m{t(cow,moo)t(crow,caw)t(dog,bark)t(hog,oink)t(lark,sing)t(lion,roar)t(oxen,low)t(rook,caw)t(seal,bark)t(sheep,baa)t(swan,cry){"c""at","meow"}};s l;while(int i=~getchar())l+=~i;printf("%s",(m[l]==""?l:l+" goes \""+m[l]+'"').c_str());}

Compiles well with VisualStudio. GCC wants me to #include <string> and #include <cstdio>. It would be shorter if I wouldn't go for bonuses, but I still hope author revises bonuses. I can't think of language where defining cow -> moo or so is way way shorter than 10bytes. Mine cost 3+key+value bytes for additional animal and flat 22+17 bytes for defining structure and so.

Ungolfed

#include <map>

#define t(a, b) { #a, #b },
using s = std::string;
int main()
{
    std::map<s, s> m{
        t(cow,moo)
        t(crow,caw)
        t(dog,bark)
        t(hog,oink)
        t(lark,sing)
        t(lion,roar)
        t(oxen,low)
        t(rook,caw)
        t(seal,bark)
        t(sheep,baa)
        t(swan,cry)
        { "c""at", "meow" }
    };
    s l;
    while (int i = ~getchar())
        l += ~i;
    printf("%s", (m[l] == "" ? l : l + " goes " + m[l]).c_str());
}

"t(crow,caw)" has a length of 11. So getting rid of that to "t(swan,cry)" would drop 14 bytes. And admittedly make it less fun :(
Noodle9

@user, As I said, I still hope author revises bonuses.
Zereges

You should state C++11 in the headline. Python 2 and 3 are also always distinct noted. While the using is no big deal, the initializer list is.
Karl Napf

@KarlNapf Thanks for pointing that out.
Zereges

You can also change #include <map> to #import<map> for -2 bytes. The space before < can be omitted and #import throws some warnings but is accepted be GCC and MSVC
Karl Napf

0

Pyth, 31 - 15 = 16 bytes

You can try it out here

In+C99"at"zz;E+z" goes \"Meow\"

Explaination:

I                                # If-statement
 n                               # not equal
  +C99"at"                       # Adds the char 99 with the string "at" = "cat"
          z                      # z, the user input
           z                     # Print the user input
            ;                    # Ends all open parentheses
             E                   # Else-statement
              +z" goes \"Meow\"  # Adds ' goes "Meow"' to z and prints the result

1
C99 can be replaced with \C. It's still +\C"at", so you can keep the bonus.
clap

0

C, 76 bytes

main(){char a[99];gets(a);printf("%s%s",a,strcmp(a,"cat")?"":" goes meow");}

0

PHP, 70-15 = 55 bytes

<?=$l=rtrim(stream_get_contents(STDIN),~òõ),$l==~œž‹?~ߘšŒßݲšˆÝ:'';

(saved as ISO-8859-1)

Uses inverted undefined constants as string literals:

  • ~òõ == "\r\n"
  • ~œž‹ == 'cat'
  • ~ߘšŒßݲšˆÝ == ' goes "Meow"'

Everything is combined in a single echo statement, shorthanded with <?=

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.