Skip to content

Commit 6cc0307

Browse files
2015, day 18
1 parent 59d32af commit 6cc0307

File tree

3 files changed

+90
-0
lines changed

3 files changed

+90
-0
lines changed

src/main.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ fn main() {
4848
(2015, 15) => year_2015::day15::run(inputs::read(year, day)),
4949
(2015, 16) => year_2015::day16::run(inputs::read(year, day)),
5050
(2015, 17) => year_2015::day17::run(inputs::read(year, day)),
51+
(2015, 18) => year_2015::day18::run(inputs::read(year, day)),
5152
(2015, _) => println!("work in progress..."),
5253

5354
// 2016

src/year_2015/day18.rs

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
pub fn run(input: Vec<String>) {
2+
let part1 = solve(&input, 100, false);
3+
println!("part 1: {}", part1);
4+
assert_eq!(part1, 1061);
5+
6+
let part2 = solve(&input, 100, true);
7+
println!("part 2: {}", part2);
8+
assert_eq!(part2, 1006);
9+
}
10+
11+
fn solve(input: &Vec<String>, iterations: u64, sticky: bool) -> u64 {
12+
let mut grid = [[false; 100]; 100];
13+
14+
// process each line of input
15+
for (y, line) in input.iter().enumerate() {
16+
for (x, c) in line.chars().enumerate() {
17+
if c == '#' {
18+
grid[y][x] = true;
19+
}
20+
}
21+
}
22+
23+
// run Conway's game of life iterations number of times
24+
for _ in 0..iterations {
25+
// create a copy of the existing grid
26+
let mut grid2 = [[false; 100]; 100];
27+
for y in 0..100 {
28+
for x in 0..100 {
29+
grid2[y][x] = grid[y][x];
30+
}
31+
}
32+
33+
for y in 0..100 {
34+
for x in 0..100 {
35+
// count neighbors
36+
let mut c = 0;
37+
for dy in -1..2 {
38+
for dx in -1..2 {
39+
if (dx == 0) && (dy == 0) {
40+
continue;
41+
}
42+
if y + dy < 0 {
43+
continue;
44+
}
45+
if y + dy >= 100 {
46+
continue;
47+
}
48+
if x + dx < 0 {
49+
continue;
50+
}
51+
if x + dx >= 100 {
52+
continue;
53+
}
54+
55+
if grid2[(y + dy) as usize][(x + dx) as usize] {
56+
c += 1;
57+
}
58+
}
59+
}
60+
61+
// change state on grid but by looking up in grid2
62+
if grid2[y as usize][x as usize] {
63+
grid[y as usize][x as usize] = (c == 2) || (c == 3);
64+
} else {
65+
grid[y as usize][x as usize] = c == 3;
66+
}
67+
}
68+
}
69+
70+
if sticky {
71+
grid[0][0] = true;
72+
grid[99][0] = true;
73+
grid[0][99] = true;
74+
grid[99][99] = true;
75+
}
76+
}
77+
78+
// count how many lights are lit
79+
let mut lit = 0;
80+
for x in grid.iter() {
81+
for y in x.iter() {
82+
if *y {
83+
lit += 1;
84+
}
85+
}
86+
}
87+
return lit;
88+
}

src/year_2015/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,4 @@ pub mod day14;
1515
pub mod day15;
1616
pub mod day16;
1717
pub mod day17;
18+
pub mod day18;

0 commit comments

Comments
 (0)