高尔夫黄鼠狼计划


65

理查德•道金斯Richard Dawkins)在他的“ 盲人制表师”一书中描述了鼬鼠程序。该算法可以描述如下:

  1. 以28个字符的随机字符串开头。有效字符均为大写字母和空格。

  2. 制作该字符串的100个副本,每个字符的5%机会被随机字符替换。

  3. 将每个新字符串与目标“比较像是Weasel的单词”进行比较,并根据字符串中正确且位置正确的字母数给每个得分。

  4. 如果任何新字符串的得分都很高(28),请暂停。

  5. 从第3步中选择得分最高的字符串。如何决定平局取决于您,但是只能选择一个字符串。以所选的字符串并转到步骤2。

获胜者将是获得正确答案的最短代码段,同时以以下格式打印每一代得分最高的字符串:

请以这种格式回答

如果人们可以通过检查其他人来帮助您,那么答案将非常有帮助!


4
允许使用哪些字符?Unicode?小写?
Oriol 2014年

4
啊,我爱道金斯。一个简单的算法显示出美观性和进化的可行性。
Cruncher 2014年

是否可以将“步骤4”更好地替换为“步骤1.5),如果新字符串的得分正确(为28),则暂停”,然后“步骤4)选择得分最高的字符串,然后执行步骤1.5。”?也就是说,如果最初的随机字符串是赢家,我们是否需要扇出?
罗伯·史达琳

1
我对这里的操作顺序有些困惑。我们打算基于原始字符串制作100个新字符串吗?还是它是100个新字符串,第一个字符串基于原始字符串,而每个后续字符串都基于前一个字符串?算法描述似乎暗示着前者,而样本输出似乎来自后者。
Iszi 2014年

2
指令很清楚,但是如果原始字符串是目标,该怎么办?
Christian Palmstierna 2014年

Answers:


27

APL(143)

0{⍵≢T←'METHINKS IT IS LIKE A WEASEL':c∇⍨1+⍺⊣⎕←(⍕⍺),':'c'-- score:',s⊣c←⊃c/⍨G=s←⌈/G←{+/⍵=T}¨c←{⍵{⍵:⍺⋄C[?27]}¨9≠?28/20}¨100⍴⊂⍵}⊃∘(C←27↑⎕A)¨?28/27

说明:

  • 0{... }⊃∘(C←27↑⎕A)¨?28/27:设置C为前27个大写字母。只有26个,因此第27个元素将是一个空格。从中选择28个随机项目C。这将是第一个。第一代将是0

  • ⍵≢T←'METHINKS IT IS LIKE A WEASEL:设置T为字符串'METHINKS IT IS LIKE A WEASEL'。只要不等于T

    • {... }¨100⍴⊂⍵:制作100份。对于每一个...
      • 9≠?28/20:从1到20中选择28个随机数。制作一个位掩码,每个掩码1表示该随机数不等于9。(这表示5%的机会0)。
      • ⍵{⍵:⍺⋄C[?27]}¨:对于其中的每个字母,如果对应的位是1,请保留该字母,否则将其替换为从中随机选择的元素C
    • c←:将100个突变的字符串存储在中c
    • G←{+/⍵=T}¨c:对于中的每个元素c,计算分数(匹配的字符数T)并将分数存储在中G
    • s←⌈/G:找到最大分数并将其存储在中s
    • c←⊃c/⍨G=s:从c分数等于s(最高)的第一项中选择,然后c再次存储。
    • ⎕←(⍕⍺),':'c'-- score:',s:以给定格式打印世代(是当前世代,c是当前最佳字符串,s是得分)
    • c∇⍨1+⍺:增加生成并使用当前最佳字符串(c)作为输入再次运行变异。

5
说明?这看起来像字母汤!:)
ToastyMallows 2014年

2
@ToastyMallows:添加了解释
marinus

1
到目前为止最好的答案,很高兴对此做出解释。
2014年

1
@marinus你是巫师吗?
ToastyMallows 2014年

3
Bullcrap,您刚刚打开MS Word并使用了WingDings字体
Embattled Swag 2014年

11

数学- 238 236 225

