Day 8 done

This commit is contained in:
Daniel Flanagan 2024-12-08 07:18:20 -06:00
parent f954cdad24
commit c595088352

115
2024/rust/src/day8.rs Normal file
View file

@ -0,0 +1,115 @@
mod prelude;
pub use crate::prelude::*;
fn main() {
let input = day_input(8);
show_answers(part1(&input), part2(&input));
}
fn part1(input: &str) -> usize {
let mut map: HashMap<u8, HashSet<(i64, i64)>> = HashMap::new();
let mut antinodes: HashSet<(i64, i64)> = HashSet::new();
let (width, height) = (
input.lines().count() as i64,
input.lines().next().unwrap().len() as i64,
);
for (y, line) in input.lines().enumerate() {
for (x, c) in line.bytes().enumerate() {
if c == b'.' {
continue;
}
map.entry(c)
.or_insert_with(|| HashSet::new())
.insert((x as i64, y as i64));
}
}
for nodes in map.values() {
println!("{nodes:?}");
for (i, (x1, y1)) in nodes.iter().enumerate() {
for (j, (x2, y2)) in nodes.iter().enumerate() {
if i == j {
continue;
}
let (dx, dy) = (x1 - x2, y1 - y2);
let (a1x, a1y) = (x1 + dx, y1 + dy);
let (a2x, a2y) = (x2 - dx, y2 - dy);
if a1x >= 0 && a1x < width && a1y >= 0 && a1y < height {
antinodes.insert((a1x, a1y));
}
if a2x >= 0 && a2x < width && a2y >= 0 && a2y < height {
antinodes.insert((a2x, a2y));
}
}
}
}
antinodes.len()
}
fn part2(input: &str) -> usize {
let mut map: HashMap<u8, HashSet<(i64, i64)>> = HashMap::new();
let mut antinodes: HashSet<(i64, i64)> = HashSet::new();
let (width, height) = (
input.trim().lines().count() as i64,
input.lines().next().unwrap().trim().len() as i64,
);
for (y, line) in input.lines().enumerate() {
for (x, c) in line.bytes().enumerate() {
if c == b'.' {
continue;
}
map.entry(c)
.or_insert_with(|| HashSet::new())
.insert((x as i64, y as i64));
}
}
for nodes in map.values() {
for (i, (x1, y1)) in nodes.iter().enumerate() {
for (j, (x2, y2)) in nodes.iter().enumerate() {
antinodes.insert((*x1, *y1));
antinodes.insert((*x2, *y2));
if i == j {
continue;
}
let (dx, dy) = (x1 - x2, y1 - y2);
let (mut a1x, mut a1y) = (x1 + dx, y1 + dy);
while a1x >= 0 && a1x < width && a1y >= 0 && a1y < height {
antinodes.insert((a1x, a1y));
println!("{a1x} {a1y} {}", antinodes.len());
a1x += dx;
a1y += dy;
}
let (mut a2x, mut a2y) = (x2 - dx, y2 - dy);
while a2x >= 0 && a2x < width && a2y >= 0 && a2y < height {
antinodes.insert((a2x, a2y));
println!("{a2x} {a2y} {}", antinodes.len());
a2x -= dx;
a2y -= dy;
}
}
}
}
antinodes.len()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
let input = "............
........0...
.....0......
.......0....
....0.......
......A.....
............
............
........A...
.........A..
............
............";
assert_eq!(part1(input), 14);
assert_eq!(part2(input), 34);
}
}