day9: cheated from others for part 2, still a mess

This commit is contained in:
ktims committed 2026-12-01 01:46:52 -07:00
1 parent c35270a6a2
commit 77c3c20ad0
1 file changed
+226 -64
+226 -64
View File
@@ -3,7 +3,7 @@ use grid::{AsCoord2d, Coord2d, Grid};
use indicatif::{ParallelProgressIterator, ProgressIterator, ProgressStyle}; use indicatif::{ParallelProgressIterator, ProgressIterator, ProgressStyle};
use itertools::Itertools; use itertools::Itertools;
use rayon::prelude::*; use rayon::prelude::*;
use std::collections::HashMap; use std::collections::{HashMap, VecDeque};
use std::{ use std::{
cmp::{max, min}, cmp::{max, min},
fmt::Display, fmt::Display,
@@ -93,34 +93,45 @@ fn build_hashgrid(reds: &Vec<Coord2d>) -> HashMap<Coord2d, u8> {
grid grid
} }
// FIXME: TOTALLY BROKEN fn flood_fill(grid: &mut Grid<u8>, pos: Coord2d) {
fn flood_fill(grid: &mut Grid<u8>) { if grid.get(&pos) != Some(&b'.') {
#[derive(Debug, Eq, PartialEq)] return;
enum State {
OffLine(bool), // Off a line(true=inside)
OnLine(bool), // On a line(previous state)
} }
for y in 0..grid.height() { let mut q = VecDeque::new();
let mut state = State::OffLine(false); q.push_back(pos);
for x in 0..grid.width() { while let Some(next) = q.pop_front() {
match grid.get(&(x, y)) { let (mut lx, mut rx) = (next.x, next.x);
Some(b'.') => { while grid.get(&Coord2d {
if state == State::OffLine(true) || state == State::OnLine(false) { x: lx - 1,
grid.set(&(x, y), b'X'); y: next.y,
state = State::OffLine(true) }) == Some(&b'.')
} else { {
state = State::OffLine(false) grid.set(
&Coord2d {
x: lx - 1,
y: next.y,
},
b'X',
);
lx -= 1;
}
while grid.get(&Coord2d { x: rx, y: next.y }) == Some(&b'.') {
grid.set(&Coord2d { x: rx, y: next.y }, b'X');
rx += 1;
}
flood_scan(grid, lx, rx, next.y + 1, &mut q);
flood_scan(grid, lx, rx, next.y - 1, &mut q);
} }
} }
Some(b'#') | Some(b'X') => {
state = State::OnLine(match state { fn flood_scan(grid: &mut Grid<u8>, lx: i64, rx: i64, y: i64, q: &mut VecDeque<Coord2d>) {
State::OnLine(s) => s, let mut span_added = false;
State::OffLine(s) => s, for x in lx..rx {
}) if grid.get(&Coord2d { x, y }) != Some(&b'.') {
} span_added = false
None => panic!("overran the grid"), } else if !span_added {
Some(c) => panic!("unexpected value {c}"), q.push_back(Coord2d { x, y });
} span_added = true
} }
} }
} }
@@ -128,8 +139,10 @@ fn flood_fill(grid: &mut Grid<u8>) {
// #[aoc(day9, part2, Brute)] // #[aoc(day9, part2, Brute)]
fn part2(reds: &Vec<Coord2d>) -> u64 { fn part2(reds: &Vec<Coord2d>) -> u64 {
let mut grid = build_grid(reds); let mut grid = build_grid(reds);
flood_fill(&mut grid); // Find the first red starting at top left - 'inside' must be to its bottom right
println!("{grid}"); let start = grid.find(&b'#').unwrap();
flood_fill(&mut grid, start + &(1, 1).to_coord());
// println!("{grid}");
let pairs = reds let pairs = reds
.iter() .iter()
@@ -160,7 +173,7 @@ fn part2(reds: &Vec<Coord2d>) -> u64 {
}) })
.find_map_first(|(good, a, b)| if good { Some((a, b)) } else { None }) .find_map_first(|(good, a, b)| if good { Some((a, b)) } else { None })
.unwrap(); .unwrap();
println!("win: {a} {b}"); // println!("win: {a} {b}");
(a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1) (a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1)
} }
@@ -257,7 +270,7 @@ fn outside_points(prev: &Coord2d, cur: &Coord2d, next: &Coord2d) -> Vec<Coord2d>
match (l1_diff, l2_diff) { match (l1_diff, l2_diff) {
// CW // CW
((1, 0), (0, 1)) => vec![cur + (0, -1), cur + (1, -1), cur + (1, 0)], // x^ y^ ((1, 0), (0, 1)) => vec![cur + (0, -1), cur + (1, -1), cur + (1, 0)], // x^ y^
((0, 1), (-1, 0)) => vec![cur + (1, 0), cur + (1, 1), cur + (0, -1)], // y^ xv ((0, 1), (-1, 0)) => vec![cur + (1, 0), cur + (1, 1), cur + (0, 1)],
((-1, 0), (0, -1)) => vec![cur + (0, 1), cur + (-1, 1), cur + (-1, 0)], // xv yv ((-1, 0), (0, -1)) => vec![cur + (0, 1), cur + (-1, 1), cur + (-1, 0)], // xv yv
((0, -1), (1, 0)) => vec![cur + (-1, 0), cur + (-1, -1), cur + (0, -1)], // yv x^ ((0, -1), (1, 0)) => vec![cur + (-1, 0), cur + (-1, -1), cur + (0, -1)], // yv x^
// CCW // CCW
@@ -276,13 +289,26 @@ fn outside_points(prev: &Coord2d, cur: &Coord2d, next: &Coord2d) -> Vec<Coord2d>
#[aoc(day9, part2, Lines)] #[aoc(day9, part2, Lines)]
fn part2_lines(reds: &Vec<Coord2d>) -> u64 { fn part2_lines(reds: &Vec<Coord2d>) -> u64 {
// let mut grid = build_hashgrid(reds); // let mut grid = build_hashgrid(reds);
let mut grid = build_grid(reds); // let mut grid = build_grid(reds);
println!("{grid}"); // // println!("{grid}");
let outside_points: HashMap<&Coord2d, Vec<Coord2d>> = reds // let area: i64 = reds
.iter() // .iter()
.circular_tuple_windows() // .circular_tuple_windows()
.map(|(a, b, c)| (b, outside_points(a, b, c))) // .map(|(a, b)| (a.x * b.y) - (b.x * a.y))
.collect(); // .sum();
// let outside_points: HashMap<&Coord2d, Vec<Coord2d>> = if area < 0 {
// reds.iter()
// .rev()
// .circular_tuple_windows()
// .map(|(a, b, c)| (b, outside_points(a, b, c)))
// .collect()
// } else {
// reds.iter()
// .circular_tuple_windows()
// .map(|(a, b, c)| (b, outside_points(a, b, c)))
// .collect()
// };
// for corner in reds { // for corner in reds {
// for p in &outside_points[corner] { // for p in &outside_points[corner] {
// if *grid.get(p).unwrap() == b'.' { // if *grid.get(p).unwrap() == b'.' {
@@ -306,37 +332,39 @@ fn part2_lines(reds: &Vec<Coord2d>) -> u64 {
.unwrap(), .unwrap(),
) )
{ {
println!( let tl = rect.top_left();
"[{},{}] = {}", let br = rect.bottom_right();
rect.top_left(),
rect.bottom_right(), let invalid = reds.iter().circular_tuple_windows().any(|(a, b)| {
rect.area() // 1. A polygon vertex lies strictly inside the rectangle
); let node_inside = tl.x < a.x && a.x < br.x && tl.y < a.y && a.y < br.y;
// then for each corner, check if any of its outside edges are inside and not part of another line
if reds // 2. A polygon edge slices all the way across the rectangle
.iter() let crosses_bounds = if a.x == b.x {
.filter(|corner| rect.in_bounds(corner)) let (ey_min, ey_max) = (a.y.min(b.y), a.y.max(b.y));
.inspect(|c| println!(" corner: {c}")) (tl.x < a.x && a.x < br.x) && (ey_min <= tl.y && ey_max >= br.y)
.any(|corner| { } else {
outside_points[corner] let (ex_min, ex_max) = (a.x.min(b.x), a.x.max(b.x));
.iter() (tl.y < a.y && a.y < br.y) && (ex_min <= tl.x && ex_max >= br.x)
.inspect(|p| println!(" {} = {}", p, *grid.get(p).unwrap() as char)) };
.any(|p| rect.in_bounds(p) && *grid.get(p).unwrap() == b'.')
}) node_inside || crosses_bounds
{ });
if invalid {
continue; continue;
} }
println!( // println!(
"win! {},{} = {}", // "win! {},{} = {}",
rect.top_left(), // rect.top_left(),
rect.bottom_right(), // rect.bottom_right(),
rect.area() // rect.area()
); // );
grid.set(&rect.top_left(), b'*'); // grid.set(&rect.top_left(), b'*');
grid.set(&rect.bottom_right(), b'*'); // grid.set(&rect.bottom_right(), b'*');
println!("{grid}"); // println!("{grid}");
return rect.area(); return rect.area();
} }
panic!() panic!()
@@ -452,6 +480,140 @@ mod tests {
1,8", 1,8",
56 56
)] )]
#[case(
"1,1
4,1
4,5
7,5
7,1
10,1
10,8
1,8",
32
)]
#[case(
"1,1
5,1
5,6
7,6
7,1
11,1
11,9
1,9",
45
)]
#[case(
"1,1
5,1
5,7
6,7
6,1
10,1
10,9
1,9",
90
)]
#[case(
"1,1
12,1
12,8
10,8
10,3
8,3
8,8
6,8
6,3
4,3
4,8
1,8",
32
)]
#[case(
"1,1
1,8
10,8
10,1
7,1
7,5
4,5
4,1",
32
)]
#[case(
"4,1
7,1
7,4
10,4
10,7
7,7
7,10
4,10
4,7
1,7
1,4
4,4",
40
)]
#[case(
"1,1
12,1
12,10
1,10
1,8
10,8
10,3
1,3",
36
)]
#[case(
"1,1
10,1
10,6
4,6
4,8
10,8
10,12
1,12
1,7
7,7
7,4
1,4",
50
)]
#[case(
"1,1
10,1
10,10
3,10
3,4
7,4
7,7
5,7
5,6
6,6
6,5
4,5
4,9
9,9
9,2
1,2",
20
)]
#[case(
"1,1
5,1
5,3
7,3
7,4
2,4
2,7
7,7
7,8
3,8
3,11
1,11",
16
)]
fn part2_lines_example(#[case] input: &str, #[case] answer: u64) { fn part2_lines_example(#[case] input: &str, #[case] answer: u64) {
assert_eq!(part2_lines(&parse(input)), answer); assert_eq!(part2_lines(&parse(input)), answer);