c:="@"~CharacterRange~"Z"~RandomChoice~28/."@"->" "
For[s=""<>c;i=0,{d,s}=Sort[{#~HammingDistance~"METHINKS IT IS LIKE A WEASEL",#}&@
StringReplace[s,_/;20Random[]<1:>c〚1〛]&~Array~100]〚1〛;
d>0Print[i++,":"s," -- score: ",28-d],]

输出示例

0:  CYPMEIHADXRXVTFHERYOZNRVFCSQ  -- score: 0
1:  CYPMEIHADIRXVTFBERYOZNRVFCSQ  -- score: 1
2:  CYPMEIHA IRXVTFBIRYOZNRVFCSQ  -- score: 3
...
50:  METHINKS IT IS LIKE A WEASEL  -- score: 28

9

巨蟒(273)

from random import choice as c
n=range
a=map(chr,n(65,91)+[32])
s=map(c,[a]*28)
p=x=0
while p<28:
 p,s=max((sum(g==r for g,r in zip(y,'METHINKS IT IS LIKE A WEASEL')),y)for y in ([c(a+[x]*513)for x in s]for _ in n(100)));print '%d: %s -- score: %d' % (x,''.join(s),p);x+=1

6

K,173 167

o:"METHINKS IT IS LIKE A WEASEL"
i:0;{~x~o}{-1($i),": ",(r:a@*&b=c)," -- score: ",$c:max@b:+/'o=/:a:{x{if[0~*1?20;x[y]:*1?s];x}/!#x}'100#,x;i+:1;r}/28?s:"c"$32,65+!26;

/

0: FQRZPHACDIBHZOUUCYKKFBJWVNVI -- score: 1
1: FQRZP ACDITHCOUUCYKKFBJWVNVI -- score: 2
2: FQRZP AFDIT COUUCYKKFBJWVNVI -- score: 3
...
51: METHINKS IT IS LIKECA WEASEL -- score: 27
52: METHINKS IT IS LIKECA WEASEL -- score: 27
53: METHINKS IT IS LIKE A WEASEL -- score: 28

6

Python:282个字符,没有半冒号

from random import*
g,r,l,c=0,0,"ABCDEFGHIJKLMNOPQRSTUVWXYZ ",choice
k=map(c,[l]*28)
while(r!=28):
 r,k=max((sum(i==j for i,j in zip(t,"METHINKS IT IS LIKE A WEASEL")),t)for t in[[c(l)if random()<.05 else i for i in k]for i in[1]*100])
 print`g`+":","".join(k),"-- score:",`r`
 g+=1

278具有:

from random import*;g,r,l,c=0,0,"ABCDEFGHIJKLMNOPQRSTUVWXYZ ",choice;k=map(c,[l]*28)
while(r!=28):r,k=max((sum(i==j for i,j in zip(t,"METHINKS IT IS LIKE A WEASEL")),t)for t in[[c(l)if random()<.05 else i for i in k]for i in[1]*100]);print`g`+":","".join(k),"-- score:",`r`;g+=1

4
您应该明确说明语言,并且由于问题被标记为代码高尔夫,因此您应该提供字符计数。
Tim Seguine 2014年

会的,谢谢你的提示蒂姆。
Noelkd 2014年

另外,您应该使用所有一个字母的变量名来进一步减少字符数。
门把手

等到以后再打一些球,仍然获得了一些轻松的胜利。谢谢。
Noelkd 2014年

1
真的应该以所有相同的字母开头吗?:)
Joachim Isaksson 2014年

5

JavaScript中,277 246

c=m=>" ABCDEFGHIJKLMNOPQRSTUVWXYZ"[0|Math.random()*m];for(s=[k=28];e=k;s[--k]=c(27));for(;alert(k+++": "+s.join("")+" -- score: "+e),e<28;s=t)for(z=100;f=0,z--;f>e&&(t=n,e=f))n=s.map((h,p)=>(h=c(540)||h,f+=h=="METHINKS IT IS LIKE A WEASEL"[p],h))

(需要箭头功能支持;仅出于可读性而添加缩进)

// c() returns a random char using `m` as an index max
c=m=>" ABCDEFGHIJKLMNOPQRSTUVWXYZ"[0|Math.random()*m];

// generate base string `s`
for(s=[k=28];e=k;s[--k]=c(27));

// while score `e` is < 28
for(;alert(k+++": "+s.join("")+" -- score: "+e),e<28;s=t)
    for(z=100;f=0,z--;f>e&&(t=n,e=f))            // do 100 mutations; keep best score
        n=s.map((h,p)=>(                         // map `s` to `n` with 5% mutation
            h=c(540)||h,                         // change the char in 5% of cases
            f+=h=="METHINKS IT IS LIKE A WEASEL"[p],  // score++ if char matches
            h                                    // arrow function return character
        ))

随意更改alertconsole.log,如果你想要一个更愉快的体验执行。

这里有一些漂亮的高尔夫球位:

  • 该函数c从字母字符串返回随机字符" ABC..."。该函数采用一个参数作为随机索引选择的上限。在生成基本字符串时,我们使用27,因此该函数的行为正常。

    但是,我们通过要求540中的随机上限来滥用此行为h = c(540) || hc实际上只有5%的时间会返回字符串(因为540 * .05 = 27);在其他95%的时间中,随机选择的索引超出了字符串的长度,因此该函数返回undefined。该假值导致中的逻辑或级联c(540) || h,因此使用原始maph(即,没有替换发生)。

  • 得分求和操作呢f+=h=="METHINKS IT IS LIKE A WEASEL"[p],它说“添加truef如果当前map字符h的匹配p黄鼠狼字符串的字符”。数字加布尔加法将布尔结果强制为01,这意味着f仅当与目标WEASEL字符串匹配时才递增。


为什么要v在代码中说明?那里没有其他地方提到过。您可以节省2个字符。
WallyWest

1
@ Eliseod'Annunzio v是一个参数存储在箭头功能cc = (v => ...)。如果要定义不带参数的箭头功能,则它需要两个字符()=>...,而不是一个字符v=>...,因此最好使用未使用的参数。
ps药

巧妙使用代码!
WallyWest

不错的把戏 k=s=[28]和的++,我不知道!
Dom Hastings 2014年

5

R(245个 239 238字符)

t=strsplit("METHINKS IT IS LIKE A WEASEL","")[[1]]
h=sample
s=h(f<-c(LETTERS," "),28,T)
c=0
while(!all(s==t)){for(i in 1:100){z=ifelse(runif(28)<.05,h(f,1),s)
y=sum(s==t)
if(sum(z==t)>y)s=z}
cat(c<-c+1,": ",s," -- score: ",y,"\n",sep="")}

给出:

1: HSSSIMJM ETJISGBSCIELUYPLSED -- score: 7
2: HSSSIMJM ETJISGBSKIELUYPLSED -- score: 8
3: EETLITLM ETJISTBSKIELUYLLSEL -- score: 11

...

78: METHINKS IT IS LIKEEA WEASEL -- score: 27
79: METHINKS IT IS LIKEEA WEASEL -- score: 27
80: METHINKS IT IS LIKEEA WEASEL -- score: 27
81: METHINKS IT IS LIKE A WEASEL -- score: 28

0: ...如果第一次调用catc增加到1,如何获得第一行?(尽管如此,我还是花了一个小时才尝试做一些更短的事情,但我仍然不能::))
plannapus 2014年

@plannapus是的,它来自旧版本(稍长一些)。我是将其开头更改为-1,还是在第一行中使用1 ...
Henrik

我发现您的代码有两个问题。首先,这ifelse(…,h(f,1),…)会将所有选定的位置替换为相同的随机字符。您可以朝这个方向解释规则,但是感觉就像弯曲它们一样,所以我至少会提及它。其次,s=z1:100循环中进行替换,因此您不会复制同一字符串的100个副本,而是有时复制一个副本。这似乎是违反规则,而不仅仅是弯曲规则。
MvG 2014年

5

C 256

char c[101][29],s,n,z,b,j,i,w;g;main(){for(;w<28;printf("%d: %s -- score: %d\n",g++,c[b=n],w))for(i=w=0;i<101;i++)for(s=j=0;j<28&&!(i==b&&g);j++)(s+=(c[i][j]=g&&rand()%20?c[b][j]:(z=rand()%27)?'A'+z-1:' ')=="METHINKS IT IS LIKE A WEASEL"[j])>w?n=i,w=s:0;}

简单的三个循环,初始化,从父代生成新字符串以及由同一条语句计算出的得分。即使有缩进,它也不是很可读。

C 252

i,g,n,b,o,s,w,z;char c[2929];main(){for(;(o=i%29)|i|w<28;(i=(i+1)%2929)||printf("%d: %s -- score: %d\n",g++,&c[b=n],w))(s+=o>27?-s:((i-o!=b||!g)&&(c[i]=g&&rand()%20?c[b+o]:(z=rand()%27)?'A'+z-1:' ')=="METHINKS IT IS LIKE A WEASEL"[o]))>w?n=i-o,w=s:0;}

一个循环,其中一个数组包含所有101个字符串。

第二个版本违反了规则,因为它打印了步骤1中的字符串(等效于步骤1),但不是最后一个字符串。我很困惑如何解决它而又不使尺寸膨胀。无论如何,我都将其发布以获取灵感。

C 256

