Skip to content

Instantly share code, notes, and snippets.

@tinaun
Created December 7, 2017 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tinaun/e2d40eb586d9c8becc8915127d324224 to your computer and use it in GitHub Desktop.
Save tinaun/e2d40eb586d9c8becc8915127d324224 to your computer and use it in GitHub Desktop.
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq)]
struct Node {
weight: u32,
children: Vec<String>,
}
impl Node {
fn weight(&self, map: &HashMap<String, Node>) -> u32 {
self.get_weights(map).into_iter().fold(self.weight, |acc, (_, weight)| {acc + weight})
}
fn get_weights(&self, map: &HashMap<String, Node>) -> Vec<(String, u32)> {
self.children.iter().map(|n| {
let child = map.get(n).unwrap();
(n.to_string(), child.weight(map))
}).collect()
}
}
pub fn adv_main(input: Vec<String>) {
let mut map = HashMap::<String, Node>::new();
let mut left = Vec::new();
let mut right = Vec::new();
for line in input {
let chunks: Vec<_> = line.split("->").map(|s| s.trim()).collect();
let l: Vec<_> = chunks[0].split_whitespace().collect();
left.push(l[0].to_string());
let end = l[1].len() - 1;
let weight: u32 = (&l[1][1..end]).parse().unwrap();
let children: Vec<String> = if let Some(r) = chunks.get(1) {
let r: Vec<_> = r.split(", ").map(|s| s.to_string()).collect();
right.extend(r.clone());
r
} else {
vec![]
};
map.insert(l[0].to_string(), Node {
weight,
children,
});
}
for l in &left {
if !right.contains(l) {
let mut root = map.get(l).unwrap();
println!("p1: {}", l);
let mut weights = root.get_weights(&map);
weights.sort_by_key(|&(_, v)| -(v as i64));
println!("weights: {:?}", weights);
let diff = weights[0].1 - weights[1].1;
while weights[0].1 - weights[1].1 > 0 {
root = map.get(&weights[0].0).unwrap();
weights = root.get_weights(&map);
weights.sort_by_key(|&(_, v)| -(v as i64));
println!("node: {:?}, weights: {:?}", root.weight, weights);
}
println!("p2: {}", root.weight - diff);
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment