Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use nalgebra::DMatrix;
- macro_rules! parse {
- ($x: ident, $y: ident) => {
- {
- let x = $x.parse();
- let y = $y.parse();
- if x.is_err() || y.is_err() {
- return None;
- }
- (x.unwrap_or(0), y.unwrap_or(0))
- }
- };
- }
- macro_rules! max {
- ($x: expr) => ($x);
- ($x: expr, $($z: expr),+) => (::std::cmp::max($x, max!($($z),*)));
- }
- #[derive(Debug)]
- struct Point {
- x: i32,
- y: i32,
- }
- fn aoc_05(points: &[(Point, Point)], max_x: i32, max_y: i32, only_vertical_horizontal: bool) -> u32 {
- let mut matrix = DMatrix::<i32>::zeros(max_x.abs() as usize + 1, max_y.abs() as usize + 1);
- for (p1, p2) in points {
- let dx = (p2.x - p1.x).signum();
- let dy = (p2.y - p1.y).signum();
- let (mut x, mut y) = (p1.x, p1.y);
- // Part 1...
- if only_vertical_horizontal && dx != 0 && dy != 0 {
- continue;
- }
- while (x, y) != (p2.x + dx, p2.y + dy) {
- matrix[(x as usize, y as usize)] += 1;
- x += dx;
- y += dy;
- }
- }
- matrix.fold(0, |mut iter, val| {
- if val > 1 {
- iter += 1;
- }
- iter
- })
- }
- fn parse_input(s: &str) -> Option<(Point, Point)> {
- match s.split_once(" -> ") {
- Some((p1, p2)) => {
- match p1.split_once(',') {
- Some((x1, y1)) => {
- let (x1, y1) = parse!(x1, y1);
- match p2.split_once(',') {
- Some((x2, y2)) => {
- let (x2, y2) = parse!(x2, y2);
- Some((Point { x: x1, y: y1 }, Point { x: x2, y: y2 }))
- },
- None => None
- }
- },
- None => None
- }
- },
- None => None
- }
- }
- fn main() {
- // Get the data
- let points: Vec<(Point, Point)> = include_str!("../input.txt").lines().filter_map(parse_input).collect::<Vec<(Point, Point)>>();
- // Get the max of x and y
- let (max_x, max_y) = points.iter().fold((0, 0), |max, val| (max!(val.0.x, val.1.x, max.0), max!(val.0.y, val.1.y, max.1)));
- // Current matrix settings
- println!("Max x {} max y {}", max_x, max_y);
- let result = aoc_05(&points, max_x, max_y, true);
- println!("Total #1 {}", result);
- // Same code...
- let result = aoc_05(&points, max_x, max_y, false);
- println!("Total #2 {}", result);
- }
Advertisement
Add Comment
Please, Sign In to add comment