Make sure that day1/part1 is getting the correct solution again

Add input.txt for day1, add test for example case
This commit is contained in:
Evie Litherland-Smith 2023-12-29 08:36:59 +00:00
parent b5d25969a2
commit 5989e4f10f
3 changed files with 1028 additions and 33 deletions

1000
day1/src/input.txt Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,5 +1,6 @@
mod part1; mod part1;
fn main() { fn main() {
println!("Hello, world!"); println!("Part1: {}", part1::main());
println!("Part2: TODO");
} }

View file

@ -1,44 +1,29 @@
use regex::Regex; use regex::Regex;
use std::{fs::read_to_string, path::Path};
fn parse(file: &str, parse_words: bool) -> i32 { pub(crate) fn main() -> i32 {
read_to_string(Path::new(file)) parse(include_str!("input.txt"))
.unwrap() }
pub(crate) fn parse(input: &str) -> i32 {
input
.lines() .lines()
.map(|m| calibration_values(num_from_line(m, parse_words))) .map(|m| calibration_values(num_from_line(m)))
.sum() .sum()
} }
fn num_from_line(line: &str, parse_words: bool) -> Vec<i32> { pub(crate) fn num_from_line(line: &str) -> Vec<i32> {
let rstring = if parse_words { Regex::new(r"(\d){1}")
r"(\d|one|two|three|four|five|six|seven|eight|nine){1}"
} else {
r"(\d){1}"
};
Regex::new(rstring)
.unwrap() .unwrap()
.find_iter(line) .find_iter(line)
.map(|m| -> i32 { .map(|m| {
match m.as_str().parse::<i32>() { m.as_str()
Ok(val) => val, .parse::<i32>()
Err(_) => match m.as_str().to_lowercase().as_ref() { .expect("Expected i32 due to Regex match")
"one" => 1,
"two" => 2,
"three" => 3,
"four" => 4,
"five" => 5,
"six" => 6,
"seven" => 7,
"eight" => 8,
"nine" => 9,
_ => panic!("Shouldn't get here due to rstring {}", &rstring),
},
}
}) })
.collect() .collect()
} }
fn calibration_values(num_vec: Vec<i32>) -> i32 { pub(crate) fn calibration_values(num_vec: Vec<i32>) -> i32 {
([num_vec[0], num_vec[num_vec.len() - 1]]) ([num_vec[0], num_vec[num_vec.len() - 1]])
.iter() .iter()
.fold(String::new(), |a, b| a + &b.to_string()) .fold(String::new(), |a, b| a + &b.to_string())
@ -46,7 +31,16 @@ fn calibration_values(num_vec: Vec<i32>) -> i32 {
.unwrap() .unwrap()
} }
pub(crate) fn main() { #[cfg(test)]
println!("{:?}", parse("inputs/2023/day1_1.txt", false)); mod tests {
println!("{:?}", parse("inputs/2023/test1_2.txt", true)); use super::*;
#[test]
fn example() {
let input = "1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet";
assert_eq!(parse(input), 142);
}
} }