Skip to content

Commit eefa86f

Browse files
committed
2024 day 14
1 parent a5ca72f commit eefa86f

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

crates/year2024/src/day14.rs

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
use utils::point::Point2D;
2+
use utils::prelude::*;
3+
4+
/// Finding when robots arrange themselves into a picture.
5+
///
6+
/// Assumes that the picture of the Christmas tree will involve a horizontal line of at least 10
7+
/// robots, and that doesn't happen in any prior iterations.
8+
#[derive(Clone, Debug)]
9+
pub struct Day14 {
10+
robots: Vec<Robot>,
11+
}
12+
13+
#[derive(Copy, Clone, Debug)]
14+
struct Robot {
15+
position: Point2D<i32>,
16+
velocity: Point2D<i32>,
17+
}
18+
19+
const WIDTH: i32 = 101;
20+
const HEIGHT: i32 = 103;
21+
22+
impl Day14 {
23+
pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
24+
Ok(Self {
25+
robots: parser::number_range(0..=WIDTH - 1)
26+
.with_prefix("p=")
27+
.then(parser::number_range(0..=HEIGHT - 1).with_prefix(","))
28+
.then(parser::i32().with_prefix(" v="))
29+
.then(parser::i32().with_prefix(","))
30+
.map(|(px, py, vx, vy)| Robot {
31+
position: Point2D::new(px, py),
32+
velocity: Point2D::new(vx, vy),
33+
})
34+
.parse_lines(input)?,
35+
})
36+
}
37+
38+
#[must_use]
39+
pub fn part1(&self) -> u64 {
40+
let mut counts = [0; 4];
41+
for &(mut r) in self.robots.iter() {
42+
r.position += r.velocity * 100;
43+
r.position.x = r.position.x.rem_euclid(WIDTH);
44+
r.position.y = r.position.y.rem_euclid(HEIGHT);
45+
46+
if r.position.x == WIDTH / 2 || r.position.y == HEIGHT / 2 {
47+
continue;
48+
}
49+
50+
let mut quadrant = 0;
51+
if r.position.x > WIDTH / 2 {
52+
quadrant += 2;
53+
}
54+
if r.position.y > HEIGHT / 2 {
55+
quadrant += 1;
56+
}
57+
counts[quadrant] += 1;
58+
}
59+
counts.iter().product()
60+
}
61+
62+
#[must_use]
63+
pub fn part2(&self) -> u32 {
64+
let mut robots = self.robots.clone();
65+
for i in 1..=u32::MAX {
66+
let mut grid = [false; (WIDTH + 1) as usize * HEIGHT as usize];
67+
for r in robots.iter_mut() {
68+
r.position += r.velocity;
69+
r.position.x = r.position.x.rem_euclid(WIDTH);
70+
r.position.y = r.position.y.rem_euclid(HEIGHT);
71+
grid[r.position.y as usize * (WIDTH + 1) as usize + r.position.x as usize] = true;
72+
}
73+
74+
let mut count = 0;
75+
for b in grid {
76+
if b {
77+
count += 1;
78+
if count >= 10 {
79+
return i;
80+
}
81+
} else {
82+
count = 0;
83+
}
84+
}
85+
}
86+
unreachable!("no solution found")
87+
}
88+
}
89+
90+
examples!(Day14 -> (u32, u32) []);

crates/year2024/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,5 @@ utils::year!(2024 => year2024, ${
1515
11 => day11::Day11,
1616
12 => day12::Day12,
1717
13 => day13::Day13,
18+
14 => day14::Day14,
1819
});

0 commit comments

Comments
 (0)