|
31 | 31 | //! ```none
|
32 | 32 | //! Test Value: 2
|
33 | 33 | //! Equation: 2
|
34 |
| -//! Addition is possible |
35 |
| -//! Multiplication is possible |
36 |
| -//! Concatenation is possible |
37 | 34 | //! ```
|
38 | 35 | //!
|
39 |
| -//! Following the addition or concatentation branches results in a test value of 0 which means |
40 |
| -//! that all terms have been applied successfully and the equation is valid. |
| 36 | +//! The test value is equal to the last term which means that the equation is valid. |
41 | 37 | //!
|
42 | 38 | //! Inverse concenation can be implemented without time consuming conversion to or from
|
43 | 39 | //! strings by dividing the left term by the next power of ten greater than the right term.
|
@@ -81,29 +77,26 @@ pub fn part2(input: &Input) -> u64 {
|
81 | 77 | }
|
82 | 78 |
|
83 | 79 | fn valid(terms: &[u64], test_value: u64, index: usize, concat: bool) -> bool {
|
84 |
| - if test_value == 0 { |
85 |
| - return index == 0; |
| 80 | + if index == 1 { |
| 81 | + test_value == terms[1] |
| 82 | + } else { |
| 83 | + (concat |
| 84 | + && test_value % next_power_of_ten(terms[index]) == terms[index] |
| 85 | + && valid(terms, test_value / next_power_of_ten(terms[index]), index - 1, concat)) |
| 86 | + || (test_value % terms[index] == 0 |
| 87 | + && valid(terms, test_value / terms[index], index - 1, concat)) |
| 88 | + || (test_value >= terms[index] |
| 89 | + && valid(terms, test_value - terms[index], index - 1, concat)) |
86 | 90 | }
|
87 |
| - |
88 |
| - if index == 0 { |
89 |
| - return false; |
90 |
| - } |
91 |
| - |
92 |
| - (concat |
93 |
| - && test_value % next_power_of_ten(terms[index]) == terms[index] |
94 |
| - && valid(terms, test_value / next_power_of_ten(terms[index]), index - 1, concat)) |
95 |
| - || (test_value % terms[index] == 0 |
96 |
| - && valid(terms, test_value / terms[index], index - 1, concat)) |
97 |
| - || (test_value >= terms[index] |
98 |
| - && valid(terms, test_value - terms[index], index - 1, concat)) |
99 | 91 | }
|
100 | 92 |
|
| 93 | +#[inline] |
101 | 94 | fn next_power_of_ten(n: u64) -> u64 {
|
102 |
| - let mut power = 10; |
103 |
| - |
104 |
| - while power <= n { |
105 |
| - power *= 10; |
| 95 | + if n < 10 { |
| 96 | + 10 |
| 97 | + } else if n < 100 { |
| 98 | + 100 |
| 99 | + } else { |
| 100 | + 1000 |
106 | 101 | }
|
107 |
| - |
108 |
| - power |
109 | 102 | }
|
0 commit comments