feat: solve day 3
This commit is contained in:
parent
7f4517b9e6
commit
acbd3801ca
2 changed files with 98 additions and 0 deletions
5
data/examples/03.txt
Normal file
5
data/examples/03.txt
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
987654321111111
|
||||
811111111111119
|
||||
234234234234278
|
||||
818181911112111
|
||||
|
||||
93
src/bin/03.rs
Normal file
93
src/bin/03.rs
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
use std::cmp::Ordering;
|
||||
|
||||
use itertools::Itertools;
|
||||
|
||||
advent_of_code::solution!(3);
|
||||
|
||||
pub fn part_one(input: &str) -> Option<u64> {
|
||||
input
|
||||
.lines()
|
||||
.filter(|line| !line.is_empty())
|
||||
.map(|line| {
|
||||
let first = line
|
||||
.chars()
|
||||
.enumerate()
|
||||
.filter(|c| c.0 != line.len() - 1)
|
||||
.max_by(|a, b| {
|
||||
if a.1.cmp(&b.1) == Ordering::Equal {
|
||||
b.0.cmp(&a.0)
|
||||
} else {
|
||||
a.1.cmp(&b.1)
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let second = line
|
||||
.chars()
|
||||
.enumerate()
|
||||
.skip(first.0 + 1)
|
||||
.max_by(|a, b| {
|
||||
if a.1.cmp(&b.1) == Ordering::Equal {
|
||||
b.0.cmp(&a.0)
|
||||
} else {
|
||||
a.1.cmp(&b.1)
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
format!("{}{}", first.1, second.1)
|
||||
})
|
||||
.map(|num_str| num_str.parse().unwrap_or(0))
|
||||
.sum1()
|
||||
}
|
||||
|
||||
pub fn part_two(input: &str) -> Option<u64> {
|
||||
input
|
||||
.lines()
|
||||
.filter(|line| !line.is_empty())
|
||||
.map(|line| {
|
||||
let mut num_str = vec![];
|
||||
let mut prev = (0, '0');
|
||||
for i in 0..12 {
|
||||
let skip_amt = if i == 0 { 0 } else { prev.0 + 1 };
|
||||
let curr = line
|
||||
.chars()
|
||||
.enumerate()
|
||||
.filter(|c| c.0 <= line.len() - (12 - i))
|
||||
.skip(skip_amt)
|
||||
.max_by(|a, b| {
|
||||
if a.1.cmp(&b.1) == Ordering::Equal {
|
||||
b.0.cmp(&a.0)
|
||||
} else {
|
||||
a.1.cmp(&b.1)
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
num_str.push(curr.1);
|
||||
prev = curr;
|
||||
}
|
||||
|
||||
num_str.into_iter().join("")
|
||||
})
|
||||
.map(|num_str| num_str.parse().unwrap_or(0))
|
||||
.sum1()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_part_one() {
|
||||
let mut result = part_one(&advent_of_code::template::read_file("examples", DAY));
|
||||
assert_eq!(result, Some(357));
|
||||
|
||||
result = part_one("622262224226");
|
||||
assert_eq!(result, Some(66));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_part_two() {
|
||||
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
|
||||
assert_eq!(result, Some(3121910778619));
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue