-
Notifications
You must be signed in to change notification settings - Fork 3
/
day_21.rs
129 lines (105 loc) Β· 3.16 KB
/
day_21.rs
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
use std::collections::HashSet;
use aoc_lib::{direction::Direction, matrix::Matrix};
use common::{Answer, Solution};
use nd_vec::{vector, Vec2};
use polynomial::Polynomial;
pub struct Day21;
impl Solution for Day21 {
fn name(&self) -> &'static str {
"Step Counter"
}
fn part_a(&self, input: &str) -> Answer {
let map = parse(input);
let mut pos = HashSet::new();
pos.insert(map.find(Tile::Start).unwrap().num_cast::<i32>().unwrap());
for _ in 0..64 {
let mut new_pos = HashSet::new();
for p in pos {
for dir in Direction::ALL {
let new_p = dir.advance(p);
if !map.contains(new_p)
|| *map.get(new_p.num_cast().unwrap()).unwrap() != Tile::Wall
{
new_pos.insert(new_p);
}
}
}
pos = new_pos;
}
pos.len().into()
}
fn part_b(&self, input: &str) -> Answer {
let map = parse(input);
let start = map.find(Tile::Start).unwrap().num_cast::<i32>().unwrap();
let size = map.size.num_cast::<i32>().unwrap();
let mut pos = HashSet::new();
pos.insert(start);
let mut points = Vec::new();
for i in 0.. {
let mut new_pos = HashSet::new();
if i % size.x() == 65 {
points.push((i, pos.len()));
if points.len() >= 3 {
break;
}
}
for p in pos {
for dir in Direction::ALL {
let new_p = dir.advance(p);
let mapped = map_pos(new_p, size);
if *map.get(mapped).unwrap() != Tile::Wall {
new_pos.insert(new_p);
}
}
}
pos = new_pos;
}
let x = points.iter().map(|x| x.0 as f64).collect::<Vec<_>>();
let y = points.iter().map(|x| x.1 as f64).collect::<Vec<_>>();
let poly = Polynomial::lagrange(&x, &y).unwrap();
poly.eval(26501365.0).round().into()
}
}
fn map_pos(pos: Vec2<i32>, size: Vec2<i32>) -> Vec2<usize> {
let mut mapped = pos;
mapped = vector!((size.x() + mapped.x() % size.x()) % size.x(), mapped.y());
mapped = vector!(mapped.x(), (size.y() + mapped.y() % size.y()) % size.y());
mapped.num_cast().unwrap()
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
enum Tile {
Garden,
Wall,
Start,
}
fn parse(input: &str) -> Matrix<Tile> {
Matrix::new_chars(input, |x| match x {
'#' => Tile::Wall,
'.' => Tile::Garden,
'S' => Tile::Start,
_ => panic!("Invalid input"),
})
}
#[cfg(test)]
mod test {
use common::Solution;
use indoc::indoc;
use super::Day21;
const CASE: &str = indoc! {"
...........
.....###.#.
.###.##..#.
..#.#...#..
....#.#....
.##..S####.
.##..#...#.
.......##..
.##.#.####.
.##..##.##.
...........
"};
#[test]
fn part_a() {
assert_eq!(Day21.part_a(CASE), 4056.into());
}
}