Johann Woelper пре 6 година
родитељ
комит
ea63981567
2 измењених фајлова са 79 додато и 2 уклоњено
  1. 74 0
      src/day_6.rs
  2. 5 2
      src/main.rs

+ 74 - 0
src/day_6.rs

@@ -0,0 +1,74 @@
+use std::collections::HashMap;
+
+#[derive(Debug, Default)]
+struct Planet {
+    parent: Option<String>,
+    children: Vec<String>
+}
+
+fn get_parent(sys: &HashMap<String, Planet>, planet: &String) -> Option<String> {
+    let p = sys.get(planet).unwrap();
+    // println!("get parent of {}: {:?}", planet, p.parent);
+    p.parent.clone()
+}
+
+fn get_parents(sys: &HashMap<String, Planet>, planet: &String) -> u32{
+
+    let mut count = 0;
+    let mut planet_name = planet.clone();
+    loop {
+        match get_parent(sys, &planet_name) {
+            Some(p) => {
+                count += 1;
+                planet_name = p;
+            },
+            None => break
+        }
+    }
+    count
+}
+
+pub fn main() {
+    let mut solar_system : HashMap<String, Planet> = HashMap::new();
+
+    let input = include_str!("day6.txt");
+    for rel in input.split("\n"){
+
+        // dbg!(rel);
+        let seq: Vec<String> = rel.split(")").map(|x| x.to_string()).collect();
+        let parent = &seq[0];
+        let child = &seq[1];
+
+        match solar_system.get_mut(parent) {
+            Some(planet) => {
+                // Planet exists, add child to it
+                planet.children.push(child.to_string());
+            },
+            None => {
+                // This planet will be the root since it's not there
+                let p = Planet {
+                    parent : None,
+                    children : vec![child.to_string()]
+                };
+                solar_system.insert(parent.to_string(), p);
+            }
+        }
+        
+        // And add the child to the solar system, along with it's parent
+        let c = Planet {parent: Some(parent.to_string()), children: vec![]};
+        solar_system.insert(child.to_string(), c);
+
+    }
+
+
+    let mut pcount = 0;
+
+    for (n, p) in &solar_system {
+        let num_p = get_parents(&solar_system, &n);
+        println!("Planet {} {}", n, num_p);
+        pcount += num_p;
+
+    }
+    println!("Count {}", pcount);
+
+}

+ 5 - 2
src/main.rs

@@ -3,13 +3,16 @@ mod day_2;
 mod day_3;
 mod day_4;
 mod day_5;
-
+mod day_6;
+// mod d5;
 
 
 
 
 
 fn main() {
-    day_3::main();
+    // day_3::main();
     // day_5::main();
+    day_6::main();
+
 }