Last active
August 29, 2015 14:16
-
-
Save hovsater/d3dc9c3a0027eefe2677 to your computer and use it in GitHub Desktop.
Conway Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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