Skip to content

Instantly share code, notes, and snippets.

@sathish316

sathish316/gol.rb

Created Feb 9, 2012
Embed
What would you like to do?
Game of life golf
d=[-1,0,1] n=->(w,i,j){(d.product(d)-[[0,0]]).map{|x,y|w[[i+x,j+y]]}.count(true)} t=->(w){Hash[w.map{|k,v|c=n.(w,*k);[k,(v&&c==2)||c==3]}]}
@sathish316

This comment has been minimized.

Copy link
Owner Author

@sathish316 sathish316 commented May 17, 2012

Usage example:

def pattern(grid)
  world = {}
  grid.split.each_with_index do |line,i|
    line.chars.each_with_index do |char,j|
      world[[i,j]] = (char == 'X')
    end
  end
  world
end

def display(world)
  max_x = world.keys.map(&:first).max + 1
  max_y = world.keys.map(&:last).max + 1
  max_x.times do |i|
    max_y.times do |j|
      print (world[[i,j]] ? 'X' : '.')
    end
    puts
  end
end

w = pattern <<-G
.....
..X..
..X..
..X..
.....
G

while(true)
  system 'clear'
  display(w)
  w = t.(w)
  sleep(2)
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment