|
| 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 check(&equation, equation[0], equation.len() - 1, false) { |
| 25 | + part_one += equation[0]; |
| 26 | + part_two += equation[0]; |
| 27 | + } else if check(&equation, equation[0], equation.len() - 1, true) { |
| 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 check(terms: &[u64], test_value: u64, index: usize, concat: bool) -> bool { |
| 46 | + (test_value == 0) |
| 47 | + || (concat |
| 48 | + && test_value % next_power_of_ten(terms[index]) == terms[index] |
| 49 | + && check(terms, test_value / next_power_of_ten(terms[index]), index - 1, concat)) |
| 50 | + || (test_value % terms[index] == 0 |
| 51 | + && check(terms, test_value / terms[index], index - 1, concat)) |
| 52 | + || (test_value >= terms[index] |
| 53 | + && check(terms, test_value - terms[index], index - 1, concat)) |
| 54 | +} |
| 55 | + |
| 56 | +fn next_power_of_ten(n: u64) -> u64 { |
| 57 | + let mut power = 10; |
| 58 | + |
| 59 | + while power <= n { |
| 60 | + power *= 10; |
| 61 | + } |
| 62 | + |
| 63 | + power |
| 64 | +} |
0 commit comments