|
| 1 | +use std::{cmp::Reverse, iter}; |
| 2 | + |
| 3 | +use common::{Answer, solution}; |
| 4 | +use itertools::Itertools; |
| 5 | +use nd_vec::{Vec2, vector}; |
| 6 | + |
| 7 | +solution!("Movie Theater", 9); |
| 8 | + |
| 9 | +fn part_a(input: &str) -> Answer { |
| 10 | + parse(input) |
| 11 | + .iter() |
| 12 | + .combinations(2) |
| 13 | + .map(|x| (x[0].x().abs_diff(x[1].x()) + 1) * (x[0].y().abs_diff(x[1].y()) + 1)) |
| 14 | + .max() |
| 15 | + .unwrap() |
| 16 | + .into() |
| 17 | +} |
| 18 | + |
| 19 | +fn part_b(input: &str) -> Answer { |
| 20 | + let red = parse(input); |
| 21 | + red.iter() |
| 22 | + .tuple_combinations() |
| 23 | + .map(|(a, b)| { |
| 24 | + ( |
| 25 | + (a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1), |
| 26 | + (a, b), |
| 27 | + ) |
| 28 | + }) |
| 29 | + .sorted_by_key(|(area, _)| Reverse(*area)) |
| 30 | + .find(|(_area, (a, b))| { |
| 31 | + let min = vector!(a.x().min(b.x()), a.y().min(b.y())); |
| 32 | + let max = vector!(a.x().max(b.x()), a.y().max(b.y())); |
| 33 | + |
| 34 | + for (&α, &β) in red.iter().chain(iter::once(&red[0])).tuple_windows() { |
| 35 | + let lmin = vector!(α.x().min(β.x()), α.y().min(β.y())); |
| 36 | + let lmax = vector!(α.x().max(β.x()), α.y().max(β.y())); |
| 37 | + |
| 38 | + if α.x() == β.x() { |
| 39 | + let x = β.x(); |
| 40 | + if ((lmin.y() < min.y() && lmax.y() > min.y()) |
| 41 | + || (lmin.y() < max.y() && lmax.y() > max.y()) |
| 42 | + || (lmin.y() >= min.y() && lmax.y() <= max.y())) |
| 43 | + && x > min.x() |
| 44 | + && x < max.x() |
| 45 | + { |
| 46 | + return false; |
| 47 | + } |
| 48 | + } else if α.y() == β.y() { |
| 49 | + let y = β.y(); |
| 50 | + if ((lmin.x() < min.x() && lmax.x() > min.x()) |
| 51 | + || (lmin.x() < max.x() && lmax.x() > max.x()) |
| 52 | + || (lmin.x() >= min.x() && lmax.x() <= max.x())) |
| 53 | + && y > min.y() |
| 54 | + && y < max.y() |
| 55 | + { |
| 56 | + return false; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + true |
| 62 | + }) |
| 63 | + .unwrap() |
| 64 | + .0 |
| 65 | + .into() |
| 66 | +} |
| 67 | + |
| 68 | +// not: >1565730054 |
| 69 | + |
| 70 | +fn parse(input: &str) -> Vec<Vec2<i64>> { |
| 71 | + (input.lines()) |
| 72 | + .map(|x| { |
| 73 | + let (x, y) = x.split_once(',').unwrap(); |
| 74 | + vector!(x.parse().unwrap(), y.parse().unwrap()) |
| 75 | + }) |
| 76 | + .collect::<Vec<_>>() |
| 77 | +} |
| 78 | + |
| 79 | +#[cfg(test)] |
| 80 | +mod test { |
| 81 | + use indoc::indoc; |
| 82 | + |
| 83 | + const CASE: &str = indoc! {" |
| 84 | + 7,1 |
| 85 | + 11,1 |
| 86 | + 11,7 |
| 87 | + 9,7 |
| 88 | + 9,5 |
| 89 | + 2,5 |
| 90 | + 2,3 |
| 91 | + 7,3 |
| 92 | + "}; |
| 93 | + |
| 94 | + #[test] |
| 95 | + fn part_a() { |
| 96 | + assert_eq!(super::part_a(CASE), 50.into()); |
| 97 | + } |
| 98 | + |
| 99 | + #[test] |
| 100 | + fn part_b() { |
| 101 | + assert_eq!(super::part_b(CASE), 24.into()); |
| 102 | + } |
| 103 | +} |
0 commit comments