Ивайло обнови решението на 20.12.2011 12:37 (преди около 13 години)
+module GameOfLife
+ class Board
+ def initialize *arg
+ init_members
+ init_dimensions arg
+ (0...@matrix_rows).each { |x| @ma3x[x] = Array.new @matrix_cols, 0 }
+ arg.each { |cell| @ma3x[cell[0]][cell[1]] = 1 }
+ end
+
+ def init_members
+ @points = []
+ @ma3x = []
+ @matrix_rows = 0
+ @matrix_cols = 0
+ end
+
+ def each
+ @points.each { |point| yield point }
+ end
+
+ def init_dimensions arg
+ arg.each do |x|
+ @points << x
+ @matrix_cols < x[1] + 1 ? @matrix_cols = x[1] + 1: nil
+ @matrix_rows < x[0] + 1 ? @matrix_rows = x[0] + 1: nil
+ end
+ end
+
+ def [] x, y
+ @points.each do |p|
+ if p[0] == x && p[1] == y
+ return true
+ end
+ end
+ return false
+ end
+
+ def count
+ @points.size
+ end
+
+ def next_generation
+ helper = BoardHelper.new @matrix_cols, @matrix_rows, @ma3x
+ helper.next_gen
+ end
+ end
+
+ class BoardHelper
+ def initialize cols, rows, ma3x
+ @cols = cols
+ @rows = rows
+ @ma3x = ma3x
+ end
+
+ def next_gen
+ new_points = []
+ @ma3x.each_index do |row|
+ add_points! row, new_points
+ end
+ Board.new *new_points
+ end
+
+ def add_points! row, new_points
+ @ma3x[row].each_index do |cell|
+ res = (new_cell row, cell)
+ if res then new_points << res end
+ end
+ end
+
+ def new_cell x, y
+ if ((@ma3x[x][y] == 1) && (alive_neighbours(x, y) < 2)) then return nil end
+ if ((@ma3x[x][y] == 1) && (2..3).include?(alive_neighbours(x, y))) then return [x,y] end
+ if ((@ma3x[x][y] == 1) && (alive_neighbours(x, y) > 3)) then return nil end
+ if ((@ma3x[x][y] == 0) && (alive_neighbours(x, y) == 3)) then return [x,y] end
+ end
+
+ def alive_neighbours x, y
+ (cell_value x - 1, y - 1) + (cell_value x - 1, y) + (cell_value x - 1, y + 1) +
+ (cell_value x, y - 1) + (cell_value x, y + 1) +
+ (cell_value x + 1, y - 1) + (cell_value x + 1, y) + (cell_value x + 1, y + 1)
+ end
+
+ def cell_value x, y
+ x >= 0 && x < @rows && y >= 0 && y < @cols ? @ma3x[x][y] : 0
+ end
+ end
+end