struct{char d[29];}p,t,n;i,j=-1,z,s,w,g;main(){for(;w<28;j>1&&printf("%d: %s -- score: %d\n",g++,(p=n).d,w))for(;j++%100;p=j?p:t)for(s=0,i=28;i--;)(s+=(t.d[i]=j&&rand()%20?p.d[i]:(z=rand()%27)?'A'+z-1:' ')=="METHINKS IT IS LIKE A WEASEL"[i])>w?n=t,w=s:0;}

使用不同的方法,而不是创建一个数组来容纳101个字符串,只需将字符串重新生成100次并使用结构赋值即可轻松复制。初始化是通过在“ -1”处启动“ repeat 100 times”(重复100次)计数器并通过策略性选择的后增量来仔细处理它的。尽管使用了非常不同的方法,但最终结果与第一次尝试完全相同-256个字符。


4

C#-436

namespace System.Linq{class W{static void Main(){var r=new Random();
Func<char>c=()=>(char)(r.Next(33,60)%59+32);var s="";
while(s.Length<28)s+=c();var a="METHINKS IT IS LIKE A WEASEL";int b=0;
while (s!=a){int m=-1;var f=s;for(int i=0;i<100;i++){
var l=string.Join("",s.Select(j=>(r.Next(20)!=0?j:c()).ToString()));
int o=Enumerable.Range(0,28).Sum(j=>l[j]==a[j]?1:0);if(o>m){f=l;m=o;}}
Console.WriteLine(b+++": "+(s=f)+" -- score: "+m);}}}}

这已破了。您需要使用系统;或手动排位赛系统。
不是。

不,你没有。ideone.com/4alNSi
2014年

很好。将NS声明视为对不起。
不是。

3

Lua 5.1(502)

最小化版本:

s,t,b,c,i,q,a,d,f="ABCDFGHJYUEGKSHNCOLPQIEJUSNC","METHINKS IT IS LIKE A WEASEL",1,math.random,table.insert,1,string.sub,100,28 while q~=f do r,p={},{} for x=1,d do i(r,s) i(p,0) e="" for o=1,f do if c(1,20)==1 then if c(1,27)==1 then e=e.." " else e=e..string.char(c(65,90)) end else e=e..a(r[x],o,o) end end r[x]=e for y=1,f do if a(r[x],y,y)==a(t,y,y) then p[x]=p[x]+1 end end if p[x]==f then s=r[x] end end for x=1,d do if p[x]>=q then s,q=r[x],p[x] end end print(b..":",s,"-- score: "..q) b=b+1 end

和更易于阅读的版本(带有注释!):

s,t,b,c,i,q,a,d,f="ABCDFGHJYUEGKSHNCOLPQIEJUSNC","METHINKS IT IS LIKE A WEASEL",1,math.random,table.insert,1,string.sub,100,28
--s=random string, t=target, b=counter, c=reference to math.random, i=reference to table.insert, q=top score,a=reference to string.sub, d=constant (100), f=constant (28)
while q~=f do
    r,p={},{}
    for x=1,d do  --add 100 copies to the table of strings
        i(r,s)
        i(p,0)
        e=""
        for o=1,f do  --for each character in string
            if c(1,20)==1 then  -- 5% chance
                if c(1,27)==1 then e=e.." " else e=e..string.char(c(65,90)) end  --set it to an ASCII char between 65 and 90 (A-Z) or a space character
            else
                e=e..a(r[x],o,o)
            end
        end
        r[x]=e  --current string = mutations
        for y=1,f do
            if a(r[x],y,y)==a(t,y,y) then p[x]=p[x]+1 end
        end  --for each char increment score if it is correct
        if p[x]==f then
            s=r[x]
        end  --if 28 then final string is this!
    end
    for x=1,d do
        if p[x]>=q then s,q=r[x],p[x] end  --if this is the highest score so far, then make the string equal to this
    end
    print(b..":",s,"-- score: "..q)  --print it!
    b=b+1  --add one to the counter!
end

老实说,即使这绝对不会赢,我只是很高兴找到并最小化解决这个问题的合理方法!(强调合理):p


3

SAS-374

%macro r;ranuni(7)%mend;%macro s;r=int(%r*27);substr(x,t,1)=byte(ifn(r,64+r,32));%mend;%macro y;char(y,t)=char(x,t)%mend;options nonotes nosource;data x;length x$28;do t=1to 28;%s;end;y="METHINKS IT IS LIKE A WEASEL";do z=1by 1;o=x;do i=1to 100;c=0;x=o;do t=1to 28;if %r<=.05then do;%s;end;c+%y;end;if c>m then do;m=c;v=x;end;end;x=v;put z":" x"-- score:" m;if m<28;end;run;

->

1 :GUUVLNUSILSRZLRBXVVCWXX HXKC -- score:2
2 :MUUVLNUSILSRZLRBXVMCWXX HXKC -- score:3
3 :MUUVLNESILSRILRBXVMCWXX HXKC -- score:4
4 :MEUVLNESILSRIRRBXVMCWXX HXKC -- score:5
....
95 :METHINKS IT IS LIKE A XEASEL -- score:27
96 :METHINKS IT IS LIKE A XEASEL -- score:27
97 :METHINKS IT IS LIKE A XEASEL -- score:27
98 :METHINKS IT IS LIKE A WEASEL -- score:28

带有换行符/缩进/注释:

%macro r;
 ranuni(7)   /* seed 0 will make new each time (seed=clock), otherwise fixed results */
%mend;
%macro s;  /* does the rand char, used both to initialize and replace; */
 r=int(%r*27); 
 substr(x,t,1)=byte(ifn(r,64+r,32)); *r=0 becomes space otherwise upper char;
%mend;
%macro y;  /*compares using new to 9.2 CHAR function which is equivalent to substr(str,start,1) */
 char(y,t)=char(x,t)
%mend;
options nonotes nosource; /*cheapest way to get clean log */
data x;
 length x$28; /*annoyingly necessary*/
 do t=1to 28;%s;end; /*initialize string*/
 y="METHINKS IT IS LIKE A WEASEL"; /*compare string */
 do z=1by 1; /*start iterating */
  o=x; /*save this iteration's string */
  do i=1to 100;
   c=0; /*score for this iteration*/
   x=o; /*string to fudge about start out clean, reusing x so no params to macro*/
   do t=1to 28;
    if %r<=.05then do;%s;end; /*if 5% then change the char out */
    c+%y; /*score that character*/
   end;
   if c>m then do; /*if on better scoring line, save it */
    m=c;
    v=x;
   end;
  end;
  x=v; *for next iter - this is cheaper than other options involving o=v due to first iter;
  put z":" x"-- score:" m;
  if m<28; *quit at 28;
 end;
run;

3

C 361 331

不如Art的解决方案好,但这是我(新手)尝试使用C解决方案的尝试。361个字符(如果删除换行符和制表符)。

char*w="METHINKS IT IS LIKE A WEASEL";char b[101][29];t,s,n,i,j,x,a;main(){for(;i<28;i++)b[0][i]=w[rand()%28];while(s<28){for(j=1;j<101;j++){x=0;for(i=0;i<28;i++){if(!(rand()%20))b[j][i]=w[rand()%28];else b[j][i]=b[0][i];if(b[j][i]==w[i])x++;}if(x>s){s=x;t=j;}}printf("%d: %s -- score %d\n",n++,b[t],s);for(;i>=0;--i){a=b[0][i];b[0][i]=b[t][i];b[t][i]=a;}t=0;}}

编辑:摆脱了嵌套的循环,并使用一维数组。希望它能带来更大的变化,但它只为我节省了30个字符。这是代码:

char*w="METHINKS IT IS LIKE A WEASEL";char b[2929];t,s,n,i,x;main(){for(;i<28;i++)b[i]=w[rand()%28];while(s<28){for(;i<2929;i++){if((i+1)%29){if(!(i%29))x=0;b[i]=rand()%20?b[i%29]:w[rand()%28]; x+=b[i]==w[i%29];if(x>s){s=x;t=i/29;}}}for(i=0;i<29;i++){x=b[i+t*29];b[i+t*29]=b[i];b[i]=x;}printf("%d: %s -- score %d\n",n++,b,s);t=0;}}

编辑:这是原始的,没有高尔夫球的代码,对于那些有兴趣知道如何进行“高尔夫球”的人。在启用了-Wall和C99的GCC中编译时,该代码不会产生任何警告。也许您是像我这样的高尔夫新手,还是像我这样的C新手,或者您只是好奇。:) https://gist.github.com/cpx/97edbce4db3cb30c306a


3

斯卡拉 347 341 337个字符:

import util.Random.{nextInt=>r}
val t="METHINKS IT IS LIKE A WEASEL"
def c="ABCDEFGHIJKLMNOPQRSTUVWXYZ "(r(27))
def s(a:String)=t.zip(a).map{x=>if(x._1==x._2) 1 else 0}.sum
def w(a:String,i:Int=0){println(f"$i%2d: $a -- score: ${s(a)}")
if(s(a)!=28){w((0 to 99).map{_=>a.map(o=>if(r(20)<1) c else o)}.sortBy(s).last,i+1)}}
w(t.map(_=>c))

=>

 0: PGSHWAEPALQFTCORUKANPNUTRVXH -- score: 2
 1: PGSHWAEPALQ TCOQUKANPNUTRVXH -- score: 3
...
47: METHINKS WT IS LIKE A WEASEL -- score: 27
48: METHINKS IT IS LIKE A WEASEL -- score: 28

哎呀 我误解了算法,而不是“将一个字符的每个字符有5%的机会替换为随机字符”,而是排列了一个随机字符。将修复。
罗布·史达琳

固定并修剪一点!
罗伯·史达琳

在scala 2.10中,println("%2d: %s -- score: %d".format(i,a,s(a))可以更改为println(f"$i%2d: $a%s -- score: ${s(a)}%d"),节省4个字符!
罗伯·史达琳

(((('A'to'Z')toSeq):+'')==“ ABCDEFGHIJKLMNOPQRSTUVWXYZ”,打印字符串不需要2%s,节省9个字符
Chris

@Chris您在哪个版本的scala上运行该版本?def c=(' '+:('A'to'Z'))(r(27))给我error: type mismatch; found : Int required: scala.collection.generic.CanBuildFrom[scala.collection.immutable.IndexedSeq[Char],Char,?]
Rob Starling,2014年

2

PHP 442

<? function r(){$n=rand(65,91);if($n==91) return ' ';else return chr($n);}function s($s){$c=0;$t='METHINKS IT IS LIKE A WEASEL';for($i=0;$i<28;$i++) if($s[$i]==$t[$i]) $c++;return $c;}function m($s){for($i=0;$i<28;$i++) if(rand(0,99)<5) $s[$i]=r();return $s;}$s='';for($i=0;$i<28;$i++) $s.=r();for($i=0;;$i++){$l=s($s);printf("%2d: %s -- score: %d\n",$i,$s,$l);if($l==28) break;$x=$s;for($j=0;$j<100;$j++){$t=m($s);if(s($t)>$l) $x=$t;}$s=$x;}

准备就绪:

<?
//random char
function r(){
    $n=rand(65,91);
    if($n==91) return ' ';
    else return chr($n);
}
//score
function s($s){
    $c=0;
    $t='METHINKS IT IS LIKE A WEASEL';
    for($i=0;$i<28;$i++)
        if($s[$i]==$t[$i]) $c++;
    return $c;
}
//mutate
function m($s){
    for($i=0;$i<28;$i++)
    if(rand(0,99)<5) $s[$i]=r();
    return $s;
}
$s='';
for($i=0;$i<28;$i++) $s.=r();
for($i=0;;$i++){
    $l=s($s);
    printf("%2d: %s -- score: %d\n",$i,$s,$l);
    if($l==28) break;
    $x=$s;
    for($j=0;$j<100;$j++){
        $t=m($s);
        if(s($t)>$l) $x=$t;
    }
    $s=$x;
}

之后删除多余的空格if\for,它是436。您还可以检查$n>90其他字符
Einacio 2014年

我喜欢这个,它实际上是可读的。我发现您的r()s()功能有一些可能的改进。这是带注释的更改:ideone.com/4ecZQc
Llama先生

哦,您的printf语句可以缩短。的%s长度始终相同,并且%d左对齐,因此您可以改用以下内容:printf("%2d: $s -- score: $l\n",$i);
拉马先生(Mr. Llama)2014年

2

爪哇(632)

class C {public static void main(String[] a){String b="AAAAAAAAAAAAAAAAAAAAAAAAAAAA";for(int i=1;;i++){String c=w(b);int s=s(c);if(s==28)break;if(s(b)<s){b=c;System.out.println(i+": "+c+" -- score: "+s);}}}public static String w(String b) {StringBuffer c = new StringBuffer(b);int max = 0;for (int i=0;i<100;i++){for(int j=0;j<28;j++)if(Math.random()<.06){double d=Math.random();c.setCharAt(j,(char)(d==1?32:d*26+65));}String d=c.toString();int s=s(d);if(s>max){max=s;b=d;}}return b;}public static int s(String s){String b="METHINKS IT IS LIKE A WEASEL";int sum=0;for(int j=0;j<28;j++)sum+=s.charAt(j)==b.charAt(j)?1:0;return sum;}}

Java是一种冗长的语言。


2

蟒(330 321)

def b(i,s):print i,':',''.join(s),'-- score:',p(s)
from random import*;a=" ABCDEFGHIJKLMNOPQRSTUVWXYZ";i,s,t=0,choice(a)*28,"METHINKS IT IS LIKE A WEASEL";p=lambda n:sum(n[c]==t[c]for c in range(28))
while p(s)<28:b(i,s);s=sorted([[(c,choice(a))[random()<.05]for c in s]for k in[1]*100],key=lambda n:p(n))[-1];i+=1
b(i,s)

可读版本:

def b(i,s):
    print i,':',''.join(s),'-- score:',p(s)

import random as r
a=" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
i,s,t=0,r.choice(a)*28,"METHINKS IT IS LIKE A WEASEL"
p=lambda n:sum(1for c in range(28)if n[c]==t[c])
while p(s)<28:
    b(i,s)
    s=sorted([[(c,r.choice(a))[r.random()<.05]for c in s]for k in[1]*100],key=lambda n:p(n))[-1];i+=1
b(i,s)

输出示例:

0 : SSSSSSSSSSSSSSSSSSSSSSSSSSSS -- score: 3
1 : SSSQSSSSSSSSSSSSISSSSSSSSSSS -- score: 4
2 : SSSQISSSSSSSSSSSISSSSSSSSSSS -- score: 5
3 : SSSQISSSSSSSSSSSIKSSSSSSSSSS -- score: 6
4 : SMSQISSSSSSSISSSIKSSSSGSSSSS -- score: 7
...
53 : METHINKS IT IS UIKE A WEASEL -- score: 27
54 : METHINKS IT IS UIKE A WEASEL -- score: 27
55 : METHINKS IT IS LIKE A WEASEL -- score: 28

编辑:删除了一些基于AMK和Timtechs答案的字符


2
sum(1for c in range(28)if n[c]==t[c])可能会缩短为sum(n[c]==t[c] for c in range(28))(-3个字符)
AMK 2014年

1
保存5个字符,更改import random as rfrom random import*然后删除以下三个实例r.
Timtech

1
抱歉,我不会说Python。样本输出中的零行仅仅是一个奇怪的巧合,还是您的脚本总是以all开头S?挑战在于从一串随机字符开始。
Iszi 2014年

它以28个随机字符开头,但是它们始终相同。
PsHegger 2014年

@Iszi Lol,它从来没有说过每个角色都必须是随机的!PsHegger:大声笑开头以所有S开头都适合您的语言名称;)
Doorknob

2

PHP(381 397 323 319 312):

<? function s(&$s,&$i=0){$t='METHINKS IT IS LIKE A WEASEL';$i=0;$c=$s;$f=28;while($f--){$n=rand(0,26);$i+=($s[$f]=($c=='_'||!rand(0,19)?chr($n?$n+64:32):$s[$f]))==$t[$f];}}$s='_';s($s);$x=$y=0;do{$f=100;while($f--){$m=$s;s($m,$i);if($i>$y){$y=$i;$l=$m;}}printf("%2d: %s -- score: $y\n",$x++,$s=$l);}while($y<28);

可读版本:

<?
function s(&$s, &$i = 0) {
    $t = 'METHINKS IT IS LIKE A WEASEL';
    $i = 0;
    $c = $s;
    $f = 28; while ($f--) {
        $n = rand(0, 26);
        $i += ($s[$f] = ($c == '_' || !rand(0, 19) ? chr($n ? $n + 64 : 32) : $s[$f])) == $t[$f];
    }
}

$s = '_';
s($s);
$x = $y = 0;

do {
    $f = 100; while ($f--) {
        $m = $s;
        s($m, $i);

        if ($i > $y) {
            $y = $i;
            $l = $m;
        }
    }

    printf("%2d: %s -- score: $y\n", $x++, $s = $l);
} while ($y < 28);

优化学分(319):

优化学分(312):

  • @Einacio的评论

我喜欢联合发生器+随机发生器
Einacio 2014年

你可以既改变for$f=N;while($f--){每3个字符。另一个字符:$n=rand(0,26);[...]chr($n?$n+64:32)
Einacio 2014年

生成器+随机器+分数计算。:)谢谢,我应用了您的优化。
弟弟菲利普(Filip)2014年

2

红宝石218

g,s,p,t=-1,'',1;while t!=28;t,b=-1;100.times{|i|m,n='',0
28.times{|j|n+=1if(m[j]=(rand<p ?[*?A..?Z,' '].sample: s[j]))=="METHINKS IT IS LIKE A WEASEL"[j]}
b,t=m,n if n>t};puts"#{g+=1}: #{s=b} -- score: #{t}";p=0.05;end

示例运行

0: LRAZZMKL IKUOGEHLKPWEVNEAZWX -- score: 6
1: LRAZZMKL IKUIGEALKMWEVNEAZWX -- score: 7
2: HRAGZMKL IKUIGEALKMWEVNEAZWX -- score: 7
3: HVAGZMKL IKUISAALKYWEVNEAZWX -- score: 8
                  ...
48: METHIUKS IT IS LIKEIA WEASEL -- score: 26
49: METHINKS IT IS LIKEIA WEASEL -- score: 27
50: METHINKS IT IS LIKEIA WEASEL -- score: 27
51: METHINKS IT IS LIKE A WEASEL -- score: 28

2

红宝石- 225 202 203 198个字符

到目前为止,Ruby在这项挑战中的代表性不足,所以我想尝试一下!欢迎改进。

g=-1
s=[]
puts"#{g+=1}: #{$.,s=(0..99).map{n=(r=0..27).map{|i|x=[' ',*?A..?Z].sample;rand<0.05?x:s[i]||=x};[r.count{|i|n[i]=='METHINKS IT IS LIKE A WEASEL'[i]},n*'']}.max;s} -- score: #$."until$.>27

在输出中,“世代#”开始于,1但问题指定0。如果您使用g=-1它初始化,那很好。可能有一种更聪明的方法,但我是这样做的。干杯,RubyGolfer。
达伦·斯通

@DarrenStone好的,谢谢!花费一个角色,但我想不出更好的方法。
Paul Prestidge 2014年

1
通过将代码移到字符串中,您可以得到198个字符:(前两行相同,然后其余部分)puts"#{g+=1}: #{$.,s=(0..99).map{n=(r=0..27).map{|i|x=[' ',*?A..?Z].sample;rand<0.05?x:s[i]||=x};[r.count{|i|n[i]=='METHINKS IT IS LIKE A WEASEL'[i]},n*'']}.max;s} -- score: #$."until$.>27
贾斯汀

好决定!我会在编辑它。
保罗Prestidge

2

红宝石,206 200 199

q,i,*R=*-2..27
puts"#{i+=1}: #{$.,s=(-2..q).map{x=R.map{|j|!s||rand<0.05?[*?A..?Z,' '].sample: s[j]};[R.count{|i|x[i]=='METHINKS IT IS LIKE A WEASEL'[i]},x]}.max;q=97;s.join} -- score: #$."until$.>27

第一行是简单地定义一个奇特的方式q=-2i=-1R=(0..27).to_a。所有工作都在第二行中完成:

puts"..."until$.>27 # Prints the string in quotes until we reach the desired score
     ^
     |
 +---+
 |
"#{i+=1}: #{...} -- score: #$."
   ^        ^               ^  
   +--------|---------------|-- Generation counter
 +----------+---------------|-- Current string
 |                          +-- Score of current string (interpolates the `$.` variable)
 |   
 #{$.,s=(-2..q).map{...}.max;q=97;s.join} # Generate the score & string
   ^         ^  ^   ^    ^   ^    ^
   +---------|--|---|----|---|----|------ Store the score; this variable makes
             |  |   |    |   |    |       string interpolation shorter.
             +--|---|----|---+----|------ `q` automatically takes care of generating
                |   |    |        |        the string vs randomizing the string.
                +---|----|--------|------  Make 100 (or 1 the first time) strings,
                    |    |        |        and compute their score.
                    |    +--------|------- Take the string with the max score.
 +------------------+             +------- `s` is stored as an array
 |
 x=R.map{...};[R.count{...},x] # Compute string and its score, store in array
   ^     ^    ^^       ^
   +-----|----|+-------|------ `R` is 0..27, we use the constant to save chars.
         |    +--------|------ `max` orders by first element, then second. We clearly want
         |             |       the highest score, so make the score first.
 +-------+-------------|------ Generate the string, store in `x`.
 |                     +------ Count the number of chars that overlap with 'METHINKS...'
 |                     |
 |                    {|i|x[i]=='METHINKS IT IS LIKE A WEASEL'[i]}
{|j|!s||rand<0.05?[*?A..?Z,' '].sample: s[j]}
    ^   ^         ^             ^       ^
    +---+---------|-------------|-------|---- 5% chance of randomizing, or 100% for
                  |             |       |     first string.
                  +-------------+-------|---- Sample from alphabet + ' '.
                                        +---- Don't alter the string 95% of the time

@ZachGates很高兴您喜欢评论风格
贾斯汀

2

Japt v2.0a0,112 108个字节

ª(T=Si26õdI q¹ö28
_¬í¥`Ú0ˆks Š ‰ ¦ke a Øâel`u q)x
(OpW+`: {U} -- sÖ: `+(K=[U]xV¹WÄ
K<28©ßLÆ®p513 iT ö}ÃñV o

在线尝试!

由于@ ETHproductions,-4个字节。

开箱及其工作方式

U||(T=Si26õdI q) ö28  Initialize primary input
U||                   If U is not initialized...
        26õdI           Generate uppercase alphabets
              q         Convert to string
      Si                Add space
   (T=         )        Assign to variable T
                 ö28    Sample 28 random chars from T and form a string
                        Implicitly assign to U

_q í==`Ú0ˆks Š ‰ ¦ke a Øâel`u q)x  Match counting function
_                                  Declare a function...
 q í==                         )     Convert to array of chars and pair with the next,
                                     and map with equality...
      `Ú0ˆks Š ‰ ¦ke a Øâel`u q        "methinks it is like a weasel" to uppercase
                                        split into chars
                                x    Sum (true == 1, false == 0)
                                   Implicitly assign to V

(OpW+`: {U} -- sÖ: `+(K=[U]xV) W+1  Output and increment counter
(Op                           )      Output with newline...
   W+`: {U} -- sÖ: `+                 `{W}: {U} -- score: `
                         [U]xV         Call V on [U] and force cast to number
                      (K=     )        Assign to K
                                W+1  Add 1 to W and implicitly assign to W

K<28&&ßLo@Um_p513 iT ö}} ñV o  Termination check and recursion
K<28&&                         If the match count is less than 28...
      ß                          Recurse the program with...
          Um_                      Map over chars of U...
             p513 iT                 The char repeated 513 times plus T
                     ö}              Sample a char from it
       Lo@             }           Generate array of 100 of the above
                         ñV o      Sort by V, pop the largest, pass it as U

106个字节,切换到v1.4.5。
粗野的

2

Japt -R,94字节

Bubbler的解决方案中获得启发但有所启发的另一种方法。

;C±S ö28
ȶ`Ú0ks   ¦ke a Øâel`gY
@=#dÆ£20ö ?X:CöÃÃñ_¬xVÃo)ʶG}a@Np[X+':Uu '-²`sÖ:`G=U¬xV]¸

测试(或在线尝试


说明

1号线

结果被分配给变量U

;C±S ö28
;C           :The lower case alphabet
  ±S         :Append a space and reassign result to C
     ö28     :Generate a string of 28 random characters

2号线

结果被分配给变量V

ȶ`Ú...l`gY
È               :A function that takes 2 arguments; a string (X) and an integer (Y)
  `Ú...l`       :  The compressed string "methinks it is like a weasel"
         gY     :  Get the character at index Y
 ¶              :  Test for equality with X

3号线

该行的结果与换行符和输出隐式连接。

@=#dÆ£20ö ?X:CöÃÃñ_¬xVÃo)Ê¥G}a@Np[X+':Uu '-²`sÖ:`G=U¬xV]¸
@                           }a@                            :Repeat until true
                                 [                     ]   :Build an array containing ...
                                  X+':                     :  A colon appended to the number of the current iteration
                                      Uu                   :  The current value of U uppercased
                                         '-²               :  A hyphen repeated twice
                                            `sÖ:`          :  The compressed string "score: "
                                                   U¬      :  Split U to an array of characters
                                                      V    :   Pass each character X at index Y through function V
                                                     x     :   Reduce by addition
                                                 G=        :   Assign the result to variable G
                                                        ¸  :Join with spaces
                               Np                          :Push to N (initially an empty array)
  #d                                                       :100
    Æ                                                      :Generate the range [0,100) and pass each through a function
     £                                                     :  Map over each character X in U
      20ö                                                  :    Generate a random number in the range [0,20), which has a 5% chance of being 0 (falsey)
          ?X                                               :    If thruthy, return X
            :Cö                                            :    Else return a random character from C
               Ã                                           :  End mapping
                Ã                                          :End function
                 ñ_                                        :Sort by passing each through a function
                   ¬                                       :  Split to an array of characters
                     V                                     :  Pass each character X at index Y through function V
                    x                                      :  Reduce by addition
                      Ã                                    :End sorting
                       o                                   :Pop the last element
 =                      )                                  :Reassign to U
                         Ê                                 :Length
                          ¶G                               :Equal to G

2

Perl 5,219字节

