Skip to content

Instantly share code, notes, and snippets.

@mizukmb
Created May 5, 2020 14:55
Show Gist options
  • Save mizukmb/fc5ad7b5bf4958521bc3279f29ba6d70 to your computer and use it in GitHub Desktop.
Save mizukmb/fc5ad7b5bf4958521bc3279f29ba6d70 to your computer and use it in GitHub Desktop.
// lifegame
// 生→1
// 死→0
fn is_birth(target_row: i32, target_col: i32, field: &Field) -> bool {
if field[target_row as usize][target_col as usize] == 1 {
return false;
}
let mut count = 0;
for i in 0..3 {
for j in 0..3 {
if i as i32 - 1 == 0 && j as i32 - 1 == 0 {
continue;
}
if target_row + i as i32 - 1 < 0 || target_row + i as i32 - 1 >= field.len() as i32 {
continue;
}
if target_col + j as i32 - 1 < 0 || target_col + j as i32 - 1 >= field.len() as i32 {
continue;
}
if field[(target_row + i as i32 - 1) as usize][(target_col + j as i32 - 1) as usize]
== 1
{
count += 1;
}
}
}
if count == 3 {
true
} else {
false
}
}
fn is_survive(target_row: i32, target_col: i32, field: &Field) -> bool {
if field[target_row as usize][target_col as usize] == 0 {
return false;
}
let mut count = 0;
for i in 0..3 {
for j in 0..3 {
if i as i32 - 1 == 0 && j as i32 - 1 == 0 {
continue;
}
if target_row + i as i32 - 1 < 0 || target_row + i as i32 - 1 >= field.len() as i32 {
continue;
}
if target_col + j as i32 - 1 < 0 || target_col + j as i32 - 1 >= field.len() as i32 {
continue;
}
if field[(target_row + i as i32 - 1) as usize][(target_col + j as i32 - 1) as usize]
== 1
{
count += 1;
}
}
}
if count == 2 || count == 3 {
true
} else {
false
}
}
fn process(field: Field, cycle: usize) {
let mut result = field.clone();
for c in 0..cycle {
for row in 0..result.len() {
for col in 0..result[row].len() {
if is_birth(row as i32, col as i32, &result) {
result[row][col] = 1;
continue;
}
if is_survive(row as i32, col as i32, &result) {
result[row][col] = 1;
} else {
result[row][col] = 0;
}
}
}
println!("Cycle: {}", c + 1);
display(&result);
}
}
fn display(field: &Field) {
for row in field {
for cell in row {
print!("{}", cell);
}
println!("");
}
println!("");
}
type Field = Vec<Vec<u8>>;
fn main() {
let mut field = Field::new();
field.push(vec![1, 1, 0, 0]);
field.push(vec![1, 0, 0, 0]);
field.push(vec![0, 0, 0, 0]);
field.push(vec![0, 1, 1, 0]);
display(&field);
process(field, 2);
}
@mizukmb
Copy link
Author

mizukmb commented May 5, 2020

mizukmb@srms:~/src/rust/lifegame$ cargo run
   Compiling lifegame v0.1.0 (/home/mizukmb/src/rust/lifegame)
    Finished dev [unoptimized + debuginfo] target(s) in 0.48s
     Running `target/debug/lifegame`
1100
1000
0000
0110

Cycle: 1
1100
1100
1010
0110

Cycle: 2
1100
0000
0110
0110

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