Skip to content

Instantly share code, notes, and snippets.

@qubyte
Created December 7, 2018 04:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qubyte/2d321c15cd1048aa94edb01bf1374e28 to your computer and use it in GitHub Desktop.
Save qubyte/2d321c15cd1048aa94edb01bf1374e28 to your computer and use it in GitHub Desktop.
Advent of Code day 06 task 2
use regex::Regex;
use std::io::{stdin, BufRead};
use std::cmp::{max};
#[macro_use]
extern crate lazy_static;
const MAX_TOTAL_DIST: usize = 10000;
fn abs_diff(a: &usize, b: &usize) -> usize {
if a < b {
b - a
} else {
a - b
}
}
struct Coordinate {
x: usize,
y: usize,
}
impl Coordinate {
fn from_str(coordinate_string: &str) -> Option<Coordinate> {
lazy_static! {
static ref regex: Regex = Regex::new(r"^(\d+),\s+(\d+)$").unwrap();
}
match regex.captures(&coordinate_string) {
None => None,
Some(cap) => Some(Coordinate {
x: cap[1].parse().unwrap(),
y: cap[2].parse().unwrap(),
}),
}
}
fn manhatten_distance(&self, other: &Coordinate) -> usize {
let x_dist = abs_diff(&self.x, &other.x);
let y_dist = abs_diff(&self.y, &other.y);
x_dist + y_dist
}
}
fn main() {
let coordinates: Vec<Coordinate> = stdin()
.lock()
.lines()
.filter_map(|line| Coordinate::from_str(&line.unwrap()))
.collect();
// Dodgy assumption that the region will lie within the bounds of the given coordinates.
let (x_max, y_max) = coordinates.iter().fold((0, 0), |(x_max, y_max), c| (max(x_max, c.x), max(y_max, c.y)));
let mut cells_in_region = 0;
for x in 0..=x_max {
for y in 0..=y_max {
let grid_point = Coordinate { x, y };
let total_dist: usize = coordinates.iter().map(|c| grid_point.manhatten_distance(&c)).sum();
if total_dist < MAX_TOTAL_DIST {
cells_in_region += 1;
}
}
}
println!("Cells in region {}", cells_in_region);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment