day03 task 1 'nicer' version
This commit is contained in:
65
src/tasks/day03.rs
Normal file
65
src/tasks/day03.rs
Normal file
@@ -0,0 +1,65 @@
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn run() {
|
||||
let content = fs::read_to_string("input/day03.txt").unwrap();
|
||||
let p1: Vec<&str> = content.lines().next().unwrap().split(",").collect();
|
||||
let p2: Vec<&str> = content.lines().skip(1).next().unwrap().split(",").collect();
|
||||
task1(&p1, &p2);
|
||||
}
|
||||
|
||||
fn task1(p1: &Vec<&str>, p2: &Vec<&str>) {
|
||||
let points1 = visited_points(&p1);
|
||||
let points2 = visited_points(&p2);
|
||||
let closest_distance = points1
|
||||
.intersection(&points2)
|
||||
.min_by_key(|(a, b)| a.abs() + b.abs())
|
||||
.unwrap();
|
||||
println!(
|
||||
"Closest point is at distance {}",
|
||||
closest_distance.0.abs() + closest_distance.1.abs()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* returns all visited points, the origin is left out, unless it is visited once again
|
||||
*/
|
||||
fn visited_points(p: &Vec<&str>) -> HashSet<(i32, i32)> {
|
||||
p.iter()
|
||||
.map(|step| {
|
||||
let direction = step.chars().next().unwrap();
|
||||
let number = step[1..].parse::<i32>().unwrap();
|
||||
(direction, number)
|
||||
})
|
||||
.scan((0, 0), |(cx, cy), (direction, number)| {
|
||||
let sx = *cx;
|
||||
let sy = *cy;
|
||||
let mut tx = *cx;
|
||||
let mut ty = *cy;
|
||||
let iter: Box<dyn Iterator<Item = (i32, i32)>> = match direction {
|
||||
'U' => {
|
||||
ty += number;
|
||||
Box::new((*cy + 1..=ty).map(move |y| (sx, y)))
|
||||
}
|
||||
'D' => {
|
||||
ty -= number;
|
||||
Box::new((ty..*cy).map(move |y| (sx, y)))
|
||||
}
|
||||
'R' => {
|
||||
tx += number;
|
||||
Box::new((*cx + 1..=tx).map(move |x| (x, sy)))
|
||||
}
|
||||
'L' => {
|
||||
tx -= number;
|
||||
Box::new((tx..*cx).map(move |x| (x, sy)))
|
||||
}
|
||||
_ => panic!("unknown direction {}", direction),
|
||||
};
|
||||
*cx = tx;
|
||||
*cy = ty;
|
||||
Some(iter)
|
||||
})
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
Reference in New Issue
Block a user