Created
May 5, 2020 14:55
-
-
Save mizukmb/fc5ad7b5bf4958521bc3279f29ba6d70 to your computer and use it in GitHub Desktop.
ライフゲーム (参考資料: https://ja.wikipedia.org/wiki/%E3%83%A9%E3%82%A4%E3%83%95%E3%82%B2%E3%83%BC%E3%83%A0 )
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
// 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); | |
} |
Author
mizukmb
commented
May 5, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment