-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0289_game_of_life.rs
More file actions
99 lines (88 loc) · 3.17 KB
/
s0289_game_of_life.rs
File metadata and controls
99 lines (88 loc) · 3.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#![allow(unused)]
pub struct Solution {}
// https://leetcode.com/problems/median-of-two-sorted-arrays/description/
use std::cmp::{max, min};
impl Solution {
pub fn game_of_life(board: &mut Vec<Vec<i32>>) {
fn will_live(coord: (usize, usize), mat: &Vec<Vec<i32>>) -> bool {
let num_alive_nei = live_neighbors(coord, mat);
if num_alive_nei < 2 || num_alive_nei > 3 {
return false;
}
if (num_alive_nei == 2 || num_alive_nei == 3) && mat[coord.0][coord.1] == 1 {
return true;
}
if num_alive_nei == 3 && mat[coord.0][coord.1] == 0 {
return true;
}
false
}
fn live_neighbors(coord: (usize, usize), mat: &Vec<Vec<i32>>) -> i32 {
if mat.is_empty() {
return 0;
}
let mut ret = 0;
let height = mat.len();
let width = mat[0].len();
// can use for loops below to make it looks nicer...
if coord.0+1 >= 0 && coord.0+1 < height && coord.1+1 >= 0 && coord.1+1 < width {
if mat[coord.0+1][coord.1+1] & 1 == 1 {
ret += 1;
}
}
if coord.0+1 >= 0 && coord.0+1 < height && coord.1-1 >= 0 && coord.1-1 < width {
if mat[coord.0+1][coord.1-1] & 1 == 1 {
ret += 1;
}
}
if coord.0-1 >= 0 && coord.0-1 < height && coord.1+1 >= 0 && coord.1+1 < width {
if mat[coord.0-1][coord.1+1] & 1 == 1 {
ret += 1;
}
}
if coord.0-1 >= 0 && coord.0-1 < height && coord.1-1 >= 0 && coord.1-1 < width {
if mat[coord.0-1][coord.1-1] & 1 == 1 {
ret += 1;
}
}
if coord.0+1 >= 0 && coord.0+1 < height && coord.1 >= 0 && coord.1 < width {
if mat[coord.0+1][coord.1] & 1 == 1 {
ret += 1;
}
}
if coord.0-1 >= 0 && coord.0-1 < height && coord.1 >= 0 && coord.1 < width {
if mat[coord.0-1][coord.1] & 1 == 1 {
ret += 1;
}
}
if coord.0 >= 0 && coord.0 < height && coord.1+1 >= 0 && coord.1+1 < width {
if mat[coord.0][coord.1+1] & 1 == 1 {
ret += 1;
}
}
if coord.0 >= 0 && coord.0 < height && coord.1-1 >= 0 && coord.1-1 < width {
if mat[coord.0][coord.1-1] & 1 == 1 {
ret += 1;
}
}
ret
}
if board.is_empty() {
return
}
let height = board.len();
let width = board[0].len();
for i in 0..height {
for j in 0..width {
if will_live((i,j), board) {
board[i][j] |= 2;
}
}
}
for i in 0..height {
for j in 0..width {
board[i][j] >>= 1;
}
}
}
}