Skip to content

Instantly share code, notes, and snippets.

@fallengiants
Created July 18, 2018 17:04
Show Gist options
  • Select an option

  • Save fallengiants/54a3534753fc426ad00ccf84a41d1b50 to your computer and use it in GitHub Desktop.

Select an option

Save fallengiants/54a3534753fc426ad00ccf84a41d1b50 to your computer and use it in GitHub Desktop.
# Cheaty idea
class Conway
def initialize(height, width)
@height = height
@width = width
@cells = [0] * width
end
def set_cell(x,y,v) # v is a boolean value
if v
@cells[x % @width] |= 1 << y
else
@cells[x % @width] ^= 1 << y
end
end
def multicell_state(*array_of_points)
points = Hash.new
array_of_points.map do |x,y|
points[x] ||= []
points[x].push(y) if y >= 0 and y < @height
end
hits = 0
points.each_pair do |x, y|
hitmash = @cells[x % @width] & y.reduce(0) {|s,i| s |= 1 << i}
hits += y.reduce(0) {|s,i| s += 1 if (hitmash & (1<<i)) > 0}
end
hits
end
def num_neighbors(x,y)
multicell_state( [x-1, y], [x+1, y], [x,y-1], [x,y+1] )
end
end
# Test
if __FILE__ == $0
life = Conway.new(5,5)
life.set_cell(1,1,true)
life.set_cell(1,3,true)
life.set_cell(0,2,true)
life.set_cell(2,2,true)
puts life.num_neighbors(1,2) #=> 4
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment