This commit is contained in:
Stefan Schwarz 2020-05-10 20:34:13 +02:00
parent e8894ad31d
commit b7025c1dc2

View file

@ -61,20 +61,15 @@ impl XY {
struct MonitoringStation { struct MonitoringStation {
map: HashMap<XY, Position>, map: HashMap<XY, Position>,
size_x: usize,
size_y: usize,
} }
impl MonitoringStation { impl MonitoringStation {
fn find(&self) -> (usize, XY) { fn find(&self) -> (usize, XY) {
let mut best = (0, XY::from((0, 0))); let best = (0, XY::from((0, 0)));
for x in 0..self.size_x { self.map
for y in 0..self.size_y { .iter()
let root = XY::from((x, y)); .filter(|(_, pos)| **pos == Position::Astroid)
// we only can build on astroids .map(|(root, _)| {
if *self.map.get(&root).unwrap() == Position::Empty {
continue;
}
let insight = self let insight = self
.map .map
.iter() .iter()
@ -83,7 +78,7 @@ impl MonitoringStation {
if *pos == Position::Empty { if *pos == Position::Empty {
return None; return None;
} }
let rel = xy - &root; let rel = xy - root;
Some(rel.direction()) Some(rel.direction())
}) })
// and keep only one in each direction // and keep only one in each direction
@ -93,12 +88,14 @@ impl MonitoringStation {
}) })
.len() .len()
- 1; - 1;
if insight > best.0 { (insight, root)
best = (insight, root) })
.fold(best, |acc, astroid| {
if astroid.0 > acc.0 {
return (astroid.0, astroid.1.clone());
} }
} acc
} })
best
} }
} }
@ -108,12 +105,10 @@ where
{ {
fn from(reader: T) -> Self { fn from(reader: T) -> Self {
let map: HashMap<XY, Position> = HashMap::new(); let map: HashMap<XY, Position> = HashMap::new();
let mut size_y = 0;
let map = reader let map = reader
.split(b'\n') .split(b'\n')
.enumerate() .enumerate()
.flat_map(|(y, line)| { .flat_map(|(y, line)| {
size_y += 1;
line.unwrap() line.unwrap()
.iter() .iter()
.enumerate() .enumerate()
@ -128,12 +123,7 @@ where
map.insert(xy.clone(), p.clone()); map.insert(xy.clone(), p.clone());
map map
}); });
let size_x = map.iter().count() / size_y; MonitoringStation { map }
MonitoringStation {
map,
size_x,
size_y,
}
} }
} }