Skip to content

Commit

Permalink
feat(07/2024): solve second part
Browse files Browse the repository at this point in the history
  • Loading branch information
manhunto committed Dec 8, 2024
1 parent 7670d8d commit 3a71c0f
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 4 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) | | 1.198 | |
| [Day 7: Bridge Repair](src/solutions/year2024/day07.rs) | | 1.198 | 219.754 |

# 2023

Expand Down
50 changes: 47 additions & 3 deletions src/solutions/year2024/day07.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,28 @@ impl Solution for Day07 {
.to_string()
}

fn part_two(&self, _input: &str) -> String {
String::from('0')
fn part_two(&self, input: &str) -> String {
input
.lines()
.filter_map(|l| {
let (left, right) = l.split(": ").collect_tuple().unwrap();
let test_value: usize = left.parse().unwrap();
let numbers: Vec<usize> = right
.split_whitespace()
.map(|s| s.parse().unwrap())
.collect();

let current = numbers[0];
let remaining = &numbers[1..];

if Self::solve_part_two(test_value, current, remaining) {
Some(test_value)
} else {
None
}
})
.sum::<usize>()
.to_string()
}
}

Expand All @@ -37,7 +57,7 @@ impl Day07 {
if numbers.is_empty() {
return expected == current;
}

if expected < current {
return false;
}
Expand All @@ -48,6 +68,25 @@ impl Day07 {
Self::solve(expected, current + next, remaining)
|| Self::solve(expected, current * next, remaining)
}

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

if expected < current {
return false;
}

let next = numbers[0];
let remaining = &numbers[1..];

let i = format!("{}{}", current, next).parse().unwrap();

Self::solve_part_two(expected, current + next, remaining)
|| Self::solve_part_two(expected, current * next, remaining)
|| Self::solve_part_two(expected, i, remaining)
}
}

#[cfg(test)]
Expand All @@ -69,4 +108,9 @@ mod tests {
fn part_one_example_test() {
assert_eq!("3749", Day07.part_one(EXAMPLE));
}

#[test]
fn part_two_example_test() {
assert_eq!("11387", Day07.part_two(EXAMPLE));
}
}

0 comments on commit 3a71c0f

Please sign in to comment.