Дарина обнови решението на 18.12.2011 21:10 (преди около 13 години)
+# encoding: UTF-8
+
+module GameOfLife
+
+ Board = Class.new do
+ def initialize *live
+ @live_cells, @next_gen, @dead_and_alive = [], [], []
+ @surrounding = [[-1,1], [0,1], [1,1], [-1, 0], [1,0], [-1,-1], [0,-1], [1,-1]]
+ live.each { |cell| init_dead_and_live(cell[0], cell[1]) }
+ @live_cells = @live_cells.uniq
+ end
+
+ def init_dead_and_live(x, y)
+ @live_cells << [x, y]
+ @surrounding.each { |surround| @dead_and_alive << [x + surround[0], y + surround[1]] }
+ @dead_and_alive = @dead_and_alive.uniq
+ end
+
+ def [](x,y)
+ cell = [x, y]
+ @live_cells.include?(cell)
+ end
+
+ def method_missing(name, *args, &block)
+ @live_cells.send(name, *args, &block)
+ end
+
+ def each
+ @live_cells.each { |coord| yield(coord[0], coord[1]) }
+ end
+
+ def alive(cell, live_neigbours)
+ @next_gen << cell if live_neigbours == 2 or live_neigbours == 3
+ end
+
+ def dead(cell, live_neigbours)
+ @next_gen << cell if live_neigbours == 3
+ end
+
+ def live_neighbour(x, y)
+ self[x, y] ? 1 : 0
+ end
+
+ def neighbours(x, y)
+ cnt = 0
+ @surrounding.each do |surround|
+ cnt = cnt + live_neighbour(x + surround[0], y + surround[1])
+ end
+ self[x,y] ? alive([x,y], cnt) : dead([x,y], cnt)
+ end
+
+ def next_generation
+ @dead_and_alive.each { |cell| neighbours(cell[0], cell[1]) }
+ Board.new *@next_gen.uniq
+ end
+ end
+end
Ха, това решение ме изненада на няколко места. Бих искал да го обсъдим, намери ме някое междучасие и ми кажи "за решението на 6-та, с Class.new
" :)
Бърза бележка: #!/usr/bin/env ruby
е това, което трябва да ползваш като shebang), ако искаш да имаш такова нещо изобщо.