Day 1 done

This commit is contained in:
Dylan Thies
2023-12-01 22:27:47 -05:00
parent c5f92ec1bc
commit ac6662445d
4 changed files with 62 additions and 40 deletions

View File

@@ -1,3 +1,2 @@
pub mod part1;
pub mod part2;

View File

@@ -1,14 +1,32 @@
use nom::{multi::{separated_list1}, self, character::complete::{alphanumeric1, newline}};
use nom::{
self,
character::complete::{alphanumeric1, newline},
multi::separated_list1,
};
pub fn part1(input: &str) -> nom::IResult<&str, String> {
let (_, values) = parse_input(input)?;
println!("{values:?}");
Ok(("", values.iter().map(|v| v.first().unwrap() * 10 + v.last().unwrap() ).sum::<u32>().to_string()))
Ok((
"",
values
.iter()
.map(|v| v.first().unwrap() * 10 + v.last().unwrap())
.sum::<u32>()
.to_string(),
))
}
fn parse_input(input: &str) -> nom::IResult<&str, Vec<Vec<u32>>> {
let (i, j) = separated_list1(newline, alphanumeric1)(input)?;
let res = j.iter().map(|v| v.chars().filter_map(|x| x.to_digit(10)).collect::<Vec<u32>>()).collect::<Vec<Vec<u32>>>();
let res = j
.iter()
.map(|v| {
v.chars()
.filter_map(|x| x.to_digit(10))
.collect::<Vec<u32>>()
})
.collect::<Vec<Vec<u32>>>();
Ok((i, res))
}
@@ -25,4 +43,5 @@ treb7uchet";
fn part1_works() {
let (_, result) = part1(INPUT).unwrap();
assert_eq!(result, "142".to_string());
}}
}
}

View File

@@ -1,12 +1,16 @@
pub fn part2(input: &str) -> String {
let values = input.lines().map(parse_line).collect::<Vec<Vec<u32>>>();
println!("{values:?}");
values.iter().map(|v| v.first().unwrap() * 10 + v.last().unwrap() ).sum::<u32>().to_string()
values
.iter()
.map(|v| v.first().unwrap() * 10 + v.last().unwrap())
.sum::<u32>()
.to_string()
}
fn parse_line(line: &str) -> Vec<u32> {
(0..line.len()).filter_map(|index| {
(0..line.len())
.filter_map(|index| {
let reduced_line = &line[index..];
let result = if reduced_line.starts_with("one") {
Some(1)
@@ -33,11 +37,10 @@ fn parse_line(line: &str) -> Vec<u32> {
};
result
}).collect()
})
.collect()
}
#[cfg(test)]
mod test {
use super::*;
@@ -54,4 +57,5 @@ zoneight234
fn part2_works() {
let result = part2(INPUT);
assert_eq!(result, "281".to_string());
}}
}
}