Created
May 17, 2012 17:05
-
-
Save sathish316/2720235 to your computer and use it in GitHub Desktop.
Game of life bit twiddling
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
=begin | |
........ 0x00 | |
........ 0x00 | |
..XX.... 0x30 | |
..XX.... 0x30 | |
....XX.. 0xC0 | |
....XX.. 0xC0 | |
........ 0x00 | |
........ 0x00 | |
=end | |
world = [0x00, 0x00, 0x30, 0x30, 0x0C, 0x0C, 0x00, 0x00] | |
def next_generation(world) | |
new_world = [] | |
8.times do |i| | |
new_world[i] ||= 0x00 | |
8.times do |j| | |
count = neighbor_count(world, i, j) | |
if (alive?(world, i, j) && count == 2) || (count == 3) | |
new_world[i] |= (0x80 >> j) | |
end | |
end | |
end | |
new_world | |
end | |
def neighbor_count(world, i, j) | |
count_before = hamming((world[i-1] || 0) & ((0xE0 >> (j-1)) & 0xFF)) | |
count_current = hamming((world[i] || 0) & ((0xA0 >> (j-1)) & 0xFF)) | |
count_after = hamming((world[i+1] || 0) & ((0xE0 >> (j-1)) & 0xFF)) | |
count_before + count_current + count_after | |
end | |
def alive?(world, i, j) | |
(world[i] & (0x80 >> j)) != 0 | |
end | |
def hamming(byte) | |
dist = 0 | |
val = byte ^ 0 | |
while not val.zero? | |
dist += 1 | |
val &= val - 1 | |
end | |
dist | |
end | |
def display(world) | |
world.each {|row| puts sprintf("%08b", row)} | |
end | |
while(true) | |
system 'clear' | |
display(world) | |
world = next_generation(world) | |
sleep(3) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment