solution: day 1

This commit is contained in:
Matej Janezic 2023-12-01 06:39:51 +01:00
parent 000000203e
commit 00000030a5
Signed by: janezicmatej
GPG Key ID: 4298E230ED37B2C0
2 changed files with 98 additions and 0 deletions

10
data/examples/01.txt Normal file
View File

@ -0,0 +1,10 @@
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
two1nine
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen

88
src/bin/01.rs Normal file
View File

@ -0,0 +1,88 @@
pub fn part_one(input: &str) -> Option<u32> {
let mut c = 0;
for line in input.lines() {
let mut itr = line.chars().filter(|x| x.is_ascii_digit());
let f = itr.next().unwrap();
let l = itr.last().unwrap_or(f);
c += format!("{f}{l}").parse::<u32>().unwrap();
}
Some(c)
}
pub fn part_two(input: &str) -> Option<u32> {
let mut c = 0;
let nums = [
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
];
for line in input.lines() {
let mut first = (line.len(), None);
let mut last = (0, None);
for (idx, n) in nums.iter().enumerate() {
let matches: Vec<_> = line.match_indices(n).collect();
if matches.is_empty() {
continue;
}
let m = matches.first().unwrap();
if m.0 < first.0 {
first = (m.0, Some(idx + 1));
}
let m = matches.last().unwrap();
if m.0 >= last.0 {
last = (m.0, Some(idx + 1));
}
}
let mut itr = line.chars().enumerate().filter(|(_, x)| x.is_ascii_digit());
let Some(f) = itr.next() else {
c += format!("{}{}", first.1.unwrap(), last.1.unwrap())
.parse::<u32>()
.unwrap();
continue;
};
let l = itr.last().unwrap_or(f);
if f.0 < first.0 {
first = (f.0, f.1.to_string().parse().ok());
}
if l.0 >= last.0 {
last = (l.0, l.1.to_string().parse().ok());
}
c += format!("{}{}", first.1.unwrap(), last.1.unwrap())
.parse::<u32>()
.unwrap();
}
Some(c)
}
aoc::solution!(1);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
assert_eq!(
part_one(&aoc::template::read_file("examples", 1)),
Some(351)
);
}
#[test]
fn test_part_two() {
assert_eq!(
part_two(&aoc::template::read_file("examples", 1)),
Some(340)
);
}
}