Skip to content

Instantly share code, notes, and snippets.

@swenson
Last active April 27, 2017 17:36
Show Gist options
  • Save swenson/53747b2fbb4c288006770203ae577b5f to your computer and use it in GitHub Desktop.
Save swenson/53747b2fbb4c288006770203ae577b5f to your computer and use it in GitHub Desktop.
Game of Life in Rust and Python
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)
print
pprint(nextgen(world))
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