|
| 1 | +advent_of_code::solution!(3); |
| 2 | + |
| 3 | +use advent_of_code::maneatingape::parse::*; |
| 4 | +use regex::Regex; |
| 5 | + |
| 6 | +enum Command { |
| 7 | + Enable, |
| 8 | + Disable, |
| 9 | + Multiply(u32, u32), |
| 10 | +} |
| 11 | + |
| 12 | +fn parse_data(input: &str) -> Vec<Command> { |
| 13 | + let mut commands = vec![]; |
| 14 | + |
| 15 | + let mul_re = Regex::new(r"^mul\((\d{1,3}),(\d{1,3})\)").unwrap(); |
| 16 | + |
| 17 | + for i in 0..input.len() { |
| 18 | + if input[i..].starts_with("mul") { |
| 19 | + if let Some(m) = mul_re.captures(&input[i..]) { |
| 20 | + let [x, y] = m.extract().1.map(|x| x.unsigned()); |
| 21 | + commands.push(Command::Multiply(x, y)); |
| 22 | + } |
| 23 | + } else if input[i..].starts_with("do()") { |
| 24 | + commands.push(Command::Enable); |
| 25 | + } else if input[i..].starts_with("don't()") { |
| 26 | + commands.push(Command::Disable); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + commands |
| 31 | +} |
| 32 | + |
| 33 | +pub fn part_one(input: &str) -> Option<u32> { |
| 34 | + let data = parse_data(input); |
| 35 | + |
| 36 | + let result = data |
| 37 | + .into_iter() |
| 38 | + .map(|c| match c { |
| 39 | + Command::Multiply(x, y) => x * y, |
| 40 | + _ => 0, |
| 41 | + }) |
| 42 | + .sum(); |
| 43 | + |
| 44 | + Some(result) |
| 45 | +} |
| 46 | + |
| 47 | +pub fn part_two(input: &str) -> Option<u32> { |
| 48 | + let data = parse_data(input); |
| 49 | + |
| 50 | + let mut enabled = true; |
| 51 | + |
| 52 | + let mut result = 0; |
| 53 | + for c in data { |
| 54 | + match c { |
| 55 | + Command::Multiply(x, y) => result += if enabled { x * y } else { 0 }, |
| 56 | + Command::Enable => enabled = true, |
| 57 | + Command::Disable => enabled = false, |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + Some(result) |
| 62 | +} |
| 63 | + |
| 64 | +#[cfg(test)] |
| 65 | +mod tests { |
| 66 | + use super::*; |
| 67 | + |
| 68 | + #[test] |
| 69 | + fn test_part_one() { |
| 70 | + let result = part_one(&advent_of_code::template::read_file("examples", DAY)); |
| 71 | + assert_eq!(result, Some(161)); |
| 72 | + } |
| 73 | + |
| 74 | + #[test] |
| 75 | + fn test_part_two() { |
| 76 | + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); |
| 77 | + assert_eq!(result, Some(48)); |
| 78 | + } |
| 79 | +} |
0 commit comments