diff --git a/src/bin/03.rs b/src/bin/03.rs new file mode 100644 index 0000000..7ae9849 --- /dev/null +++ b/src/bin/03.rs @@ -0,0 +1,59 @@ +use aoc::*; + +const INPUT: &str = include_str!("../../input/03"); + +fn main() { + println!("Part 1: {}", part1(INPUT)); + println!("Part 2: {}", part2(INPUT)); +} + +#[test] +fn example() { + assert_example!(part1, "03-test", 357); + assert_example!(part2, "03-test", 3121910778619); +} + +fn part1(input: &str) -> i64 { + parse_input(input).map(|b| b.max_joltage(2)).sum() +} + +fn part2(input: &str) -> i64 { + parse_input(input).map(|b| b.max_joltage(12)).sum() +} + +struct Bank { + joltages: Vec, +} + +impl Bank { + fn max_joltage(&self, batteries: usize) -> i64 { + let mut sum = 0; + let mut lower_bound = 0; + + for b in 0..batteries { + let mut max_joltage = 0; + let upper_bound = self.joltages.len() - batteries + b; + for i in lower_bound..=upper_bound { + if self.joltages[i] > max_joltage { + max_joltage = self.joltages[i]; + lower_bound = i + 1; + } + } + sum = sum * 10 + max_joltage; + } + + sum + } + + fn parse(line: &str) -> Self { + let joltages = line + .chars() + .map(|c| c.to_digit(10).unwrap() as i64) + .collect(); + Self { joltages } + } +} + +fn parse_input(input: &str) -> impl Iterator + use<'_> { + input.lines().map(Bank::parse) +}