Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit cd1b76c

Browse files
Merge pull request #3 from markjfisher/main
Fix early exit from validation before all terms are used
2 parents 037ab67 + 25ebadb commit cd1b76c

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

‎src/year2024/day07.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,17 @@ pub fn part2(input: &Input) -> u64 {
8181
}
8282

8383
fn valid(terms: &[u64], test_value: u64, index: usize, concat: bool) -> bool {
84-
(test_value == 0)
85-
|| (concat
86-
&& test_value % next_power_of_ten(terms[index]) == terms[index]
87-
&& valid(terms, test_value / next_power_of_ten(terms[index]), index - 1, concat))
84+
if test_value == 0 {
85+
return index == 0;
86+
}
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))
8895
|| (test_value % terms[index] == 0
8996
&& valid(terms, test_value / terms[index], index - 1, concat))
9097
|| (test_value >= terms[index]

‎tests/year2024/day07_test.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,23 @@ const EXAMPLE: &str = "\
1111
21037: 9 7 18 13
1212
292: 11 6 16 20";
1313

14+
const EXAMPLE2: &str = "\
15+
190: 10 19
16+
11174: 15 8 9 79 74
17+
729: 6 6 7 37 650";
18+
1419
#[test]
1520
fn part1_test() {
1621
let input = parse(EXAMPLE);
1722
assert_eq!(part1(&input), 3749);
23+
let input2 = parse(EXAMPLE2);
24+
assert_eq!(part1(&input2), 190);
1825
}
1926

2027
#[test]
2128
fn part2_test() {
2229
let input = parse(EXAMPLE);
2330
assert_eq!(part2(&input), 11387);
31+
let input2 = parse(EXAMPLE2);
32+
assert_eq!(part2(&input2), 11364);
2433
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /