为什么?为了讨好有钱的程序员!


21

您是否曾经想问过编译器“为什么?” 当代码无法正常工作时,我们大多数人都感到沮丧。因此,Mathworks实现了一个很好的小功能why,它回答了这个问题。举一些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.

您的任务是why用您的语言实现该功能。该函数应在有或没有输入参数的情况下工作(或者使用input 0-1)。该函数必须被命名why(或者,why(n)用STDIN 编写将导致打印适当的字符串)。

如果未提供任何参数,或者参数为零或负数,则输出字符串应为随机的有效短语。因此,应该有一个功能whywhy()why(0)why(-1)返回一个随机的句子。

如果给出了输入参数n(函数参数,不是STDIN),则输出应为第n个字符串(定义如下)。因此,why(1)应始终输出(打印/显示)相同的结果。

句子的构成如下(类型1,类型2和特殊)。所有句子都以结尾!

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

人员名单:

Stewie
Peter
Homer
The programmer
The system manager
You

结尾列表:

suggested it
insisted on it
did it

动词列表为:

To fool
To satisfy
To please

形容词列表:

the smart
the bald
the tall
the rich
the stupid

特殊情况列表:

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

选择编号的方法是:

句子类型:

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

名称:使用模数(%)定义第n个名称。

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!

结尾:第n个结尾也使用模数定义。假设结尾(1、2和3)像一样列出(1 2 2 3)。由于数字总是奇数,请使用((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

形容词:使用模数定义第n个形容词。由于数字总是偶数,请使用:(n % 10)/2

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

动词:第n个动词也使用模数定义。假设动词(1、2和3)的列出方式如下,(1 2 2 3)因为动词的数字始终是偶数,请使用(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

现在,创建随机数的方法应该非常简单,只需选择一个random即可n

一些例子:

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!

适用标准代码高尔夫规则。从挑战发布之日起的一周内将选出一名优胜者。


写出为什么在stdin中应该返回我可以使用的字符串。它必须是小写字母why还是WHY可以接受的?
丹尼斯2015年

小写和大写都可以。
Stewie Griffin 2015年

同样,结局不需要/2工作。给出分数值。13也应为insisted(14/2 = 7%4 = 3 =坚持的2nd)。
乔纳森·里奇·佩平

3
是否the rich The programmer由于指定原因而遇到类似情况是否重要the
Jonathan Leech-Pepin

1
@StewieGriffin 您列表中的单词The和单词To可能应该小写以匹配您的示例……
mbomb007 2015年

Answers:


5

JavaScript(ES6)345

不确定数字,但这是我的尝试。

测试在符合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>


好答案!不能权威性地讲数字的有效性,但是您可以使用1个字节(!)0作为字符串分隔符,而不是,!。
唐·黑斯廷斯

1
@DomHastings我认为模板字符串不再需要这个技巧。split(0)是一样的长度split','(假装这些是反引号)
edc65

啊,对不起,我当时想你可能会失去括号,这不是咖啡文字!:)
Dom Hastings 2015年

3

C#,502个字节

该项目需要将AssemblyName设置为为什么将生成具有正确名称的可执行文件。

完全打高尔夫球:

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]);}}

缩进和换行以简化说明:

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]
        );
    }
}

输入/输出示例:

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

2

PowerShell的437 461个 453字节

编辑:错过了重复的动词

在语料库和字节数计算之间进行划分

  • 267个字节=预编码的文本(排除totheit!因为它们具有固定的位置)。
  • 186字节=计算

如果未指定,则将默认参数设置为0。如果参数为<1true,它将获得一个随机数<99 fn:1并重新运行。从技术上讲,这-50被认为是随机的情况也将起作用。

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!"}}}

说明:

# 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选择保存一个字节。如果以上有99个以上的可能句子(未计算),则根据适用情况增加到999或9999(+1/2字节)


2

MUMPS,379个字节

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)_"!"

没有输入时,将生成0..839中的随机数。

用法:

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

MUMPS的从左到右评估策略在此处的括号内节省了很多字节。

旁注:看到那些看起来像的字符串"foo^bar^baz^qux"吗?这些就是所谓的“定界字符串”,并且是存储适合最大字符串大小限制的列表的标准方法,因为MUMPS实际上没有列表/数组(或者实际上除了树之外没有任何数据结构)。对于太大而无法容纳单个字符串的列表,我们改为使用深度为1的树,然后将值放在树的叶子上。好玩!


+1:所有语言的MUMPS确实需要一个why功能。;)
DLosc 2015年

1

Emacs Lisp 473字节

(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))))

最大的“浪费”大概是format%s...部分。如果可以在没有指定的情况下将变量内联到字符串中,则可以节省10个字节%s,另节省12个字节。format


1

红宝石396 378 372字节

我确定这没有发挥最大作用。

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!'}

编辑:我刚刚意识到我不知道运算符优先级。那好吧..


rand(21)似乎太小了
edc65

那99呢?:P
Peter Lenkefi 2015年

有108个复合句子+ 3个特殊情况。句子的顺序是周期性的,但是是句点...我不知道
edc65

这个时期可能是840年...数字的不错选择
edc65

1

CJam,281字节

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!"]\(=}?

固定链接

以前没有使用过CJam,所以我将介绍所有技巧。我确定有很多我不知道的技巧!

(我不知道如何将其命名为“为什么”的功能-看来CJam中不存在该功能-因此我不确定CJam的答案是否正确...)


函数确实存在,但是只有26个有效的函数名称(A到Z)。
丹尼斯

1

Lua的5.3.0,452个 460 446字节

这是我第一次尝试打高尔夫,所以如果我做错了,请纠正我!

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

取消高尔夫:

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字节

我还在学习,请保持温柔!:)

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()

可以使用int作为命令行参数,也可以不使用int。

我想强调的代码的正确性尽可能多,尽可能从产生随机数-sys.maxint - 1sys.maxint,在右侧时,显示的句子。

该代码非常依赖if语句,我确信可以用更高效的地方替换它。

反馈非常欢迎!

非高尔夫(1341字节)

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
我建议您阅读[ codegolf.stackexchange.com/questions/54/…-特别是,您可以使用该页面上的第一个技巧来节省很多字节。您也可以从动词列表的后面索引,因此只需要一个“满足条件”即可:使用argument%8/2-1并删除第二个。您也可以替换==0<1
lirtosiast 2015年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.