Skip to content

Commit

Permalink
perf(07/2024): improve readability and simplify code
Browse files Browse the repository at this point in the history
  • Loading branch information
manhunto committed Dec 8, 2024
1 parent 8471605 commit cb5517b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 18 deletions.
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
| [Day 4: Ceres Search](src/solutions/year2024/day04.rs) | ⭐⭐ | 8.620 | 6.918 |
| [Day 5: Print Queue](src/solutions/year2024/day05.rs) | ⭐⭐ | 3.151 | 11.874 |
| [Day 6: Guard Gallivant](src/solutions/year2024/day06.rs) || 8.738 | |
| [Day 7: Bridge Repair](src/solutions/year2024/day07.rs) || 18.503 | |
| [Day 7: Bridge Repair](src/solutions/year2024/day07.rs) || 1.536 | |

# 2023

Expand Down
30 changes: 13 additions & 17 deletions src/solutions/year2024/day07.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,22 @@ impl Solution for Day07 {
fn part_one(&self, input: &str) -> String {
input
.lines()
.map(|l| {
.filter_map(|l| {
let (left, right) = l.split(": ").collect_tuple().unwrap();
let test_value: usize = left.parse().unwrap();
let mut numbers: Vec<usize> = right
let numbers: Vec<usize> = right
.split_whitespace()
.map(|s| s.parse().unwrap())
.collect();

let current = numbers.remove(0);
let value = Self::solve(test_value, current, numbers.clone());
let current = numbers[0];
let remaining = &numbers[1..];

if value {
return test_value;
if Self::solve(test_value, current, remaining) {
Some(test_value)
} else {
None
}

0
})
.sum::<usize>()
.to_string()
Expand All @@ -33,20 +33,16 @@ impl Solution for Day07 {
}

impl Day07 {
fn solve(expected: usize, current: usize, number_lefts: Vec<usize>) -> bool {
let mut numbers = number_lefts.clone();

fn solve(expected: usize, current: usize, numbers: &[usize]) -> bool {
if numbers.is_empty() {
return expected == current;
}

let next = numbers.remove(0);

let current_add = current + next;
let current_multiply = current * next;
let next = numbers[0];
let remaining = &numbers[1..];

Self::solve(expected, current_add, numbers.clone())
|| Self::solve(expected, current_multiply, numbers)
Self::solve(expected, current + next, remaining)
|| Self::solve(expected, current * next, remaining)
}
}

Expand Down

0 comments on commit cb5517b

Please sign in to comment.