Решение на Шеста задача от Димо Станев

Обратно към всички решения

Към профила на Димо Станев

Резултати

  • 6 точки от тестове
  • 0 бонус точки
  • 6 точки общо
  • 18 успешни тест(а)
  • 0 неуспешни тест(а)

Код

module GameOfLife
class Board
include Enumerable
def initialize *cells
@list = cells.uniq
end
def each
@list.each { |cell| yield cell }
end
def neighbours cell
x, y = cell
[[x + 1, y], [x + 1, y + 1], [x + 1, y - 1], [x, y + 1],
[x - 1, y], [x - 1, y + 1], [x - 1, y - 1], [x, y - 1]]
end
def alive_neighbours cell
(neighbours cell).select { |cell| @list.include? cell }.size
end
def [] *cell
@list.include? cell
end
def staying_alive_cells
@list.select { |cell| alive_neighbours(cell) == 2 or alive_neighbours(cell) == 3 }
end
def new_born_cells
all_neighbours = @list.inject([]) { |cells, cell| cells | neighbours(cell) }
all_neighbours.select { |cell| alive_neighbours(cell) == 3}
end
def next_generation
Board.new *(staying_alive_cells | new_born_cells)
end
end
end

Лог от изпълнението

..................

Finished in 0.51065 seconds
18 examples, 0 failures

История (1 версия и 1 коментар)

Димо обнови решението на 15.12.2011 01:40 (преди над 12 години)

+module GameOfLife
+
+ class Board
+ include Enumerable
+
+ def initialize *cells
+ @list = cells.uniq
+ end
+
+ def each
+ @list.each { |cell| yield cell }
+ end
+
+ def neighbours cell
+ x, y = cell
+ [[x + 1, y], [x + 1, y + 1], [x + 1, y - 1], [x, y + 1],
+ [x - 1, y], [x - 1, y + 1], [x - 1, y - 1], [x, y - 1]]
+ end
+
+ def alive_neighbours cell
+ (neighbours cell).select { |cell| @list.include? cell }.size
+ end
+
+ def [] *cell
+ @list.include? cell
+ end
+
+ def staying_alive_cells
+ @list.select { |cell| alive_neighbours(cell) == 2 or alive_neighbours(cell) == 3 }
+ end
+
+ def new_born_cells
+ all_neighbours = @list.inject([]) { |cells, cell| cells | neighbours(cell) }
+ all_neighbours.select { |cell| alive_neighbours(cell) == 3}
+ end
+
+ def next_generation
+ Board.new *(staying_alive_cells | new_born_cells)
+ end
+ end
+end
  • Какво прави методът calc? Намери му по-добро име :)
  • res и tmp са неща, от които намирисва — ако ти се наложи да ги пишеш, по-добре помисли дали има начин да ги избегнеш, а ако не — поне ги преименувай по-описателно
  • За да циклиш по Enumerable неща, ползвай each, а не mapmap има друго предназначение :)
  • initialize ти е буквално еквивалентен на @list = cells.dup, а мисля, че може да изпуснеш и dup-а, тъй като никъде не променяш @list :)
  • count ти идва наготово от Enumerable
  • В neighbours имам малко възражения, че си се скъсал да пишеш cell[0/1] — по-добре ги присвои тези неща на нещо: x, y = cell :)

Иначе, като цяло, решението ти изглежда прилично, поздравления!