Георги обнови решението на 17.12.2011 17:03 (преди около 13 години)
+module GameOfLife
+
+ class Board
+
+ def initialize(*coords)
+ return 0 if coords == nil
+ @living = coords.uniq
+ @diffs = [[-1, -1],[-1, 0],[-1, 1],[0, -1],[0, 1],[1, -1],[1, 0],[1, 1]]
+ #@neighbours_count = Hash.new(0)
+ end
+
+ def [](a, b)
+ (@living.count([a, b]) > 0)
+ end
+
+ def count_neighbours()
+ neighbours = Hash.new(0)
+ @living.each do |x, y|
+ @diffs.each {|px, py| neighbours[[x + px, y + py]] += 1}
+ end
+ neighbours
+ end
+
+ def proccess_cell(k, v, generation)
+ if (@living.count(k) > 0 and (v == 2 or v == 3)) or (@living.count(k) == 0 and v == 3)
+ generation << k
+ end
+ generation
+ end
+
+
+ def next_generation()
+ neighbours, new_generation = count_neighbours(), []
+ neighbours.each do |k, v|
+ new_generation = proccess_cell(k, v, new_generation)
+ end
+ Board.new(*coords = new_generation)
+ end
+
+ def each()
+ @living.each do |x, y|
+ yield x, y
+ end
+ end
+
+ def count()
+ @living.size
+ end
+
+ def to_a()
+ @living
+ end
+
+ end
+
+end