|
| 1 | +use std::collections::HashMap; |
| 2 | +use std::str::FromStr; |
| 3 | +use std::sync::OnceLock; |
| 4 | + |
| 5 | +use aoclp::anyhow::Context; |
| 6 | +use aoclp::regex::Regex; |
| 7 | +use aoclp::solvers_impl::input::safe_get_input_as_many; |
| 8 | +use itertools::Itertools; |
| 9 | + |
| 10 | +pub fn part_1() -> usize { |
| 11 | + let devices = devices_map(); |
| 12 | + let mut cache = HashMap::new(); |
| 13 | + num_paths(&devices, "you", true, true, &mut cache) |
| 14 | +} |
| 15 | + |
| 16 | +pub fn part_2() -> usize { |
| 17 | + let devices = devices_map(); |
| 18 | + let mut cache = HashMap::new(); |
| 19 | + num_paths(&devices, "svr", false, false, &mut cache) |
| 20 | +} |
| 21 | + |
| 22 | +fn devices_map() -> HashMap<String, Vec<String>> { |
| 23 | + input().into_iter().map(|d| (d.name, d.outputs)).collect() |
| 24 | +} |
| 25 | + |
| 26 | +fn num_paths( |
| 27 | + devices: &HashMap<String, Vec<String>>, |
| 28 | + cur: &str, |
| 29 | + dac: bool, |
| 30 | + fft: bool, |
| 31 | + cache: &mut HashMap<(String, bool, bool), usize>, |
| 32 | +) -> usize { |
| 33 | + if let Some(num) = cache.get(&(cur.to_string(), dac, fft)) { |
| 34 | + return *num; |
| 35 | + } |
| 36 | + if cur == "out" { |
| 37 | + return if dac && fft { 1 } else { 0 }; |
| 38 | + } |
| 39 | + |
| 40 | + let (dac, fft) = (dac || cur == "dac", fft || cur == "fft"); |
| 41 | + let outputs = &devices[cur]; |
| 42 | + let num = outputs |
| 43 | + .iter() |
| 44 | + .map(|d| num_paths(devices, d, dac, fft, cache)) |
| 45 | + .sum(); |
| 46 | + cache.insert((cur.to_string(), dac, fft), num); |
| 47 | + num |
| 48 | +} |
| 49 | + |
| 50 | +#[derive(Debug, Clone)] |
| 51 | +struct Device { |
| 52 | + name: String, |
| 53 | + outputs: Vec<String>, |
| 54 | +} |
| 55 | + |
| 56 | +impl FromStr for Device { |
| 57 | + type Err = aoclp::Error; |
| 58 | + |
| 59 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 60 | + static REGEX: OnceLock<Regex> = OnceLock::new(); |
| 61 | + let re = |
| 62 | + REGEX.get_or_init(|| Regex::new(r"^(?<name>\w+):\s+(?<outputs>(?:\w+\s*)+)$").unwrap()); |
| 63 | + |
| 64 | + let captures = re |
| 65 | + .captures(s) |
| 66 | + .with_context(|| format!("invalid device spec: {s}"))?; |
| 67 | + let name = &captures["name"]; |
| 68 | + let outputs = &captures["outputs"]; |
| 69 | + let outputs = outputs.split_ascii_whitespace().map_into().collect_vec(); |
| 70 | + |
| 71 | + Ok(Self { name: name.into(), outputs }) |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +fn input() -> Vec<Device> { |
| 76 | + safe_get_input_as_many(2025, 11) |
| 77 | +} |
0 commit comments