$_="METHINKS IT IS LIKE A WEASEL";sub r{(A..Z,$")[rand 27]};sub t{~~grep/$t[$-++%28]/,pop=~/./g}$}.=r for@t=/./g;printf"%3d: %s -- score: %d
",$i++,(($})=sort{t($b)<=>t$a}map s/./rand>.05?$&:r/ger,($})x100),t$}until/$}/

在线尝试!


1

红宝石-410

#!/usr/bin/env ruby
C,RC=[32]+(65..90).to_a,->{C[rand(27)].chr}
T,CO,CH,OU,s,sc,a,aa,z,TR="METHINKS IT IS LIKE A WEASEL",->x{a=0;(0...28).each{|z|a+=1 if x[z]==T[z]};a},->{a[aa.rindex(sc)]},->x,y{print x;print " Score: ";puts y},(0...28).map{RC[]}.join,0,[0],[0],0,->{rand(20)==0}
until sc==28
a=[s]*100;aa=[0]*100;(0...100).each{|x|(0...28).each{|y|a[x][y]=RC[] if TR[]};z=CO[a[x]];aa[x]=CO[a[x]];OU[a[x],z]};sc=aa.max;s=CH[] end

编辑*当前失败(由于某种原因a [any]被设置为0(类型=> fixnum))。但是,实际的设计是正确的,我只需要找到导致这种情况发生的错误(这是非常神秘的)


1

Python 284

from random import*
C=choice
A=map(chr,range(65,91)+[32])
s=[C(A)for i in[0]*28]
N=x=0
while N!=28:N,s=max((len([i for i,j in zip(X,"METHINKS IT IS LIKE A WEASEL")if i==j]),X)for X in[[c if random()<.95 else C(A)for c in s]for i in[0]*100]);print`x`+":",''.join(s),"-- score:",N;x+=1

1

的JavaScript的-312

上面已经有一个较短的JS解决方案,但是它使用的是实验性指针函数,因此我想我会抛出另一个在任何JS环境中运行的解决方案:

for(r=Math.random,R=function(){return'METHINKS CODZAWFLBUGYQRXVJP'[~~(r()*27)]},_=[],_.$=n=0,D=function(s){for(c=[],c.$=i=0;i<28;){c[i]=s&&r()<.95?s[i]:R();_=(c.$+=c[i]=='METHINKS IT IS LIKE A WEASEL'[i++])>_.$?c:_};return c},D();_.$<28;){for(j=0;j++<1e2;)D(_);console.log(n+++': '+_.join('')+' -- score: '+_.$)}

1

Java的:557 534

enum W{W;public static void main(String[]a){char[]c=new char[28],h,d[];int i,k,e,s=W.s(c);for(i=0;i<28;i++)c[i]=W.r();for(i=0;;){W.p(i++,h=c,s);if(s>27)break;d=new char[100][28];for(char[]b:d){for(k=0;k<28;k++)b[k]=Math.random()<.05?W.r():h[k];if((e=W.s(b))>s){s=e;c=b;}}}}int s(char[]c){int s=0,k;for(k=0;k<28;k++)if(c[k]=="METHINKS IT IS LIKE A WEASEL".charAt(k))s++;return s;}void p(int i,char[]c,int s){System.out.println(i+": "+new String(c)+" -- score: "+s);}char r(){int i=(int)(Math.random()*27);return(char)(i==26?32:i+65);}}

展开:

enum W {
    W;

    public static void main(String[] a) {
        char[] c = new char[28], h, d[];

        int i, k, e, s = W.s(c);

        for(i = 0; i < 28; i++)
            c[i] = W.r();

        for(i = 0;;) {
            W.p(i++, h = c, s);

            if(s > 27)
                break;

            d = new char[100][28];

            for(char[] b : d) {
                for(k = 0; k < 28; k++)
                    b[k] = Math.random() < .05 ? W.r() : h[k];

                if((e = W.s(b)) > s) {
                    s = e;
                    c = b;
                }
            }
        }
    }

    int s(char[] c) {
        int s = 0, k;
        for(k = 0; k < 28; k++)
            if(c[k] == "METHINKS IT IS LIKE A WEASEL".charAt(k))
                s++;

        return s;
    }

    void p(int i, char[] c, int s) {
        System.out.println(i + ": " + new String(c) + " -- score: " + s);
    }

    char r() {
        int i = (int)(Math.random() * 27);
        return (char)(i == 26 ? 32 : i + 65);
    }
}

1

的PHP 429 426 421 415

<? function t(){$a="ABCDEFGHIJKLMNOPQRSTUVWXYZ ";return $a{rand(0,26)};}$c='';$j=$g=0;$i=28;while($i--)$c.=t();function r($s){$i=28;while($i--)!rand(0,19)&&$s{$i}=t();return $s;}function s($s,&$r){$c="METHINKS IT IS LIKE A WEASEL";$i=28;$r=0;while($i--)$r+=$s{$i}==$c{$i};}while($g<28){$n='';$v=0;$i=100;while($i--){s($t=r($c),$a);($a>$v)&&($v=$a)&($n=$t);}($v>$g)&&($g=$v)&($c=$n);echo $j++.": $c -- score: $g\n";}

漂亮的印刷品

<?php 
function t(){
    $a="ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
    return $a{rand(0,26)};
}
$c='';
$j=$g=0;
$i=28;
while($i--)
    $c.=t();
function r($s){
    $i=28;
    while($i--)
        !rand(0,19)&&$s{$i}=t();
    return $s;
}
function s($s,&$r){
    $c="METHINKS IT IS LIKE A WEASEL";
    $i=28;
    $r=0;
    while($i--)
        $r+=+($s{$i}==$c{$i});
}
while($g<28){
    $n='';
    $v=0;
    $i=100;
    while($i--){
        s($t=r($c),$a);
        ($a>$v)&&($v=$a)&($n=$t);
    }
    ($v>$g)&&($g=$v)&($c=$n);
    echo $j++.": $c -- score: $g\n";
}

下次我将不需要那么冗长的语言


到目前为止,最短的php答案做得好!
Noelkd 2014年

可能会更好,但是我应该工作
Einacio 2014年

您可以随时回来更新答案
Noelkd 2014年

1

Python 2.7-319字节

当然,它不是最小的,但是编程很有趣。

from random import*
a=map(chr,range(65,91))+[' ']
c,i,y=choice,0,{}
s=[c(a)for i in[0]*28]
while 1:
 for j in[0]*100:v=[c(a)if .05>random()else x for x in s];y[sum(1if'METHINKS IT IS LIKE A WEASEL'[k]==v[k]else 0for k in range(28))]=v
 v=max(y.keys());s=y[v];print"%d: %s -- score: %d"%(i,''.join(y[v]),v);i+=1
 if v==28:break

使用递归函数,因此如果字符串有某种奇怪的下移,它可能会达到最大递归深度。

ubuntu@ubuntu-OptiPlex-980:~$ python weasel.py
0: VPBHBSPWFTOG HAXSESCDNFPKWYE -- score: 1
1: VABHBSPWFTOG HAXSESCDNWPKWYE -- score: 2
2: VAWHBSPWFTOGIHAXSESSDNWPKWYE -- score: 3
3: VAWHBSPWFTOGIHAXSEFSGNWPKWYL -- score: 4
4: XAWHBSPYFTOGIHAXSEFSGNWPKWYL -- score: 4
5: XAWHBSKYFTOGIHAXSEFSGNWPKWYL -- score: 5
6: XAWHBSKYFTOGIHAXSEF GNWPKWYL -- score: 6
7: XAWHBSKYFTOGIHALSEF ANWPKWYL -- score: 8
8: XAKHBSKYFTTGIHALSEY ANWPKWYL -- score: 9
9: XAKHISKYFTTGIHALSEE ANWPKWYL -- score: 11
10: XAKHISKSFTTGIHALSEE ANWPKWYL -- score: 12
11: XAKHISKSFTTGIHALSBE ANWPKWKL -- score: 12
12: XAQHISKSFRT IHALSBE ANWPKWKL -- score: 13
13: XAQHISKSFIT IHALSBE ANWPKWKL -- score: 14
14: XAQHISKSFIT IHALSBE ANWPKWKL -- score: 14
15: XAQHISKSFIT IHALSBE ANWPKWKL -- score: 14
16: XALHISKSFIT ISALSBE ANWPKWKL -- score: 15
17: JALHISKSFIT ISALSBE ANWPAWKL -- score: 16
18: JALHISKSFIT ISALIBE ANWPAWKL -- score: 17
19: JALHISKSFIT ISALIBE ANWPAWKL -- score: 17
20: JALHISKSFIT ISALIBE ANWPAWKL -- score: 17
21: JALHISKSFIT ISALIKE ANWPAWYL -- score: 18
22: JALHISKSFIT IS LIKE ANWPAWYL -- score: 19
23: JALHISKSFIT IS LIKE ANWEAWYL -- score: 20
24: JALHISKSFIT IS LIKE ANWEAWYL -- score: 20
25: JALHISKSFIT IS LIKE ANWEAWZL -- score: 20
26: JALHISKS IT IS LIKE ANWEAAZL -- score: 21
27: JACHISKS IT IS LIKE ANWEASZL -- score: 22
28: JACHISKS IT IS LIKE ANWEASZL -- score: 22
29: MACHISKS IT IS LIKE ANWEASZL -- score: 23
30: MACHISKS IT IS LIKE ANWEASZL -- score: 23
31: MACHISKS IT IS LIKE AUWEASZL -- score: 23
32: MACHISKS IT IS LIKE AUWEASZL -- score: 23
33: MACHISKS IT IS LIKE AJWEASZL -- score: 23
34: MACHISKS IT IS LIKE A WEASZL -- score: 24
35: MACHISKS IT IS LIKE A WEASZL -- score: 24
36: MACHINKS IT IS LIKE A WEASZL -- score: 25
37: MACHINKS IT IS LIKE A WEASZL -- score: 25
38: MACHINKS IT IS LIKE A WEASZL -- score: 25
39: MBCHINKS IT IS LIKE A WEASZL -- score: 25
40: MBCHINKS IT IS LIKE A WEASZL -- score: 25
41: MBCHINKS IT IS LIKE A WEASZL -- score: 25
42: MBCHINKS IT IS LIKE A WEASZL -- score: 25
43: MBCHINKS IT IS LIKE A WEASZL -- score: 25
44: MBCHINKS IT IS LIKE A WEASZL -- score: 25
45: MECHINKS IT IS LIKE A WEASCL -- score: 26
46: MECHINKS IT IS LIKE A WEASCL -- score: 26
47: MECHINKS IT IS LIKE A WEASCL -- score: 26
48: MECHINKS IT IS LIKE A WEASCL -- score: 26
49: MECHINKS IT IS LIKE A WEASCL -- score: 26
50: MECHINKS IT IS LIKE A WEASCL -- score: 26
51: MEQHINKS IT IS LIKE A WEASCL -- score: 26
52: MEQHINKS IT IS LIKE A WEASCL -- score: 26
53: MEQHINKS IT IS LIKE A WEASCL -- score: 26
54: MEQHINKS IT IS LIKE A WEASCL -- score: 26
55: MEQHINKS IT IS LIKE A WEASCL -- score: 26
56: MEQHINKS IT IS LIKE A WEASCL -- score: 26
57: METHINKS IT IS LIKE A WEASCL -- score: 27
58: METHINKS IT IS LIKE A WEASCL -- score: 27
59: METHINKS IT IS LIKE A WEASCL -- score: 27
60: METHINKS IT IS LIKE A WEASCL -- score: 27
61: METHINKS IT IS LIKE A WEASCL -- score: 27
62: METHINKS IT IS LIKE A WEASCL -- score: 27
63: METHINKS IT IS LIKE A WEASCL -- score: 27
64: METHINKS IT IS LIKE A WEASCL -- score: 27
65: METHINKS IT IS LIKE A WEASEL -- score: 28

非常感谢Sp3000提供的高尔夫帮助。


1

朱莉娅281字节

打高尔夫球:

r=n->['A':'Z',' '][rand(1:27,n)]
s=a->sum(a.=="METHINKS IT IS LIKE A WEASEL".data)
p=(z,a,s)->println(z,": ",join(a)," -- score: ",s)
a = r(28)
b = s(a)
z = 0
p(z,a,b)
while b<28
c=b
d=a
for i=1:100
e=[rand()<.95?i:r(1)[1]for i=a]
f=s(e)
if(f>c)
c=f
d=e
end
end
a=d
b=c
p(z,a,b)
z+=1
end

该算法本身不是很聪明,但是这里有一些很棒的地方。结合了字符范围与其他字符,然后索引到它:['A':'Z',' '][rand(1:27,n)]和以boolean数组的总和(常见,但我还是喜欢这个主意)sum(a.=="METHINKS IT IS LIKE A WEASEL".data)。很高兴我不到300岁!

取消高尔夫:

randchar = n -> ['A':'Z',' '][rand(1:27,n)]
score = a -> sum(a.=="METHINKS IT IS LIKE A WEASEL".data)
myprint = (z,a,s) -> println(z,": ",join(a)," -- score: ",s)
currentarray = randchar(28)
currentscore = score(currentarray)
z = 0
myprint(z,currentarray,currentscore)
while currentscore < 28
    bestscore = currentscore
    bestarray = currentarray
    for i = 1:100
        temparray = [rand()<.95?i:randchar(1)[1]for i=currentarray]
        tempscore = score(temparray)
        if(tempscore > bestscore)
            bestscore = tempscore
            bestarray = temparray
        end
    end
    currentarray = bestarray
    currentscore = bestscore
    myprint(z,currentarray,currentscore)
    z+=1
end
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.