Last active
April 27, 2017 17:36
-
-
Save swenson/53747b2fbb4c288006770203ae577b5f to your computer and use it in GitHub Desktop.
Game of Life in Rust and Python
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
from pprint import pprint | |
import random | |
def nextgen(state): | |
new_state = [] | |
for i in range(5): | |
new_state.append([0] * 5) | |
for x in range(5): | |
for y in range(5): | |
count = 0 | |
for dx in [-1, 0, 1]: | |
for dy in [-1, 0, 1]: | |
if dx == 0 and dy == 0: | |
continue | |
count += state[(x + dx) % 5][(y + dy) % 5] | |
if count == 3 or (count == 2 and state[x][y]): | |
new_state[x][y] = 1 | |
return new_state | |
world = [] | |
for i in range(5): | |
world.append([random.randint(0, 1) for i in range(5)]) | |
pprint(world) | |
pprint(nextgen(world)) |
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
fn main() { | |
let matrix = vec![ | |
vec![0, 1, 0, 1, 0], | |
vec![0, 1, 0, 1, 0], | |
vec![0, 1, 0, 1, 0], | |
vec![0, 1, 0, 1, 0], | |
vec![0, 1, 0, 1, 0]]; | |
for x in 0..5 { | |
for y in 0..5 { | |
print!("{}", matrix[x][y]); | |
} | |
println!(""); | |
} | |
let mut new_matrix = vec![ | |
vec![0, 0, 0, 0, 0], | |
vec![0, 0, 0, 0, 0], | |
vec![0, 0, 0, 0, 0], | |
vec![0, 0, 0, 0, 0], | |
vec![0, 0, 0, 0, 0]]; | |
for x in 0..5 { | |
for y in 0..5 { | |
let mut count = 0; | |
for delta_x in 0..3 { | |
for delta_y in 0..3 { | |
let dx = delta_x - 1; | |
let dy = delta_y - 1; | |
let checkx = ((((x + dx) % 5) + 5) % 5) as usize; | |
let checky = ((((y + dy) % 5) + 5) % 5) as usize; | |
if dx == 0 && dy == 0 { | |
continue; | |
} | |
count += matrix[checkx][checky]; | |
} | |
} | |
if count == 3 || (count == 2 && matrix[x as usize][y as usize] == 1) { | |
new_matrix[x as usize][y as usize] = 1; | |
} | |
} | |
} | |
println!(""); | |
println!(""); | |
for x in 0..5 { | |
for y in 0..5 { | |
print!("{}", new_matrix[x][y]); | |
} | |
println!(""); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment