|
| 1 | +use std::collections::{HashMap, HashSet, VecDeque}; |
| 2 | + |
| 3 | +use codingquest_clp::aoclp::positioning::pt::{matrix_to_map, Pt}; |
| 4 | +use codingquest_clp::solvers_impl::input::get_input; |
| 5 | +use itertools::Itertools; |
| 6 | + |
| 7 | +use crate::helpers::get_problem_input_data; |
| 8 | + |
| 9 | +pub fn solve() -> u64 { |
| 10 | + let bodies: CelestialBodies = sensor_data().into(); |
| 11 | + bodies.avg_mass() |
| 12 | +} |
| 13 | + |
| 14 | +fn sensor_data() -> Vec<Vec<u64>> { |
| 15 | + get_input(get_problem_input_data(15).unwrap()) |
| 16 | + .unwrap() |
| 17 | + .safe_into_many_vecs() |
| 18 | +} |
| 19 | + |
| 20 | +struct CelestialBody(HashMap<Pt, u64>); |
| 21 | + |
| 22 | +impl CelestialBody { |
| 23 | + pub fn mass(&self) -> u64 { |
| 24 | + self.0.values().sum() |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +impl From<HashMap<Pt, u64>> for CelestialBody { |
| 29 | + fn from(value: HashMap<Pt, u64>) -> Self { |
| 30 | + Self(value) |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +struct CelestialBodies(Vec<CelestialBody>); |
| 35 | + |
| 36 | +impl CelestialBodies { |
| 37 | + pub fn avg_mass(&self) -> u64 { |
| 38 | + self.0.iter().map(CelestialBody::mass).sum::<u64>() / (self.0.len() as u64) |
| 39 | + } |
| 40 | + |
| 41 | + fn body(start: Pt, data: &HashMap<Pt, u64>, cache: &mut HashSet<Pt>) -> CelestialBody { |
| 42 | + let mut pieces = HashMap::new(); |
| 43 | + let mut stack = VecDeque::new(); |
| 44 | + pieces.insert(start, data[&start]); |
| 45 | + stack.push_back(start); |
| 46 | + while let Some(pt) = stack.pop_front() { |
| 47 | + let neighbours = pt |
| 48 | + .four_neighbours() |
| 49 | + .filter(|neighbour| !cache.contains(neighbour)) |
| 50 | + .filter(|neighbour| !pieces.contains_key(neighbour)) |
| 51 | + .filter(|neighbour| data.get(neighbour).is_some_and(|&data| data != 0)) |
| 52 | + .collect_vec(); |
| 53 | + pieces.extend(neighbours.iter().map(|pt| (*pt, data[pt]))); |
| 54 | + stack.extend(neighbours.iter().copied()); |
| 55 | + cache.extend(neighbours); |
| 56 | + } |
| 57 | + |
| 58 | + pieces.into() |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +impl From<Vec<Vec<u64>>> for CelestialBodies { |
| 63 | + fn from(value: Vec<Vec<u64>>) -> Self { |
| 64 | + let data = matrix_to_map(value); |
| 65 | + let (bodies, _) = |
| 66 | + data.iter() |
| 67 | + .fold((Vec::new(), HashSet::new()), |(mut bodies, mut cache), (pt, d)| { |
| 68 | + if !cache.contains(pt) && *d != 0 { |
| 69 | + let body = Self::body(*pt, &data, &mut cache); |
| 70 | + bodies.push(body); |
| 71 | + } |
| 72 | + (bodies, cache) |
| 73 | + }); |
| 74 | + |
| 75 | + Self(bodies) |
| 76 | + } |
| 77 | +} |
0 commit comments