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:
parent
b5d25969a2
commit
5989e4f10f
1000
day1/src/input.txt
Normal file
1000
day1/src/input.txt
Normal file
File diff suppressed because it is too large
Load diff
|
@ -1,5 +1,6 @@
|
|||
mod part1;
|
||||
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
println!("Part1: {}", part1::main());
|
||||
println!("Part2: TODO");
|
||||
}
|
||||
|
|
|
@ -1,44 +1,29 @@
|
|||
use regex::Regex;
|
||||
use std::{fs::read_to_string, path::Path};
|
||||
|
||||
fn parse(file: &str, parse_words: bool) -> i32 {
|
||||
read_to_string(Path::new(file))
|
||||
.unwrap()
|
||||
pub(crate) fn main() -> i32 {
|
||||
parse(include_str!("input.txt"))
|
||||
}
|
||||
|
||||
pub(crate) fn parse(input: &str) -> i32 {
|
||||
input
|
||||
.lines()
|
||||
.map(|m| calibration_values(num_from_line(m, parse_words)))
|
||||
.map(|m| calibration_values(num_from_line(m)))
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn num_from_line(line: &str, parse_words: bool) -> Vec<i32> {
|
||||
let rstring = if parse_words {
|
||||
r"(\d|one|two|three|four|five|six|seven|eight|nine){1}"
|
||||
} else {
|
||||
r"(\d){1}"
|
||||
};
|
||||
Regex::new(rstring)
|
||||
pub(crate) fn num_from_line(line: &str) -> Vec<i32> {
|
||||
Regex::new(r"(\d){1}")
|
||||
.unwrap()
|
||||
.find_iter(line)
|
||||
.map(|m| -> i32 {
|
||||
match m.as_str().parse::<i32>() {
|
||||
Ok(val) => val,
|
||||
Err(_) => match m.as_str().to_lowercase().as_ref() {
|
||||
"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),
|
||||
},
|
||||
}
|
||||
.map(|m| {
|
||||
m.as_str()
|
||||
.parse::<i32>()
|
||||
.expect("Expected i32 due to Regex match")
|
||||
})
|
||||
.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]])
|
||||
.iter()
|
||||
.fold(String::new(), |a, b| a + &b.to_string())
|
||||
|
@ -46,7 +31,16 @@ fn calibration_values(num_vec: Vec<i32>) -> i32 {
|
|||
.unwrap()
|
||||
}
|
||||
|
||||
pub(crate) fn main() {
|
||||
println!("{:?}", parse("inputs/2023/day1_1.txt", false));
|
||||
println!("{:?}", parse("inputs/2023/test1_2.txt", true));
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn example() {
|
||||
let input = "1abc2
|
||||
pqr3stu8vwx
|
||||
a1b2c3d4e5f
|
||||
treb7uchet";
|
||||
assert_eq!(parse(input), 142);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue