diff --git a/src/tasks/day19.rs b/src/tasks/day19.rs index 4a1bceb..e613acf 100644 --- a/src/tasks/day19.rs +++ b/src/tasks/day19.rs @@ -4,8 +4,8 @@ use itertools::Itertools; pub fn run() { let program = super::day05::load_ram("input/day19.txt"); - //part1(&program, 50); - part2(&program); // 8151016 too high + part1(&program, 50); + part2(&program); } fn part1(program: &RAM, max: i128) { @@ -20,7 +20,7 @@ fn part1(program: &RAM, max: i128) { .filter(|v| *v) .count(); - println!("{result}"); + println!("Part 1: {result}"); } const W: i128 = 100; @@ -35,29 +35,37 @@ fn part2(program: &RAM) { map.insert((x, y), read_coordinate(program, x, y)); }) }); - for starts in 0..=MAX_PERIMETER { - println!("checking perimeter {starts}"); - extend_horizon(program, &mut map, starts); - check_all_squares_at(&map, starts); + for perimeter in 0..=MAX_PERIMETER { + extend_horizon(program, &mut map, perimeter); + if let Some((x, y)) = check_all_squares_starting_at(&map, perimeter) { + let result = x * 10_000 + y; + println!("Part 2: starts at {x},{y} -> {}", result); + break; + } } } -fn check_all_squares_at(map: &HashMap<(i128, i128), bool>, starts: i128) { - (0..=starts).for_each(|i| { - check_fits(map, i, starts); - check_fits(map, starts, i); - }); +fn check_all_squares_starting_at(map: &HashMap<(i128, i128), bool>, perimeter: i128) -> Option<(i128, i128)> { + for i in 0..=perimeter { + if let Some(point) = check_fits(map, i, perimeter) { + return Some(point); + } + if let Some(point) = check_fits(map, perimeter, i) { + return Some(point); + } + } + None } -fn check_fits(map: &HashMap<(i128, i128), bool>, x: i128, y: i128) { +fn check_fits(map: &HashMap<(i128, i128), bool>, x: i128, y: i128) -> Option<(i128, i128)> { let ul = map[&(x, y)]; let ur = map[&(x + W - 1, y)]; let ll = map[&(x, y + W - 1)]; let lr = map[&(x + W, y + W - 1)]; if ul && ur && ll && lr { - let result = x * 10_000 + y; - panic!("found it! starts at {x},{y} -> {}", result); + return Some((x, y)); } + None } fn extend_horizon(program: &RAM, map: &mut HashMap<(i128, i128), bool>, starts: i128) {