Perché? Per compiacere il ricco programmatore!


21

Hai mai desiderato chiedere al compilatore "Perché?" Molti di noi sono rimasti frustrati quando il codice non funziona come dovrebbe. Mathworks ha quindi implementato una simpatica piccola funzione why, che risponde alla domanda. Per dare alcuni esempi da MATLAB:

why
The programmer suggested it.

why
To fool the tall good and smart system manager.    

why(2)
You insisted on it.

why(46)
Bill insisted on it.

Il tuo compito è implementare la whyfunzione nella tua lingua. La funzione dovrebbe funzionare con e senza un argomento di input (in alternativa utilizzare input 0o -1). La funzione deve essere denominata why(oppure, la scrittura why(n)in STDIN dovrebbe comportare la stampa della stringa appropriata).

Se non viene fornito alcun argomento o l'argomento è zero o negativo, la stringa di output deve essere una frase casuale e valida. Quindi, ci dovrebbe essere una funzione why, why(), why(0)o why(-1)che i rendimenti una frase casuale.

Se nviene fornito un argomento di input (argomento della funzione, non STDIN), l'output dovrebbe essere l'ennesima stringa (definita di seguito). Quindi, why(1)dovrebbe sempre produrre (stampare / visualizzare) lo stesso risultato.

Le frasi sono costruite come segue (Tipo 1, Tipo 2 e Speciale). Tutte le frasi finiscono con !.

"Person" "ending" !
"Verb" "adjective" "Person" !
A list of special cases

L'elenco delle persone:

Stewie
Peter
Homer
The programmer
The system manager
You

L'elenco dei finali:

suggested it
insisted on it
did it

L'elenco dei verbi sono:

To fool
To satisfy
To please

L'elenco degli aggettivi:

the smart
the bald
the tall
the rich
the stupid

L'elenco dei casi speciali:

How should I know?
Stop asking!
Don't ask!

Il modo per selezionarne uno numerato è:

Tipo di frasi:

Odd number => Type 1
Even number => Type 2
n % 7 = 0 => Type 3 (% is the modulus operator)

Nomi: l'ennesimo nome è definito usando il modulo (%).

n = 1:   1 % 7  => Stewie
n = 2:   2 % 7  => Peter
...
n = 6:   6 % 7  => You
n = 7:   7 % 7  => How should I know?
n = 11:  11 % 7 => The programmer
n = 14:  14 % 7 => Stop asking!
n = 21:  21 % 7 => Don't ask!

Endings: anche l'ennesimo finale è definito usando il modulo. Supponiamo che i finali (1, 2 e 3) siano elencati come (1 2 2 3). Poiché i numeri sono sempre dispari, utilizzare((n+1)/2 % 4)

n = 1:    ((1+1)/2 % 4)  => suggested it
n = 3:    ((3+1)/2 % 4)  => insisted on it
n = 13:   ((13+1)/2 % 4) => did it

Aggettivi: l'ennesimo aggettivo è definito usando il modulo. Poiché i numeri sono sempre pari, utilizzare:(n % 10)/2

n = 2:   (2 % 10)/2 => Smart
n = 6:   (6 % 10)/2 => The tall
...

Verbi: anche l'ennesimo verbo viene definito usando il modulo. Supponiamo che i verbi (1, 2 e 3) siano elencati come (1 2 2 3)Dato che i numeri sono sempre anche per i verbi, usa(n % 8) / 2

n = 2:   (2 % 8)/2 => To fool
n = 4:   (4 % 8)/2 => To satisfy
n = 6:   (6 % 8)/2 => To satisfy
n = 8:   (8 % 8)/2 => To please

Ora, il modo di crearne uno casuale dovrebbe essere abbastanza semplice, basta selezionare un casuale n.

Qualche esempio:

why
You suggested it!

why
To fool the tall Homer!

why
Don't ask!

why(1)
Stewie suggested it!

why(14)
Stop asking!

why(8)
To please the rich Stewie!

Si applicano le regole standard per il golf. Verrà selezionato un vincitore una settimana dal giorno in cui è stata pubblicata la sfida.


scrivendo perché nello stdin dovrebbe restituire la stringa con cui potrei essere in grado di lavorare con quello. Deve essere in minuscolo whyo sarebbe WHYaccettabile?
Dennis,

Le lettere minuscole e maiuscole vanno entrambe bene.
Stewie Griffin,

Anche i Endings non dovrebbero /2funzionare. Questo dà valori frazionari. 13dovrebbe anche essere insisted(14/2 = 7% 4 = 3 = 2 ° di insistito).
Jonathan Leech-Pepin,

3
Importa se finisci con casi come quelli the rich The programmerdovuti a quello specificato the?
Jonathan Leech-Pepin,

1
@StewieGriffin Le parole Thee Tonelle tue liste dovrebbero probabilmente essere minuscole per corrispondere ai tuoi esempi ...
mbomb007

Risposte:


5

JavaScript (ES6) 345

Non sono sicuro dei numeri, ma ecco il mio tentativo.

Prova a eseguire lo snippet di seguito in un browser conforme a EcmaScript.

why=n=>(n<1?n=Math.random()*840|0:0,s="suggested,insisted on,did,fool,satisfy,please,stupid,smart,bald,tall,rich,Don't ask!,How should I know?,Stop asking!,Stewie,Peter,Homer,programmer,system manager,You".split`,`,n%7?(p=s[n%7+13],n&1?(p>'a'?'The ':'')+p+` ${s['2011'[-~n/2%4]]} it!`:`To ${s['5344'[n%8/2]]} the ${s[n/2%5+6]} ${p}!`):s[11+n%3])  

for(o='',i=0;++i<1e3;)o+=i+':'+why(i)+'\n';O.innerHTML=o

function test() { R.innerHTML=why(+I.value) }

// Less golfed

WHY=n=>(
  n=n<1?Math.random()*999|0:n,
  s=["suggested", "insisted on", "did", "fool", "satisfy", "please",
     "stupid", "smart", "bald", "tall", "rich",
     "Don't ask!", "How should I know?", "Stop asking!",
     "Stewie", "Peter", "Homer", "programmer", "system manager", "You"],
  n%7
    ? ( p=s[n%7+13],
        n&1
        ? (p>'a'?'The ':'')+p+` ${s['2011'[-~n/2%4]]} it!`
        : `To ${s['5344'[n%8/2]]} the ${s[n/2%5+6]} ${p}!`)
    : s[11+n%3]
)  
#O { height:300px; width:50%; overflow:auto }
#I { width:2em }
Why(<input id=I>)<button onclick=test()>-></button><span id=R></span>
<pre id=O>


Bella risposta! Non puoi parlare autorevolmente sulla validità del numero, ma puoi salvare 1 byte (!) Usando 0come delimitatore di stringa anziché ,!
Dom Hastings,

1
@DomHastings Penso che il trucco non sia più necessario con le stringhe modello. split(0)è della stessa lunghezza di split','(fingi che si tratti di bastoncini)
edc65,

Ahhh, scusa, stavo pensando che potresti perdere le parentesi, non è un coffeescript! :)
Dom Hastings,

3

C #, 502 byte

Questo progetto deve avere AssemblyName impostato sul motivo per cui produrrà un eseguibile con il nome corretto.

Completamente golf:

using System;class W{static void Main(string[]i)int n=i.Length>0?int.Parse(i[0]):new Random().Next();string[]s={"Don't ask!","How should I know?","Stop asking!"},v={"To please ","To fool ","To satisfy ",null},a={"the stupid","the smart","the bald","the tall","the rich"},p={"","Stewie","Peter","Homer","The programmer","The system manager","You"},e={"suggested it!","insisted on it!",null,"did it!"};Console.Write(n%7<1?s[n%3]:n%2<1?(v[n%8/2]??v[2])+a[n%10/2]+" {0}!":"{0} "+(e[n/2%4]??e[1]),p[n%7]);}}

Rientro e nuove linee per chiarezza:

using System;
class W{
    static void Main(string[]i)
        int n=i.Length>0
            ?int.Parse(i[0])
            :new Random().Next();
        string[]
            s={"Don't ask!","How should I know?","Stop asking!"},
            v={"To please ","To fool ","To satisfy ",null},
            a={"the stupid","the smart","the bald","the tall","the rich"},
            p={"","Stewie","Peter","Homer","The programmer","The system manager","You"},
            e={"suggested it!","insisted on it!",null,"did it!"};
        Console.Write(
            n%7<1
                ?s[n%3]
                :n%2<1
                    ?(v[n%8/2]??v[2])+a[n%10/2]+" {0}!"
                    :"{0} "+(e[n/2%4]??e[1]),
            p[n%7]
        );
    }
}

Esempio di input / output:

>Why
To fool the bald Homer!
>Why 1
Stewie suggested it!

2

Powershell 437 461 453 byte

Modifica: mancavano i verbi duplicati

Suddivisione tra il corpus e i calcoli per il conteggio dei byte

  • 267 byte = testo pre-codificato (ad esclusione to, the, ite !posti dato che hanno fisse).
  • 186 byte = calcolo

Imposta l'argomento predefinito su 0 se non specificato. Se l'argomento è <1allora ottiene un numero casuale <99 fn:1e ripete. Tecnicamente questo significa -50che funzionerà anche, essendo trattato come un caso casuale.

function why{param($b=0)$p=@('Stewie','Peter','Homer','The programmer','The system manager','You');$e=@('did','suggested','insisted on','insisted on');$v=@('please','fool','satisfy','satisfy');$a=@('stupid','smart','bald','tall','rich');$s=@("Don't ask!",'How should I know?','Stop asking!');if($b-le0){why(Get-Random 99)}elseif(!($b%7)){$s[$b/7%3]}else{$n=$p[$b%7-1];if($b%2){"$n $($e[($b+1)/2%4]) it!"}else{"To $($v[$b%8/2]) the $($a[$b%10/2]) $n!"}}}

Spiegazione:

# Any -1 in calculations is to account for arrays starting at index 0
# Final key placed in position 0 for indexing (4%4 = 0)
# Powershell 1 = True, 0 = False
if($b-le0){why(Get-Random 99)}          # If not positive, choose random number
elseif(!($b%7))                         # $b%7 means special so use that
  {$s[$b/7%3]}                          # Divide by 7 and find modulo, use that phrase.
else{$n=$p[$b%7-1]                      # Get the correct person (Used in both types). 6 max
if($b%2){"$n $($e[($b+1)/2%4]) it!"}    # Create type 1 sentence
else{"To $($v[$b%8/2]) the $($a[$b%10/2]) $n!"} # Type 2

fn:199 Scelto per salvare un byte. Se ci sono più di 99 possibili frasi sopra (non calcolate) aumentare a 999 o 9999 come applicabile (+1/2 byte)


2

MUMPS, 379 byte

f(s,i) s:'i i=$L(s,"^") q $P(s,"^",i)
why(n) s:'n n=$R(840) s p="Stewie^Peter^Homer^The programmer^The system manager^You",e="suggested^insisted on^did",v="fool^satisfy^please",a="smart^bald^tall^rich^stupid",s="How should I know?^Stop asking!^Don't ask!" q:n#7=0 $$f(s,n#3) q:n#2 $$f(p,n#7)_" "_$$f(e,n+1/2#4)_" it!" q "To "_$$f(v,n#8/2)_" the "_$$f(a,n#10/2)_" "_$$f(p,n#7)_"!"

Quando non viene fornito alcun input, viene generato un numero casuale in 0..839.

Uso:

>w $$why(15)
Stewie did it!
>w $$why()
Don't ask!

La strategia di valutazione da sinistra a destra di MUMPS consente di risparmiare alcuni byte tra parentesi qui.

Nota a margine: vedi quelle stringhe che sembrano "foo^bar^baz^qux"? Queste sono le cosiddette "stringhe delimitate" e sono il modo standard di memorizzare elenchi che rientrano nel limite di dimensione massima della stringa, poiché MUMPS in realtà non ha elenchi / matrici (o, in effetti, strutture dati oltre agli alberi). Per elenchi troppo grandi per adattarsi a una singola stringa, utilizziamo invece alberi di profondità 1 e inseriamo i valori sulle foglie dell'albero. Divertimento!


+1: MUMPS, di tutte le lingue, ha davvero bisogno di una whyfunzione. ;)
DLosc,

