implement Day01

This commit is contained in:
Nico Fricke 2023-12-01 09:38:23 +01:00
parent b7187433ab
commit e65c61e2b2
3 changed files with 1066 additions and 2 deletions

7
Day01/example_input.txt Normal file
View File

@ -0,0 +1,7 @@
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen

1000
Day01/input.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,60 @@
fn main() {
println!("Hello, world!");
use std::collections::HashMap;
use std::fs::File;
use std::io;
use std::io::{BufRead, BufReader};
fn main() -> io::Result<()> {
let file = File::open("input.txt")?;
let reader = BufReader::new(file);
let mut result = 0;
for line in reader.lines() {
let numbers = get_digits(line?);
result = result + (numbers.first().unwrap() * 10 + numbers.last().unwrap());
}
println!("First: {}", result);
let file = File::open("input.txt")?;
let reader = BufReader::new(file);
let mut result = 0;
for line in reader.lines() {
let replaced_line = replace_numbers(line?);
let numbers = get_digits(replaced_line);
result = result + (numbers.first().unwrap() * 10 + numbers.last().unwrap());
}
println!("Second: {}", result);
Ok(())
}
fn replace_numbers(input: String) -> String {
let map = HashMap::from([
("one", "1"), ("two", "2"), ("three", "3"), ("four", "4"), ("five", "5"), ("six", "6"), ("seven", "7"), ("eight", "8"), ("nine", "9")
]);
let mut result = input.clone();
for (from, to) in map {
let mut replacement = from.to_owned();
replacement.push_str(to);
replacement.push_str(from);
result = result.replace(from, &replacement);
}
result
}
fn get_digits(line: String) -> Vec<u32> {
line.chars().filter_map(|a| a.to_digit(10)).collect()
}
#[cfg(test)]
mod tests {
use crate::replace_numbers;
#[test]
fn check_replace_numbers() {
let result = replace_numbers("twone".to_string());
assert_eq!(result, "two2twone1one");
}
}