my solutions to advent of code
aoc
advent-of-code
1use std::mem::swap;
2
3#[inline]
4fn get_at(world: &Vec<bool>, size: usize, x: isize, y: isize) -> u8 {
5 let isize = size as isize;
6 if x == isize || x == -1 || y == isize || y == -1 {
7 return 0;
8 };
9 let (x, y) = (x as usize, y as usize);
10 if *world.get(y * size + x).expect("invalid position") {
11 1
12 } else {
13 0
14 }
15}
16
17#[inline]
18fn get_at_bool(world: &Vec<bool>, size: usize, x: usize, y: usize) -> bool {
19 *world.get(y * size + x).expect("invalid position")
20}
21
22fn generations(times: u32, mut world: Vec<bool>, size: usize, stuck: bool) -> Vec<bool> {
23 let mut new_world = vec![false; size * size];
24 let sizem = size - 1;
25 if stuck {
26 world[0] = true;
27 world[sizem] = true;
28 world[(size * size) - 1] = true;
29 world[size * sizem] = true;
30 }
31
32 for _ in 0..times {
33 for y in 0..size {
34 for x in 0..size {
35 let xo = x as isize;
36 let yo = y as isize;
37 let xm = xo - 1;
38 let ym = yo - 1;
39 let xp = xo + 1;
40 let yp = yo + 1;
41
42 let was = get_at_bool(&world, size, x, y);
43 let neighbours = get_at(&world, size, xm, ym)
44 + get_at(&world, size, xo, ym)
45 + get_at(&world, size, xp, ym)
46 + get_at(&world, size, xm, yo)
47 + get_at(&world, size, xp, yo)
48 + get_at(&world, size, xm, yp)
49 + get_at(&world, size, xo, yp)
50 + get_at(&world, size, xp, yp);
51 new_world[y * size + x] = neighbours == 3 || (neighbours == 2 && was);
52 }
53 }
54
55 swap(&mut world, &mut new_world);
56
57 // i hate the duplication here :(
58 if stuck {
59 world[0] = true;
60 world[sizem] = true;
61 world[(size * size) - 1] = true;
62 world[size * sizem] = true;
63 }
64 }
65 world
66}
67
68fn main() {
69 let input = include_str!("../../input.txt").trim();
70 let size = input.split_once("\n").expect("invalid input").0.len();
71 let input: Vec<bool> = input.replace("\n", "").chars().map(|v| v == '#').collect();
72
73 let part_1 = generations(100, input.clone(), size, false)
74 .iter()
75 .filter(|v| **v)
76 .count();
77 println!("Part 1: {}", part_1);
78
79 let part_2 = generations(100, input.clone(), size, true)
80 .iter()
81 .filter(|v| **v)
82 .count();
83 println!("Part 2: {}", part_2);
84}