Last active
November 7, 2023 14:30
-
-
Save satoryu/398c5aadae0764a8418dd003156189c4 to your computer and use it in GitHub Desktop.
Improve speed by using Set
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
N = 30 | |
BOARDS = (N * N).times.map { |n| [n / N, n % N] } | |
NEIGHBORS = BOARDS.map { |(i, j)| [ [i, j], ((-1..1).to_a.product((-1..1).to_a).map { |(x, y)| [(i + x) % N, (j + y) % N] } - [[i, j]]).to_set ] }.to_h | |
def print_cells(cells) | |
BOARDS | |
.each_slice(N) | |
.map { |row| row.map { |cell| cells.include?(cell) ? '0' : '.' }.join } | |
.join("\n") | |
.tap { |s| puts s } | |
end | |
def update(cells) | |
NEIGHBORS.map { |(cell, neighbors)| [cell, (neighbors & cells).size] } | |
.select { |cell, count| count == 3 || (count == 2 && cells.include?(cell)) } | |
.map(&:first) | |
.to_set | |
end | |
GENERATIONS = 500 | |
initial_cells = BOARDS.sample(N * N / 2).to_set | |
GENERATIONS.times.reduce(initial_cells) do |cells, g| | |
puts "Generation #{g + 1}" | |
print_cells(cells) | |
update(cells) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment