Created
November 28, 2021 17:37
-
-
Save josh-gree/eb74bdb51831120ab0e8e8e112c5fc1f to your computer and use it in GitHub Desktop.
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
use array2d::Array2D | |
use rand::prelude::* | |
#[derive(Debug)] | |
struct Board { | |
array: Array2D<bool> | |
} | |
impl Board { | |
fn new(n_rows: usize, n_cols: usize) -> Self { | |
Self {array: Array2D::<bool>::fill_with(false, n_rows, n_cols)} | |
} | |
fn randomise(&mut self, prob: f32) { | |
for i in 0..self.array.num_columns() { | |
for j in 0..self.array.num_rows() { | |
let is_alive: bool = random::<f32>() > prob; | |
self.array[(i,j)] = is_alive | |
} | |
} | |
} | |
fn step(&mut self) { | |
for i in 0..self.array.num_columns() as i32 { | |
for j in 0..self.array.num_rows() as i32 { | |
let neigbours = self.get_neigbours(neigbour_idxs((i,j))); | |
let is_alive = match neigbours.iter().sum::<usize>() { | |
0 => false, | |
1 => false, | |
2 => true, | |
3 => true, | |
_ => false | |
}; | |
self.array[(i as usize,j as usize)] = is_alive | |
} | |
} | |
} | |
fn get_neigbours(&self, idxs: Vec<(i32,i32)>) -> Vec<usize> { | |
let mut out : Vec<usize> = vec![]; | |
for idx in idxs { | |
if let Some(v) = self.array.get(idx.0 as usize, idx.1 as usize) { | |
out.push(*v as usize) | |
} | |
} | |
out | |
} | |
} | |
fn neigbour_idxs(idx: (i32,i32)) -> Vec<(i32,i32)> { | |
vec![ | |
(idx.0 + 1,idx.1), | |
(idx.0 - 1,idx.1), | |
(idx.0,idx.1 + 1), | |
(idx.0,idx.1 - 1), | |
(idx.0 + 1,idx.1 + 1), | |
(idx.0 - 1,idx.1 - 1), | |
(idx.0 + 1,idx.1 - 1), | |
(idx.0 - 1,idx.1 + 1) | |
] | |
} | |
let mut b = Board::new(2,2); | |
b.randomise(0.5); | |
b.step(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment