Browse Source

Day 8 part 2

Tyler Hallada 5 years ago
parent
commit
f155273a5b
2 changed files with 40 additions and 1 deletions
  1. 38 0
      src/day8.rs
  2. 2 1
      src/main.rs

+ 38 - 0
src/day8.rs

@@ -11,6 +11,11 @@ pub fn solve_part1() -> Result<u32> {
11 11
     Ok(sum_metadata(&license, 0, 0).0)
12 12
 }
13 13
 
14
+pub fn solve_part2() -> Result<u32> {
15
+    let license = read_license(INPUT)?;
16
+    Ok(sum_metadata_with_indices(&license, 0).0)
17
+}
18
+
14 19
 fn read_license(filename: &str) -> Result<Vec<u32>> {
15 20
     let license = fs::read_to_string(filename)?;
16 21
     let license = license.trim();
@@ -39,6 +44,34 @@ fn sum_metadata(license: &[u32], mut index: usize, mut sum_acc: u32) -> (u32, us
39 44
     (sum_acc, index)
40 45
 }
41 46
 
47
+fn sum_metadata_with_indices(license: &[u32], mut index: usize) -> (u32, usize) {
48
+    let mut sum: u32 = 0;
49
+    let num_children = license[index];
50
+    let num_metadata = license[index + 1];
51
+    index += 2;
52
+    if num_children != 0 {
53
+        let mut child_sums: Vec<u32> = Vec::new();
54
+        for _ in 0..num_children {
55
+            let (child_sum, child_index) = sum_metadata_with_indices(license, index);
56
+            index = child_index;
57
+            child_sums.push(child_sum)
58
+        }
59
+
60
+        if num_metadata != 0 {
61
+            sum = license[index..index + num_metadata as usize]
62
+                .iter()
63
+                .map(|num| *child_sums.get(*num as usize - 1).unwrap_or(&0))
64
+                .sum();
65
+            index += num_metadata as usize;
66
+
67
+        }
68
+    } else if num_metadata != 0 {
69
+        sum = license[index..index + num_metadata as usize].iter().sum();
70
+        index += num_metadata as usize;
71
+    }
72
+    (sum, index)
73
+}
74
+
42 75
 #[cfg(test)]
43 76
 mod tests {
44 77
     use super::*;
@@ -57,4 +90,9 @@ mod tests {
57 90
     fn sums_license_metadata() {
58 91
         assert_eq!(sum_metadata(&test_license(), 0, 0).0, 138);
59 92
     }
93
+
94
+    #[test]
95
+    fn sums_license_metadata_with_indices() {
96
+        assert_eq!(sum_metadata_with_indices(&test_license(), 0).0, 66);
97
+    }
60 98
 }

+ 2 - 1
src/main.rs

@@ -35,5 +35,6 @@ fn main() {
35 35
     // println!("{}", day7::solve_part1().unwrap());
36 36
     // println!("{}", day7::solve_part2().unwrap());
37 37
     println!("Day 8:");
38
-    println!("{}", day8::solve_part1().unwrap());
38
+    // println!("{}", day8::solve_part1().unwrap());
39
+    println!("{}", day8::solve_part2().unwrap());
39 40
 }