|
| 1 | +use std::vec; |
| 2 | + |
| 3 | +pub fn part1(contents: &str) -> i64 { |
| 4 | + calculate_joltage(contents, 2) |
| 5 | +} |
| 6 | + |
| 7 | +pub fn part2(contents: &str) -> i64 { |
| 8 | + calculate_joltage(contents, 12) |
| 9 | +} |
| 10 | + |
| 11 | +fn calculate_joltage(contents: &str, digits: usize) -> i64 { |
| 12 | + let mut sum = 0; |
| 13 | + for l in contents.lines() { |
| 14 | + let nums: Vec<i64> = l.chars().map(|c| c.to_digit(10).unwrap() as i64).collect(); |
| 15 | + let mut indices = vec![]; |
| 16 | + find_max_recursive(&nums, 0, nums.len(), &mut indices, digits); |
| 17 | + indices.sort(); |
| 18 | + |
| 19 | + sum += indices |
| 20 | + .iter() |
| 21 | + .map(|e| nums[*e]) |
| 22 | + .reduce(|acc, e| acc * 10 + e) |
| 23 | + .unwrap(); |
| 24 | + } |
| 25 | + sum |
| 26 | +} |
| 27 | + |
| 28 | +fn find_max_recursive( |
| 29 | + nums: &[i64], |
| 30 | + start: usize, |
| 31 | + end: usize, |
| 32 | + indices: &mut Vec<usize>, |
| 33 | + digits: usize, |
| 34 | +) { |
| 35 | + if start == end || indices.len() == digits { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + let max_index = find_max_index(nums, start, end); |
| 40 | + indices.push(max_index); |
| 41 | + find_max_recursive(nums, max_index + 1, end, indices, digits); |
| 42 | + find_max_recursive(nums, start, max_index, indices, digits); |
| 43 | +} |
| 44 | + |
| 45 | +fn find_max_index(nums: &[i64], start: usize, end: usize) -> usize { |
| 46 | + let mut max = -1; |
| 47 | + let mut max_index: usize = 0; |
| 48 | + for (i, n) in nums[start..end].iter().enumerate() { |
| 49 | + if *n > max { |
| 50 | + max = *n; |
| 51 | + max_index = start + i; |
| 52 | + } |
| 53 | + } |
| 54 | + max_index |
| 55 | +} |
| 56 | + |
| 57 | +#[cfg(test)] |
| 58 | +mod tests { |
| 59 | + use super::*; |
| 60 | + |
| 61 | + #[test] |
| 62 | + fn test_part1() { |
| 63 | + let input = vec![ |
| 64 | + "987654321111111", |
| 65 | + "811111111111119", |
| 66 | + "234234234234278", |
| 67 | + "818181911112111", |
| 68 | + ]; |
| 69 | + |
| 70 | + assert_eq!(part1(&input.join("\n")), 357); |
| 71 | + } |
| 72 | + |
| 73 | + #[test] |
| 74 | + fn test_part2() { |
| 75 | + let input = vec![ |
| 76 | + "987654321111111", |
| 77 | + "811111111111119", |
| 78 | + "234234234234278", |
| 79 | + "818181911112111", |
| 80 | + ]; |
| 81 | + |
| 82 | + assert_eq!(part2(&input.join("\n")), 3121910778619); |
| 83 | + } |
| 84 | +} |
0 commit comments