yay solved day3-2

This commit is contained in:
Stefan Schwarz 2020-04-19 12:32:18 +02:00
parent 1df50835be
commit 5eec977c10

View file

@ -1,5 +1,6 @@
use std::collections::HashSet;
use std::io::{self, BufRead};
use std::iter::FromIterator;
#[derive(Debug)]
enum Step {
@ -10,7 +11,7 @@ enum Step {
}
impl Step {
fn draw(&self, map: &mut HashSet<Point>, start: &mut Point) {
fn draw(&self, map: &mut Vec<Point>, start: &mut Point) {
let mover: (i64, i64, &usize) = match self {
Step::Up(s) => (0, 1, s),
Step::Down(s) => (0, -1, s),
@ -22,7 +23,7 @@ impl Step {
for _ in 0..*steps {
start.x += x;
start.y += y;
map.insert(start.clone());
map.push(start.clone());
}
}
}
@ -63,23 +64,51 @@ impl From<(i64, i64)> for Point {
fn main() -> io::Result<()> {
let commands = load();
let mut wires: Vec<HashSet<Point>> = vec![];
let mut wires: Vec<Vec<Point>> = vec![];
commands.iter().enumerate().for_each(|(_, wire)| {
let mut map = HashSet::new();
let mut map = Vec::new();
let mut p: Point = (0, 0).into();
wire.iter().for_each(|step| {
step.draw(&mut map, &mut p);
});
wires.push(map);
});
let closest = wires[0].intersection(&wires[1]).fold(None, |min, point| {
let dist = point.dist_to_00();
match min {
None => Some(dist),
Some(min) => Some(if dist < min { dist } else { min }),
}
});
println!("closest: {}", closest.unwrap());
let wire_sets: Vec<HashSet<&Point>> = wires
.iter()
.map(|wire| HashSet::from_iter(wire.iter()))
.collect();
let closest = wire_sets[0]
.intersection(&wire_sets[1])
.fold(None, |min, point| {
let dist = point.dist_to_00();
match min {
None => Some(dist),
Some(min) => Some(if dist < min { dist } else { min }),
}
})
.expect("no mataching points found");
let shortest = wire_sets[0]
.intersection(&wire_sets[1])
.map(|point| {
wires[0].iter().position(|p| p == *point).unwrap()
+ wires[1].iter().position(|p| p == *point).unwrap()
+ 2
})
.fold(None, |min, dist| {
Some(match min {
None => dist,
Some(d) => {
if dist < d {
dist
} else {
d
}
}
})
})
.expect("no matching points found");
println!("closest: {}", closest);
println!("shortest: {}", shortest);
Ok(())
}