hb2*_*cil 76 language-agnostic code-golf conways-game-of-life rosetta-stone
挑战:编写实现John H. Conway的Game of Life元胞子自动机的最短程序.[ 链接 ]
编辑:经过大约一周的比赛,我选择了一个胜利者:pdehaan,用perl 打算用一个角色击败Matlab解决方案.
对于那些没有听过生命游戏的人来说,你需要一个方格单元格(理想情况下是无限的).细胞可以存活(填充)或死亡(空).我们通过应用以下规则确定下一步中哪些细胞存活:
您的程序将读入指定为命令行参数的40x80字符ASCII文本文件,以及要执行的迭代次数(N).最后,它将在N次迭代后输出到ASCII文件out.txt系统的状态.
以下是运行相关文件的示例:
in.txt:
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
..................................XX............................................
..................................X.............................................
.......................................X........................................
................................XXXXXX.X........................................
................................X...............................................
.................................XX.XX...XX.....................................
..................................X.X....X.X....................................
..................................X.X......X....................................
...................................X.......XX...................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
Run Code Online (Sandbox Code Playgroud)
迭代100次:
Q:\>life in.txt 100
Run Code Online (Sandbox Code Playgroud)
结果输出(out.txt)
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
..................................XX............................................
..................................X.X...........................................
....................................X...........................................
................................XXXXX.XX........................................
................................X.....X.........................................
.................................XX.XX...XX.....................................
..................................X.X....X.X....................................
..................................X.X......X....................................
...................................X.......XX...................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
Run Code Online (Sandbox Code Playgroud)
规则:
获胜者将由角色数决定.
祝好运!
Dr.*_*ius 40
__CODE__
未初始化,因此您的程序会运行到未定义的行为.您可以执行以下操作:
a = {2, 2, 2}; s = Export["out.txt", CellularAutomaton[{224, {2, {a, {2, 1, 2}, a}}, {1,1}}, (ReadList[#1, Byte, RecordLists → 2>1] - 46)/ 42, #2]〚#2〛 /. {0 → ".", 1 → "X"}, "Table"] &Run Code Online (Sandbox Code Playgroud)
并称之为:
s["c:\life.txt", 100]
Run Code Online (Sandbox Code Playgroud)
gno*_*ice 33
功能语法:(124个字符)
这是更容易阅读的版本(添加了不必要的换行符和空格以便更好地格式化):
function l(f,N),
b=char(importdata(f))>46;
for c=1:N,
b=~fix(filter2(ones(3),b)-b/2-3);
end;
dlmwrite('out.txt',char(b*42+46),'')
Run Code Online (Sandbox Code Playgroud)
以下是从MATLAB命令窗口运行程序的方法:
l('in.txt',100)
Run Code Online (Sandbox Code Playgroud)
命令语法:(130个字符)
有关调用函数有一个命令语法评论后,我挖得更深一些,并且发现了MATLAB功能可以在事实与命令行格式调用(有一些限制).你每天学习新的东西!
function l(f,N),
b=char(importdata(f))>46;
for c=1:eval(N),
b=~fix(filter2(ones(3),b)-b/2-3);
end;
dlmwrite('out.txt',char(b*42+46),'')
Run Code Online (Sandbox Code Playgroud)
以下是从MATLAB命令窗口运行程序的方法:
l in.txt 100
Run Code Online (Sandbox Code Playgroud)
我觉得很有趣我会看到我是否可以将输出转储到GIF文件而不是文本文件,同时仍然保持字符数低于140(即"tweetable").这是格式良好的代码:
function l(f,N),
b=char(importdata(f))>46;
k=ones(3);
for c=1:N+1,
a(:,:,:,c)=kron(b,k);
b=~fix(filter2(k,b)-b/2-3);
end;
imwrite(~a,'out.gif')
Run Code Online (Sandbox Code Playgroud)
虽然IMWRITE应该创建一个默认无限循环的GIF,但我的GIF只循环一次.也许这是一个已在较新版本的MATLAB中修复的错误.因此,为了使动画持续更长时间并使演化步骤更容易看到,我将帧延迟保留为默认值(这似乎是大约半秒).这是使用Gosper Glider Gun模式的GIF输出:
b
从逻辑(即"布尔")类型更改为数字类型,以消除一些转换.~~b+0
用b/42
,换成'same'
与's'
作为参数传递给CONV2(和它令人惊讶的还是工作!).b
回逻辑矩阵.b
并重新设置循环中的逻辑以保存1个附加字符.cell2mat
用char
,节省了4个字符.谢谢埃里克!Mla*_*vić 30
f,n=$*
c=IO.read f
n.to_i.times{i=0;c=c.chars.map{|v|i+=1
v<?.?v:('...X'+v)[[83,2,-79].map{|j|c[i-j,3]}.to_s.count ?X]||?.}*''}
File.new('out.txt',?w)<<c
Run Code Online (Sandbox Code Playgroud)
编辑:
处理换行符少于4个字符.如果你允许活细胞到达边缘时允许它破坏换行符,
可以删除7个以上(v<?.?v:
).
pde*_*aan 24
管理剥离几个字符......
$/=pop;@b=split'',<>;map{$n=-1;@b=map{++$n;/
/?$_:($t=grep/X/,@b[map{$n+$_,$n-$_}1,80..82])==3|$t+/X/==3?X:'.'}@b}1..$/;print@b
Run Code Online (Sandbox Code Playgroud)
Joh*_*ooy 20
不妨让球滚动......
import sys
_,I,N=sys.argv;R=range(3e3);B=open(I).read();B=set(k for k in R if'A'<B[k])
for k in R*int(N):
if k<1:b,B=B,set()
c=sum(len(set((k+o,k-o))&b)for o in(1,80,81,82))
if(c==3)+(c==2)*(k in b):B.add(k)
open('out.txt','w').write(''.join('.X\n'[(k in B)-(k%81<1)]for k in R))
Run Code Online (Sandbox Code Playgroud)
P D*_*ddy 20
好吧,210个字符的代码有点作弊.
#coding:l1
exec'xÚ=ŽA\nÂ@E÷sŠº1ƒÆscS‰ØL™Æª··âî¿GÈÿÜ´1iÖ½;Sçu.~H®J×Þ-‰Ñ%ª.wê,šÖ§J®d꘲>cÉZË¢V䀻Eîa¿,vKAËÀå̃<»Gce‚ÿ‡ábUt¹)G%£êŠ…óbÒüíÚ¯GÔ/n×Xši&ć:})äðtÏÄJÎòDˆÐÿG¶'.decode('zip')
Run Code Online (Sandbox Code Playgroud)
您可能无法复制和粘贴此代码并使其工作.它应该是Latin-1(ISO-8859-1),但我认为它在某个地方的某个地方变成了Windows-1252.此外,您的浏览器可能会吞下一些非ASCII字符.
因此,如果它不起作用,您可以从普通的7位字符生成文件:
s = """
23 63 6F 64 69 6E 67 3A 6C 31 0A 65 78 65 63 27 78 DA 3D 8E 41 5C 6E C2
40 0C 45 F7 73 8A BA 31 13 AD 83 15 11 11 C6 73 08 63 17 05 53 89 D8 4C
99 C6 AA B7 B7 AD E2 EE BF 47 C8 FF DC B4 31 69 D6 BD 3B 53 E7 75 2E 7E
48 AE 4A D7 DE 90 8F 2D 89 AD D1 25 AA 2E 77 16 EA 2C 9A D6 A7 4A AE 64
EA 98 B2 3E 63 C9 5A CB A2 56 10 0F E4 03 80 BB 45 16 0B EE 04 61 BF 2C
76 0B 4B 41 CB C0 E5 CC 83 03 3C 1E BB 47 63 65 82 FF 87 E1 62 55 1C 74
B9 29 47 25 A3 EA 03 0F 8A 07 85 F3 62 D2 FC ED DA AF 11 47 D4 2F 6E D7
58 9A 69 26 C4 87 3A 7D 29 E4 F0 04 74 CF C4 4A 16 CE F2 1B 44 88 1F D0
FF 47 B6 27 2E 64 65 63 6F 64 65 28 27 7A 69 70 27 29
"""
with open('life.py', 'wb') as f:
f.write(''.join(chr(int(i, 16)) for i in s.split()))
Run Code Online (Sandbox Code Playgroud)
结果是一个有效的210个字符的Python源文件.我在这里所做的就是在原始Python源代码上使用zip压缩.真正的欺骗是我在结果字符串中使用非ASCII字符.它仍然是有效的代码,它只是很麻烦.
我认为,非压缩版本的重量为234个字符,这仍然是可敬的.
import sys
f,f,n=sys.argv
e=open(f).readlines()
p=range
for v in p(int(n)):e=[''.join('.X'[8+16*(e[t][i]!='.')>>sum(n!='.'for v in e[t-1:t+2]for n in v[i-1:i+2])&1]for i in p(80))for t in p(40)]
open('out.txt','w').write('\n'.join(e))
Run Code Online (Sandbox Code Playgroud)
抱歉水平滚动,但上面的所有换行都是必需的,我将它们统计为每个一个字符.
我不会尝试阅读高尔夫代码.随机选择变量名称以实现最佳压缩.是的,我很认真.以下是更好格式化和评论的版本:
# get command-line arguments: infile and count
import sys
ignored, infile, count = sys.argv
# read the input into a list (each input line is a string in the list)
data = open(infile).readlines()
# loop the number of times requested on the command line
for loop in range(int(count)):
# this monstrosity applies the rules for each iteration, replacing
# the cell data with the next generation
data = [''.join(
# choose the next generation's cell from '.' for
# dead, or 'X' for alive
'.X'[
# here, we build a simple bitmask that implements
# the generational rules. A bit from this integer
# will be chosen by the count of live cells in
# the 3x3 grid surrounding the current cell.
#
# if the current cell is dead, this bitmask will
# be 8 (0b0000001000). Since only bit 3 is set,
# the next-generation cell will only be alive if
# there are exactly 3 living neighbors in this
# generation.
#
# if the current cell is alive, the bitmask will
# be 24 (8 + 16, 0b0000011000). Since both bits
# 3 and 4 are set, this cell will survive if there
# are either 3 or 4 living cells in its neighborhood,
# including itself
8 + 16 * (data[y][x] != '.')
# shift the relevant bit into position
>>
# by the count of living cells in the 3x3 grid
sum(character != '.' # booleans will convert to 0 or 1
for row in data[y - 1 : y + 2]
for character in row[x - 1 : x + 2]
)
# select the relevant bit
& 1
]
# for each column and row
for x in range(80)
)
for y in range(40)
]
# write the results out
open('out.txt','w').write('\n'.join(data))
Run Code Online (Sandbox Code Playgroud)
对不起,Pythonistas,对于C-ish括号格式,但我试图弄清楚每个括号是什么关闭.
Ale*_*nov 14
import System
main=do f:n:_<-getArgs;s<-readFile f;writeFile"out.txt"$t s$read n
p '\n'_='\n'
p 'X'2='X'
p _ 3='X'
p _ _='.'
t r 0=r
t r n=t[p(r!!m)$sum[1|d<-1:[80..82],s<-[1,-1],-m<=d*s,m+d*s<3240,'X'==r!!(m+d*s)]|m<-[0..3239]]$n-1
Run Code Online (Sandbox Code Playgroud)
Bri*_*ian 10
我可以减少很多,但我喜欢这个,因为它仍然在球场,非常可读.
open System.IO
let mutable a:_[,]=null
let N y x=
[-1,-1;-1,0;-1,1;0,-1;0,1;1,-1;1,0;1,1]
|>Seq.sumBy(fun(i,j)->try if a.[y+i,x+j]='X' then 1 else 0 with _->0)
[<EntryPoint>]
let M(r)=
let b=File.ReadAllLines(r.[0])
a<-Array2D.init 40 80(fun y x->b.[y].[x])
for i=1 to int r.[1] do
a<-Array2D.init 40 80(fun y x->
match N y x with|3->'X'|2 when a.[y,x]='X'->'X'|_->'.')
File.WriteAllLines("out.txt",Array.init 40(fun y->
System.String(Array.init 80(fun x->a.[y,x]))))
0
Run Code Online (Sandbox Code Playgroud)
编辑
根据要求,这是我的下一个刺:
open System
let mutable a,k=null,Array2D.init 40 80
[<EntryPoint>]
let M r=
a<-k(fun y x->IO.File.ReadAllLines(r.[0]).[y].[x])
for i=1 to int r.[1] do a<-k(fun y x->match Seq.sumBy(fun(i,j)->try if a.[y+i,x+j]='X'then 1 else 0 with _->0)[-1,-1;-1,0;-1,1;0,-1;0,1;1,-1;1,0;1,1]with|3->'X'|2 when a.[y,x]='X'->'X'|_->'.')
IO.File.WriteAllLines("out.txt",Array.init 40(fun y->String(Array.init 80(fun x->a.[y,x]))))
0
Run Code Online (Sandbox Code Playgroud)
一些基本的打高尔夫球,减少了14%.我不禁觉得我在使用2D数组/字符串数组而不是一维数组而失败,但现在感觉不喜欢这样做.请注意我如何优雅地读取文件3200次来初始化我的数组:)
ASh*_*lly 10
Ruby 1.8: 178 175 chars
f,n=$*;b=IO.read f
n.to_i.times{s=b.dup
s.size.times{|i|t=([82,1,-80].map{|o|b[i-o,3]||''}*'').count 'X'
s[i]=t==3||b[i]-t==?T??X:?.if s[i]>13};b=s}
File.new('out.txt','w')<<b
Run Code Online (Sandbox Code Playgroud)
换行很重要(尽管所有换行都可以用分号代替.)
编辑:修复换行问题,并修剪3个字符.
Mol*_*ill 10
只是玩弄BalusC的解决方案.有限的声誉意味着我无法添加任何评论作为他的评论.
class M{public static void main(String[]a)throws Exception{int t=3240,j=t,i=new Integer(a[1])*t+t;char[]b=new char[i+t],p={1,80,81,82};for(new java.io.FileReader(a[0]).read(b,t,t);j<i;){char c=b[j],l=0;for(int n:p)l+=b[j+n]/88+b[j-n]/88;b[j+++t]=c>10?(l==3|l+c==90?88:'.'):c;}new java.io.FileWriter("out.txt").append(new String(b,j,t)).close();}}
Run Code Online (Sandbox Code Playgroud)
更具可读性(?)版本:
class M{
public static void main(String[]a)throws Exception{
int t=3240,j=t,i=new Integer(a[1])*t+t;
char[]b=new char[i+t],p={1,80,81,82};
for(new java.io.FileReader(a[0]).read(b,t,t);j<i;){
char c=b[j],l=0;
for(int n:p)l+=b[j+n]/88+b[j-n]/88;
b[j+++t]=c>10?(l==3|l+c==90?88:'.'):c;
}
new java.io.FileWriter("out.txt").append(new String(b,j,t)).close();
}
}
Run Code Online (Sandbox Code Playgroud)
斯卡拉 - 467 364 339字符
object G{def main(a:Array[String]){val l=io.Source.fromFile(new java.io.File(a(0)))getLines("\n")map(_.toSeq)toSeq
val f=new java.io.FileWriter("out.txt")
f.write((1 to a(1).toInt).foldLeft(l){(t,_)=>(for(y<-0 to 39)yield(for(x<-0 to 79)yield{if(x%79==0|y%39==0)'.'else{val m=t(y-1)
val p=t(y+1);val s=Seq(m(x-1),m(x),m(x+1),t(y)(x-1),t(y)(x+1),p(x-1),p(x),p(x+1)).count('X'==_)
if(s==3|(s==2&t(y)(x)=='X'))'X'else'.'}})toSeq)toSeq}map(_.mkString)mkString("\n"))
f.close}}
Run Code Online (Sandbox Code Playgroud)
我认为还有很大的改进空间......
[编辑]是的,它是:
object G{def main(a:Array[String]){var l=io.Source.fromFile(new java.io.File(a(0))).mkString
val f=new java.io.FileWriter("out.txt")
var i=a(1).toInt
while(i>0){l=l.zipWithIndex.map{case(c,n)=>if(c=='\n')'\n'else{val s=Seq(-83,-82,-81,-1,1,81,82,83).map(_+n).filter(k=>k>=0&k<l.size).count(l(_)=='X')
if(s==3|(s==2&c=='X'))'X'else'.'}}.mkString
i-=1}
f.write(l)
f.close}}
Run Code Online (Sandbox Code Playgroud)
[编辑]我觉得还有更多要挤出来......
object G{def main(a:Array[String]){val f=new java.io.FileWriter("out.txt")
f.write(((1 to a(1).toInt):\(io.Source.fromFile(new java.io.File(a(0))).mkString)){(_,m)=>m.zipWithIndex.map{case(c,n)=>
val s=Seq(-83,-82,-81,-1,1,81,82,83)count(k=>k+n>=0&k+n<m.size&&m(k+n)=='X')
if(c=='\n')c else if(s==3|s==2&c=='X')'X'else'.'}.mkString})
f.close}}
Run Code Online (Sandbox Code Playgroud)
以下解决方案使用我自己的自定义域特定编程语言,我称之为NULL:
3499538
Run Code Online (Sandbox Code Playgroud)
如果您想知道它是如何工作的:我的语言只包含每个程序的一个语句.该语句表示属于代码高尔夫线程的StackOverflow线程ID.我的编译器将其编译成一个程序,该程序寻找最佳的javascript解决方案(使用SO API),下载并在Web浏览器中运行它.
运行时可能对新线程更好(可能需要一些时间才能出现第一个upvoted Javascript答案),但从好处来看,它只需要非常少的编码技能.
a=process.argv
f=require('fs')
m=46
t=f.readFileSync(a[2])
while(a[3]--)t=[].map.call(t,function(c,i){for(n=g=0;e=[-82,-81,-80,-1,1,80,81,82][g++];)t[i+e]>m&&n++
return c<m?c:c==m&&n==3||c>m&&n>1&&n<4?88:m})
f.writeFile('out.txt',t)
Run Code Online (Sandbox Code Playgroud)
只是想知道我的java解决方案可以用多少更小和更丑的C.减少到300,包括预处理器位的换行符.将内存释放到操作系统!假设OS将关闭并刷新文件,可以节省~20.
#include<stdio.h>
#include<stdlib.h>
#define A(N)j[-N]/88+j[N]/88
int main(int l,char**a){
int t=3240,i=atoi(a[2])*t+t;
char*b=malloc(i+t),*j;
FILE*f;
fread(j=b+t,1,t,fopen(a[1],"r"));
for(;j-b-i;j++[t]=*j>10?l==3|l+*j==90?88:46:10)
l=A(1)+A(80)+A(81)+A(82);
fwrite(j,1,t,f=fopen("out.txt","w"));
fclose(f);
}
Run Code Online (Sandbox Code Playgroud)
MUMPS:314个字符
L(F,N,R=40,C=80)
N (F,N,R,C)
O F:"RS" U F D C F
.F I=1:1:R R L F J=1:1:C S G(0,I,J)=($E(L,J)="X")
F A=0:1:N-1 F I=1:1:R F J=1:1:C D S G(A+1,I,J)=$S(X=2:G(A,I,J),X=3:1,1:0)
.S X=0 F i=-1:1:1 F j=-1:1:1 I i!j S X=X+$G(G(A,I+i,J+j))
S F="OUT.TXT" O F:"WNS" U F D C F
.F I=1:1:R F J=1:1:C W $S(G(N,I,J):"X",1:".") W:J=C !
Q
Run Code Online (Sandbox Code Playgroud)