-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday14.rs
More file actions
211 lines (179 loc) · 5.16 KB
/
day14.rs
File metadata and controls
211 lines (179 loc) · 5.16 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
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use regex::Regex;
use std::collections::HashMap;
// const N_ROWS: usize = 7;
// const N_COLS: usize = 11;
const N_ROWS: usize = 103;
const N_COLS: usize = 101;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Quadrant {
UpperLeft,
LowerLeft,
UpperRight,
LowerRight,
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
struct Point {
row: isize,
col: isize,
}
impl Point {
pub fn add(&self, other: &Point) -> Point {
Point {
row: self.row + other.row,
col: self.col + other.col,
}
}
pub fn scale(&self, factor: isize) -> Point {
Point {
row: self.row * factor,
col: self.col * factor,
}
}
pub fn quadrant(&self, n_rows: usize, n_cols: usize) -> Option<Quadrant> {
let mid_rows = (n_rows / 2) as isize;
let mid_cols = (n_cols / 2) as isize;
if self.row == mid_rows || self.col == mid_cols {
return None;
}
if self.row < mid_rows {
if self.col < mid_cols {
return Some(Quadrant::UpperLeft);
}
return Some(Quadrant::UpperRight);
}
if self.col < mid_cols {
return Some(Quadrant::LowerLeft);
}
Some(Quadrant::LowerRight)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Robot {
start: Point,
velocity: Point,
}
impl Robot {
pub fn step(&self, n_steps: usize, n_rows: usize, n_cols: usize) -> Point {
let unbound_end = self.start.add(&self.velocity.scale(n_steps as isize));
Point {
row: unbound_end.row.rem_euclid(n_rows as isize),
col: unbound_end.col.rem_euclid(n_cols as isize),
}
}
}
fn parse_input(input: &str) -> Vec<Robot> {
let re =
Regex::new(r"p=(?<poscol>\d+),(?<posrow>\d+) v=(?<velcol>-?\d+),(?<velrow>-?\d+)").unwrap();
let mut robots = Vec::new();
for line in input.lines() {
if line.is_empty() {
continue;
}
let capture = re.captures(line).unwrap();
let start = Point {
row: capture
.name("posrow")
.unwrap()
.as_str()
.parse::<isize>()
.unwrap(),
col: capture
.name("poscol")
.unwrap()
.as_str()
.parse::<isize>()
.unwrap(),
};
let velocity = Point {
row: capture
.name("velrow")
.unwrap()
.as_str()
.parse::<isize>()
.unwrap(),
col: capture
.name("velcol")
.unwrap()
.as_str()
.parse::<isize>()
.unwrap(),
};
let robot = Robot { start, velocity };
robots.push(robot);
}
robots
}
fn score(robots: &Vec<Robot>, n_rows: usize, n_cols: usize, n_steps: usize) -> usize {
let counts = robots.iter().fold(HashMap::new(), |mut counts, robot| {
let quadrant = robot.step(n_steps, n_rows, n_cols).quadrant(n_rows, n_cols);
match quadrant {
None => counts,
Some(quadrant) => {
*counts.entry(quadrant).or_insert(0_usize) += 1;
counts
}
}
});
if counts.len() != 4 {
return 0;
}
counts.values().fold(1_usize, |prod, &count| prod * count)
}
fn render(robots: &Vec<Robot>, n_rows: usize, n_cols: usize, n_steps: usize) -> Vec<Vec<char>> {
let mut grid = vec![vec!['.'; n_cols]; n_rows];
for robot in robots {
let pos = robot.step(n_steps, n_rows, n_cols);
grid[pos.row as usize][pos.col as usize] = '#';
}
grid
}
fn print_grid(grid: &Vec<Vec<char>>) {
for row in grid {
println!("{}", row.iter().collect::<String>());
}
}
pub fn task01(input: &str) -> String {
let robots = parse_input(input);
let n_steps = 100_usize;
score(&robots, N_ROWS, N_COLS, n_steps).to_string()
}
pub fn task02(input: &str) -> String {
let robots = parse_input(input);
let max_period = N_ROWS * N_COLS;
let max_render = 10;
let mut scores = (1..max_period)
.map(|n_steps| (n_steps, score(&robots, N_ROWS, N_COLS, n_steps)))
.collect::<Vec<(usize, usize)>>();
scores.sort_by(|a, b| a.1.cmp(&b.1));
for i in 0..max_render {
let (n_steps, score) = scores[i];
println!("n_steps: {}, score: {}", n_steps, score);
let grid = render(&robots, N_ROWS, N_COLS, n_steps);
print_grid(&grid);
}
"Everything printed".to_string()
}
#[cfg(test)]
mod tests {
use super::super::fs_utils::{read_example, read_input};
use super::*;
#[test]
fn test_task01() {
let input = read_example(14, 1);
let robots = parse_input(&input);
let n_steps = 100_usize;
assert_eq!(score(&robots, 7, 11, n_steps), 12);
}
#[test]
fn run_task01() {
let input = read_input(14);
assert_eq!(task01(&input), "230900224");
}
#[test]
fn test_task02() {}
#[test]
fn run_task02() {
// semi-manual solution
assert_eq!("6532", "6532");
}
}