|
1 | 1 | use crate::solutions::Solution; |
| 2 | +use itertools::Itertools; |
2 | 3 | pub struct Day07; |
3 | 4 |
|
4 | 5 | impl Solution for Day07 { |
5 | | - fn part_one(&self, _input: &str) -> String { |
6 | | - String::from('0') |
| 6 | + fn part_one(&self, input: &str) -> String { |
| 7 | + input |
| 8 | + .lines() |
| 9 | + .map(|l| { |
| 10 | + let (left, right) = l.split(": ").collect_tuple().unwrap(); |
| 11 | + let test_value: usize = left.parse().unwrap(); |
| 12 | + let mut numbers: Vec<usize> = right |
| 13 | + .split_whitespace() |
| 14 | + .map(|s| s.parse().unwrap()) |
| 15 | + .collect(); |
| 16 | + |
| 17 | + let current = numbers.remove(0); |
| 18 | + let value = Self::solve(test_value, current, numbers.clone()); |
| 19 | + |
| 20 | + if value { |
| 21 | + return test_value; |
| 22 | + } |
| 23 | + |
| 24 | + 0 |
| 25 | + }) |
| 26 | + .sum::<usize>() |
| 27 | + .to_string() |
7 | 28 | } |
8 | 29 |
|
9 | 30 | fn part_two(&self, _input: &str) -> String { |
10 | 31 | String::from('0') |
11 | 32 | } |
12 | 33 | } |
13 | 34 |
|
| 35 | +impl Day07 { |
| 36 | + fn solve(expected: usize, current: usize, number_lefts: Vec<usize>) -> bool { |
| 37 | + let mut numbers = number_lefts.clone(); |
| 38 | + |
| 39 | + if numbers.is_empty() { |
| 40 | + return expected == current; |
| 41 | + } |
| 42 | + |
| 43 | + let next = numbers.remove(0); |
| 44 | + |
| 45 | + let current_add = current + next; |
| 46 | + let current_multiply = current * next; |
| 47 | + |
| 48 | + Self::solve(expected, current_add, numbers.clone()) |
| 49 | + || Self::solve(expected, current_multiply, numbers) |
| 50 | + } |
| 51 | +} |
| 52 | + |
14 | 53 | #[cfg(test)] |
15 | 54 | mod tests { |
16 | 55 | use crate::solutions::year2024::day07::Day07; |
17 | 56 | use crate::solutions::Solution; |
18 | 57 |
|
19 | | - const EXAMPLE: &str = r#""#; |
| 58 | + const EXAMPLE: &str = r#"190: 10 19 |
| 59 | +3267: 81 40 27 |
| 60 | +83: 17 5 |
| 61 | +156: 15 6 |
| 62 | +7290: 6 8 6 15 |
| 63 | +161011: 16 10 13 |
| 64 | +192: 17 8 14 |
| 65 | +21037: 9 7 18 13 |
| 66 | +292: 11 6 16 20"#; |
20 | 67 |
|
21 | 68 | #[test] |
22 | 69 | fn part_one_example_test() { |
23 | | - assert_eq!("0", Day07.part_one(EXAMPLE)); |
| 70 | + assert_eq!("3749", Day07.part_one(EXAMPLE)); |
24 | 71 | } |
25 | 72 | } |
0 commit comments