|
| 1 | +advent_of_code::solution!(7); |
| 2 | + |
| 3 | +use advent_of_code::maneatingape::parse::*; |
| 4 | + |
| 5 | +fn parse_data(input: &str) -> Vec<Vec<u64>> { |
| 6 | + input |
| 7 | + .lines() |
| 8 | + .map(|line| line.iter_unsigned().collect()) |
| 9 | + .collect() |
| 10 | +} |
| 11 | + |
| 12 | +fn solve(result: u64, left: u64, right: &[u64], use_concatenation: bool) -> bool { |
| 13 | + if right.is_empty() { |
| 14 | + return result == left; |
| 15 | + } |
| 16 | + |
| 17 | + if left > result { |
| 18 | + return false; |
| 19 | + } |
| 20 | + |
| 21 | + let first_left_value = left + right[0]; |
| 22 | + if solve(result, first_left_value, &right[1..], use_concatenation) { |
| 23 | + return true; |
| 24 | + } |
| 25 | + |
| 26 | + let second_left_value = left * right[0]; |
| 27 | + if solve(result, second_left_value, &right[1..], use_concatenation) { |
| 28 | + return true; |
| 29 | + } |
| 30 | + |
| 31 | + if use_concatenation { |
| 32 | + let third_left_number = left * 10_u64.pow(right[0].ilog(10) + 1) + right[0]; |
| 33 | + if solve(result, third_left_number, &right[1..], use_concatenation) { |
| 34 | + return true; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + false |
| 39 | +} |
| 40 | + |
| 41 | +fn part_x(data: Vec<Vec<u64>>, use_concatenation: bool) -> u64 { |
| 42 | + data.into_iter() |
| 43 | + .filter(|line| solve(line[0], line[1], &line[2..], use_concatenation)) |
| 44 | + .map(|line| line[0]) |
| 45 | + .sum() |
| 46 | +} |
| 47 | + |
| 48 | +pub fn part_one(input: &str) -> Option<u64> { |
| 49 | + let data = parse_data(input); |
| 50 | + |
| 51 | + let result = part_x(data, false); |
| 52 | + |
| 53 | + Some(result) |
| 54 | +} |
| 55 | + |
| 56 | +pub fn part_two(input: &str) -> Option<u64> { |
| 57 | + let data = parse_data(input); |
| 58 | + |
| 59 | + let result = part_x(data, true); |
| 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(3749)); |
| 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(11387)); |
| 78 | + } |
| 79 | +} |
0 commit comments