1

Emacs Lisp 473 byte

(defun why(n)(if(and n(> n 0))(let*((p'(t"Stewie""Peter""Homer""The programmer""The system manager""You"))(e'("did""suggested""insisted on""insisted on"))(v'("please""fool""satisfy""satisfy"))(a'("stupid""smart""bald""tall""rich"))(s'("Don't ask!""How should I know?""Stop asking!"))(q(nth(% n 7)p)))(cond((=(% n 7)0)(nth(%(/ n 7)3)s))((=(% n 2)1)(format"%s %s it!"q(nth(%(/(1+ n)2)4)e)))(t(format"To %s the %s %s!"(nth(/(% n 8)2)v)(nth(/(% n 10)2)a)q))))(why(random 99))))

'Rifiuti' più grande è probabilmente la format, %s... sezioni. Se le variabili fossero incorporate nelle stringhe senza la specifica, si risparmierebbero 10 byte %se altri 12 suformat


1

Rubino 396 378 372 byte

Sono sicuro che questo non è giocato al massimo.

p=%w[a Stewie Peter Homer The\ programmer The\ system\ manager You]
why=->n{n<1 ? why[rand(99)+1]:n%7<1 ? $><<%w[a How\ should\ I\ know? Stop\ asking! Don't\ ask!][n/7]:n%2<1 ? $><<'To '+%w[fool satisfy satisfy please][n%8/2-1]+' the '+%w[smart bald tall rich stupid][n%10/2-1]+' '+p[n%7]+?!:$><<p[n%7]+' '+%w[a suggested insisted\ on insisted\ on did][(n+1)/2%4]+' it!'}

Modifica: ho appena realizzato che non conosco la precedenza dell'operatore. Oh bene..


rand (21) sembra troppo piccolo
edc65

Che mi dici di 99? : P
Peter Lenkefi,

Ci sono 108 frasi composte + 3 casi speciali. La sequenza delle frasi è periodica ma il periodo ... Non lo so
edc65,

Il periodo è probabilmente 840 ... buona scelta di numeri
edc65

1

CJam, 281 byte

99mrqi_])0>=i:A7md{;A2%{S["suggested""insisted on""did"]A2/=+" it"+}{"To "["fool""satisfy"_"please"]A(2/:B=" the "["smart""bald""tall""rich""stupid"]B=SM}?[M"Stewie""Peter""Homer""The programmer""The system manager""You"]A=\'!}{["How should I know?""Stop asking!""Don't ask!"]\(=}?

Permalink

Non ho mai usato CJam prima, quindi prenderò qualche consiglio. Sono sicuro che ci sono molti trucchi che non conosco!

(Non sono riuscito a capire come nominarlo come una funzione chiamata "why" - sembra che le funzioni non esistano in CJam - quindi non sono sicuro che una risposta CJam sia ok o no ...)


Funzioni fanno esistono, ma ci sono solo 26 i nomi delle funzioni validi (da A a Z).
Dennis,

1

Lua 5.3.0, 452 460 446 byte

Questo è il mio primo tentativo di giocare a golf, quindi per favore correggimi se ho fatto qualcosa di sbagliato!

a={"Stewie","Peter","Homer","The Programmer","The system manager","You"}b={"fool ","satisfy ",n,"please "}b[3]=b[2]why=function(n)pcall(math.randomseed,n and n>0 and n)n=math.random(1e9)q=n>>4r=n>>8return 1>n&7 and({"How should I Know?","Stop asking!","Don't ask!"})[q%3+1]or 0<n%2 and a[q%6+1]..({" suggested"," insisted on"," did"})[r%3+1].." it"or"To "..b[q%4+1].."the "..({"smart ","bald ","tall ","rich ","stupid "})[r%5+1]..a[(r>>4)%6+1]end

Ungolfed:

a={
    "Stewie",
    "Peter",
    "Homer",
    "The Programmer",
    "The system manager",
    "You"
}
b={
    "fool ",
    "satisfy ",
    n,
    "please "
}
b[3]=b[2]
why=function(n)
    pcall(math.randomseed,n and n>0 and n)
    n=math.random(1e9)
    q=n>>4
    r=n>>8
    return
            1>n&7 and
                ({"How should I Know?","Stop asking!","Don't ask!"})[q%3+1]
            or 0<n%2 and
                a[q%6+1]..({" suggested"," insisted on"," did"})[r%3+1].." it"
            or
                "To "..b[q%4+1].."the "..({"smart ","bald ","tall ","rich ","stupid "})[r%5+1]..a[(r>>4)%6+1]
end

0

Python (2), 692 byte

Sto ancora imparando, quindi per favore sii gentile! :)

from sys import argv,maxint
import random
def why(*O):
 P=["You","Stewie","Peter","Homer","programmer","system manager"];E=["did","suggested","insisted on","insisted on"];I=["please","fool","satisfy","satisfy"];Q=["stupid","smart","bald","tall","rich"];S=["Don't ask!","How should I know?","Stop asking!"]
 if len(argv)>1:A=O[0]
 else:A=random.randint(-maxint-1,maxint)
 if A%7==0:print S[A%3]
 else:
  M=P[A%6]
  if A%11==0:
   M=P[4]
  if A%2==0:
   if M==P[0]:M="you"
   U=I[(A%8)/2];Z=Q[(A%10)/2];print"To %s the %s %s!"%(U,Z,M)
  if A%2==1:
   if M==P[4]:M="The %s"%P[4]
   if M==P[5]:M="The %s"%P[5]
   C=E[((A+1)/2)%4];print"%s %s it!"%(M,C)
if len(argv)>1:why(int(argv[1]))
else:why()

Funziona con o senza int come argomento della riga di comando.

Ho cercato di sottolineare il codice correttezza, per quanto possibile, in quanto con la generazione di numeri casuali da -sys.maxint - 1a sys.maxinte visualizzare le frasi nel caso giusto.

Il codice si basa molto sulle dichiarazioni if ​​che sono sicuro che potrebbero essere sostituite con qualcosa di più efficiente.

Il feedback è molto gradito!

Ungolfed (1341 byte)

from sys import argv, maxint
import random

def Why(*Optional):
    Persons = ["You", "Stewie", "Peter", "Homer", "programmer", "system manager"]
    Endings = ["did it", "suggested it", "insisted on it", "insisted on it"]
    Verbs = ["please", "fool", "satisfy", "satisfy"]
    Adjectives = ["stupid", "smart", "bald", "tall", "rich"]
    SpecialCases = ["Don't ask!", "How should I know?", "Stop asking!"]

    if len(argv) > 1:
        Argument = Optional[0]
    else:
        Argument = random.randint(-maxint - 1, maxint)

    if Argument % 7 is 0:
        print SpecialCases[Argument % 3]
    else:
        Person = Persons[(Argument) % 6]
        if Argument % 11 is 0:
            Person = "programmer"
        if Argument % 2 is 0:
            if Person is "You":
                Person = "you"
            Verb = Verbs[(Argument % 8) / 2]
            Adjective = Adjectives[(Argument % 10) / 2]
            print "To %s the %s %s!" % (Verb, Adjective, Person)
        if Argument % 2 is 1:
            if Person is "programmer":
                Person = "The programmer"
            if Person is "system manager":
                Person = "The system manager"
            Ending = Endings[((Argument + 1) / 2) % 4]
            print "%s %s!" % (Person, Ending)

if len(argv) > 1:
    Why(int(argv[1]))
else:
    Why()

2
Ti suggerisco di leggere [ codegolf.stackexchange.com/questions/54/… —in particolare, puoi salvare molti byte usando il primo suggerimento in quella pagina. Puoi anche indicizzare dalla parte posteriore dell'elenco dei verbi in modo da avere solo bisogno di "soddisfare": usa argument%8/2-1e rimuovi il secondo. Puoi anche sostituire ==0con <1.
lirtosiast
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.