|
| 1 | +//! # Bridge Repair |
| 2 | +//! |
| 3 | +//! Concenation in part two can be implemented without time consuming conversion to or from strings. |
| 4 | +//! Instead multiply the left term by the next power of ten greater than the right term, then add |
| 5 | +//! the right term. For example: |
| 6 | +//! |
| 7 | +//! * 15 || 6 = 15 * 10 + 6 |
| 8 | +//! * 17 || 14 = 17 * 100 + 14 |
| 9 | +//! |
| 10 | +//! Finding the next power of 10 is quick as the input only contains 1 to 3 digit numbers. |
| 11 | +use crate::util::parse::*; |
| 12 | + |
| 13 | +type Input = (u64, u64); |
| 14 | + |
| 15 | +pub fn parse(input: &str) -> Input { |
| 16 | + let mut equation = Vec::new(); |
| 17 | + let mut part_one = 0; |
| 18 | + let mut part_two = 0; |
| 19 | + |
| 20 | + for line in input.lines() { |
| 21 | + equation.extend(line.iter_unsigned::<u64>()); |
| 22 | + |
| 23 | + // If an equation is valid for part one then it's also valid for part two. |
| 24 | + if basic(&equation, equation[0], equation[1], 2) { |
| 25 | + part_one += equation[0]; |
| 26 | + part_two += equation[0]; |
| 27 | + } else if advanced(&equation, equation[0], equation[1], 2) { |
| 28 | + part_two += equation[0]; |
| 29 | + } |
| 30 | + |
| 31 | + equation.clear(); |
| 32 | + } |
| 33 | + |
| 34 | + (part_one, part_two) |
| 35 | +} |
| 36 | + |
| 37 | +pub fn part1(input: &Input) -> u64 { |
| 38 | + input.0 |
| 39 | +} |
| 40 | + |
| 41 | +pub fn part2(input: &Input) -> u64 { |
| 42 | + input.1 |
| 43 | +} |
| 44 | + |
| 45 | +fn basic(terms: &[u64], test_value: u64, total: u64, index: usize) -> bool { |
| 46 | + if index == terms.len() { |
| 47 | + return total == test_value; |
| 48 | + } |
| 49 | + if total > test_value { |
| 50 | + return false; |
| 51 | + } |
| 52 | + |
| 53 | + basic(terms, test_value, total + terms[index], index + 1) |
| 54 | + || basic(terms, test_value, total * terms[index], index + 1) |
| 55 | +} |
| 56 | + |
| 57 | +fn advanced(terms: &[u64], test_value: u64, total: u64, index: usize) -> bool { |
| 58 | + if index == terms.len() { |
| 59 | + return total == test_value; |
| 60 | + } |
| 61 | + if total > test_value { |
| 62 | + return false; |
| 63 | + } |
| 64 | + |
| 65 | + advanced(terms, test_value, total + terms[index], index + 1) |
| 66 | + || advanced(terms, test_value, total * terms[index], index + 1) |
| 67 | + || advanced(terms, test_value, total * next_power(terms[index]) + terms[index], index + 1) |
| 68 | +} |
| 69 | + |
| 70 | +#[inline] |
| 71 | +fn next_power(n: u64) -> u64 { |
| 72 | + if n < 10 { |
| 73 | + 10 |
| 74 | + } else if n < 100 { |
| 75 | + 100 |
| 76 | + } else if n < 1000 { |
| 77 | + 1000 |
| 78 | + } else { |
| 79 | + unreachable!() |
| 80 | + } |
| 81 | +} |
0 commit comments