Skip to content

Instantly share code, notes, and snippets.

@hovsater
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hovsater/d3dc9c3a0027eefe2677 to your computer and use it in GitHub Desktop.
Save hovsater/d3dc9c3a0027eefe2677 to your computer and use it in GitHub Desktop.
Conway Ruby
def parse(filename)
contents = File.read(filename)
[contents.gsub("\n", "").split(//), contents.split[0].size]
end
def neighbours(i, s)
f,l=[i%s==0,i%s==s-1]
[(f ? -1 : i-s-1),i-s,(l ? -1 : i-s+1),(f ? -1 : i-1),(l ? -1 : i+1),(f ? -1 : i+s-1),i+s,(l ? -1 : i+s+1) ].reject { |i| i < 0 }
end
g,s=parse(ARGV[0])
while true do
system "clear"
g=g.each_with_object([]).with_index do |(c, ng), i|
a=neighbours(i,s).map { |i| g[i] }.count("X")
ng[i]=c=="X" ? (a<2 || a>3) ? "O" : "X" : (a==3) ? "X" : "O"
end
g.each_slice(s) { |r| puts r.join }
sleep 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment