forked from sagivo/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
game_of_life.rb
74 lines (65 loc) · 1.82 KB
/
game_of_life.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# Alogirthm for Game of Life
# Check more details here - http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
class GameOfLife
attr_accessor :matrix, :rows, :columns
def initialize rows, columns
@rows, @columns = rows, columns
@matrix = []
rows.times do |row|
@matrix[row] ||= []
columns.times do |column|
@matrix[row][column] = false
end
end
end
def next_tick
new_matrix = []
rows.times do |row|
new_matrix[row] ||= []
columns.times do |column|
alive_neighbours_count = neighbours(row, column).count(true)
if !self.matrix[row][column] && alive_neighbours_count == 3
new_matrix[row][column] = true
elsif self.matrix[row][column] && alive_neighbours_count != 2 && alive_neighbours_count != 3
new_matrix[row][column] = false
else
new_matrix[row][column] = self.matrix[row][column]
end
end
end
self.matrix = new_matrix
end
def print_cells
rows.times do |row|
columns.times do |column|
matrix[row][column] ? print("O") : print("-")
end
print "\n"
end
print "\n"
end
def neighbours row, column
neighbours = []
rows_limit = matrix.count - 1
columns_limit = matrix[0].count - 1
([0, row-1].max..[rows_limit, row+1].min).to_a.each do |row_index|
([0, column-1].max..[columns_limit, column+1].min).to_a.each do |column_index|
neighbours << matrix[row_index][column_index] unless row_index == row && column_index == column
end
end
neighbours
end
end
game = GameOfLife.new(100, 100)
# set alive cells
game.matrix[0][0] = true
game.matrix[0][1] = true
game.matrix[1][0] = true
game.matrix[1][3] = true
game.matrix[2][1] = true
game.matrix[2][2] = true
game.print_cells
5.times do
game.next_tick
game.print_cells
end