|
| 1 | +use std::collections::HashMap; |
| 2 | + |
| 3 | +use common::{Answer, solution}; |
| 4 | + |
| 5 | +solution!("Reactor", 11); |
| 6 | + |
| 7 | +fn part_a(input: &str) -> Answer { |
| 8 | + let mut map = HashMap::new(); |
| 9 | + |
| 10 | + for line in input.lines() { |
| 11 | + let (from, to) = line.split_once(": ").unwrap(); |
| 12 | + let to = to.split_whitespace().collect::<Vec<_>>(); |
| 13 | + map.insert(from, to); |
| 14 | + } |
| 15 | + |
| 16 | + fn count_paths(map: &HashMap<&str, Vec<&str>>, current: &str) -> u64 { |
| 17 | + if current == "out" { |
| 18 | + return 1; |
| 19 | + } |
| 20 | + |
| 21 | + let mut out = 0; |
| 22 | + |
| 23 | + for child in &map[current] { |
| 24 | + out += count_paths(map, child); |
| 25 | + } |
| 26 | + |
| 27 | + out |
| 28 | + } |
| 29 | + |
| 30 | + count_paths(&map, "you").into() |
| 31 | +} |
| 32 | + |
| 33 | +fn part_b(input: &str) -> Answer { |
| 34 | + let mut map = HashMap::new(); |
| 35 | + |
| 36 | + for line in input.lines() { |
| 37 | + let (from, to) = line.split_once(": ").unwrap(); |
| 38 | + let to = to.split_whitespace().collect::<Vec<_>>(); |
| 39 | + map.insert(from, to); |
| 40 | + } |
| 41 | + |
| 42 | + fn count_paths<'a>( |
| 43 | + memo: &mut HashMap<(&'a str, bool, bool), u64>, |
| 44 | + map: &HashMap<&str, Vec<&'a str>>, |
| 45 | + current: &'a str, |
| 46 | + mut fft: bool, |
| 47 | + mut dac: bool, |
| 48 | + ) -> u64 { |
| 49 | + let key = (current, fft, dac); |
| 50 | + if let Some(memo) = memo.get(&key) { |
| 51 | + return *memo; |
| 52 | + } |
| 53 | + |
| 54 | + if current == "out" { |
| 55 | + if fft && dac { |
| 56 | + return 1; |
| 57 | + } |
| 58 | + return 0; |
| 59 | + } |
| 60 | + |
| 61 | + if current == "fft" { |
| 62 | + fft = true; |
| 63 | + } |
| 64 | + |
| 65 | + if current == "dac" { |
| 66 | + dac = true; |
| 67 | + } |
| 68 | + |
| 69 | + let mut out = 0; |
| 70 | + for child in &map[current] { |
| 71 | + out += count_paths(memo, map, child, fft, dac); |
| 72 | + } |
| 73 | + |
| 74 | + memo.insert(key, out); |
| 75 | + out |
| 76 | + } |
| 77 | + |
| 78 | + count_paths(&mut HashMap::new(), &map, "svr", false, false).into() |
| 79 | +} |
| 80 | + |
| 81 | +#[cfg(test)] |
| 82 | +mod test { |
| 83 | + use indoc::indoc; |
| 84 | + |
| 85 | + const CASE: &str = indoc! {" |
| 86 | + svr: aaa bbb |
| 87 | + aaa: fft |
| 88 | + fft: ccc |
| 89 | + bbb: tty |
| 90 | + tty: ccc |
| 91 | + ccc: ddd eee |
| 92 | + ddd: hub |
| 93 | + hub: fff |
| 94 | + eee: dac |
| 95 | + dac: fff |
| 96 | + fff: ggg hhh |
| 97 | + ggg: out |
| 98 | + hhh: out |
| 99 | + "}; |
| 100 | + |
| 101 | + #[test] |
| 102 | + fn part_a() { |
| 103 | + assert_eq!(super::part_a(CASE), 5.into()); |
| 104 | + } |
| 105 | + |
| 106 | + #[test] |
| 107 | + fn part_b() { |
| 108 | + assert_eq!(super::part_b(CASE), 2.into()); |
| 109 | + } |
| 110 | +} |
0 commit comments