Skip to content

Instantly share code, notes, and snippets.

@PuercoPop
Created May 23, 2020 22:10
Show Gist options
  • Save PuercoPop/259c03e671de5a2cfdbabb898908ee87 to your computer and use it in GitHub Desktop.
Save PuercoPop/259c03e671de5a2cfdbabb898908ee87 to your computer and use it in GitHub Desktop.
// https://adventofcode.com/2019/day/6
// https://doc.rust-lang.org/beta/std/collections/struct.HashMap.html
use std::fs;
use std::collections::{
HashSet, HashMap, VecDeque
};
fn main() {
let mut graph = HashMap::new();
let mut reachable = HashMap::new();
// let input = fs::read_to_string("./src/6.example").unwrap();
let input = fs::read_to_string("./src/6.input").unwrap();
for line in input.lines() {
let x = line.split(")").collect::<Vec<&str>>();
let (from, to) = (x[0], x[1]);
if let None = graph.get(&from) {
graph.insert(from, HashSet::new());
reachable.insert(from, HashSet::new());
}
let orbit = graph.get_mut(&from).unwrap();
orbit.insert(to);
let orbit = reachable.get_mut(&from).unwrap();
orbit.insert(to);
}
// println!("{:?}\n", graph);
for base_planet in graph.clone().keys() {
let mut next = VecDeque::new();
let y = graph.get_mut(base_planet).unwrap().clone();
for p in y.iter() {
next.push_front(p);
}
while !next.is_empty() {
let planet = next.pop_front().unwrap();
let planets = graph.get(planet);
if let Some(orbiting_planets) = planets {
for orbiting_planet in orbiting_planets.iter() {
next.push_back(orbiting_planet);
reachable.get_mut(base_planet).unwrap().insert(orbiting_planet);
}
}
}
}
let answer: usize = reachable.values().map(|planets| planets.len()).sum();
println!("answer: {:?}", answer);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment