Created
January 9, 2021 10:19
-
-
Save hyuki/e80040c62db4afd227e1a89ab9b421d7 to your computer and use it in GitHub Desktop.
turing-pattern.rb
This file contains hidden or 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
| #!/usr/bin/env ruby | |
| # cf. https://researchmap.jp/blogs/blog_entries/view/76000/82ceec6feab77462a8f9598c65815d76 | |
| NX = 32 | |
| NY = 32 | |
| NT = 20 | |
| W1 = 1 | |
| W2 = 1 | |
| @world = nil | |
| def display | |
| puts "----" | |
| NY.times do |y| | |
| NX.times do |x| | |
| if on(x, y) | |
| print "●" | |
| else | |
| print "○" | |
| end | |
| end | |
| puts | |
| end | |
| end | |
| def on(x, y) | |
| if x < 0 or y < 0 or NX <= x or NY <= y | |
| false | |
| else | |
| @world[y][x] | |
| end | |
| end | |
| def count_adjacents(x, y) | |
| count = 0 | |
| count += 1 if on(x - 1, y) | |
| count += 1 if on(x, y - 1) | |
| count += 1 if on(x + 1, y) | |
| count += 1 if on(x, y + 1) | |
| count | |
| end | |
| def count_neibors(x, y) | |
| count = 0 | |
| count += 1 if on(x - 2, y) | |
| count += 1 if on(x, y - 2) | |
| count += 1 if on(x + 2, y) | |
| count += 1 if on(x, y + 2) | |
| count += 1 if on(x - 1, y - 1) | |
| count += 1 if on(x + 1, y - 1) | |
| count += 1 if on(x - 1, y + 1) | |
| count += 1 if on(x + 1, y + 1) | |
| count | |
| end | |
| def next_generation | |
| next_world = [] | |
| NY.times do |y| | |
| next_world[y] = [] | |
| NX.times do |x| | |
| ev = W1 * count_adjacents(x, y) - W2 * count_neibors(x, y) | |
| if ev > 0 | |
| next_world[y][x] = true | |
| elsif ev < 0 | |
| next_world[y][x] = false | |
| else | |
| next_world[y][x] = @world[y][x] | |
| end | |
| end | |
| end | |
| @world = next_world | |
| end | |
| def init_world | |
| srand(314159) | |
| @world = [] | |
| NY.times do |y| | |
| @world[y] = [] | |
| NX.times do |x| | |
| @world[y][x] = [false, true].sample | |
| end | |
| end | |
| end | |
| init_world | |
| display | |
| NT.times do | |
| next_generation | |
| display | |
| end | |
Author
hyuki
commented
Jan 9, 2021

Author
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
