2023(1): My god, here is some WET code

This commit is contained in:
2023-12-02 23:12:20 +01:00
parent 1c17fcede7
commit 4d95eabd78

View File

@ -1,6 +1,7 @@
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
use std::collections::HashMap;
fn main() {
let mut sum = 0;
@ -9,30 +10,14 @@ fn main() {
if let Ok(lines) = read_lines("./input") {
for line in lines {
if let Ok(text) = line {
// TODO: Please us something like a collection instead of
// hardcoding every replacement.
let sanitext = text
.replace("one", "1")
.replace("two", "2")
.replace("three", "3")
.replace("four", "4")
.replace("five", "5")
.replace("six", "6")
.replace("seven", "7")
.replace("eight", "8")
.replace("nine", "9")
;
// DEBUG:
println!(
"{} => {} yields {} + {} = {}",
text,
sanitext,
first_digit(&sanitext),
last_digit(&sanitext),
first_digit(&sanitext) + last_digit(&sanitext)
);
sum = sum + first_digit(&sanitext);
mus = mus + last_digit(&sanitext);
//println!(
// "{} yields {:?} + {:?}",
// text,
// first_digit(&text),
// last_digit(&text),
//);
sum = sum + first_digit(&text).unwrap_or(0);
mus = mus + last_digit(&text).unwrap_or(0);
} else {
println!("Error on line \"{:?}\"", line);
}
@ -42,20 +27,50 @@ fn main() {
println!("{}", 10*sum + mus);
}
// TODO: Switch to Option(i32) to allow not having a digit in text <https://doc.rust-lang.org/std/option/>.
fn first_digit(text: &String) -> i32 {
for c in text.chars() {
if c.is_digit(10) {
return c.to_digit(10).unwrap() as i32;
const DIGITSTABLE: [(&str, u32); 18]= [
("1", 1), ("one", 1),
("2", 2), ("two", 2),
("3", 3), ("three", 3),
("4", 4), ("four", 4),
("5", 5), ("five", 5),
("6", 6), ("six", 6),
("7", 7), ("seven", 7),
("8", 8), ("eight", 8),
("9", 9), ("nine", 9),
];
fn first_digit(text: &String) -> Option<u32> {
let digits = HashMap::from(DIGITSTABLE);
let mut hit = false;
let mut first_digit: &u32 = &0;
let mut first_index: usize = 0;
for (needle, digit) in &digits {
let index = text.find(needle);
if index.is_some() && (!hit || index.unwrap() < first_index) {
hit = true;
first_digit = digit;
first_index = index.unwrap();
}
}
// TODO: What if there is no digit?
0
if hit { Some(*first_digit) } else { None }
}
fn last_digit(text: &String) -> i32 {
let txet = &mut text.chars().rev().collect();
first_digit(txet)
fn last_digit(text: &String) -> Option<u32> {
let digits = HashMap::from(DIGITSTABLE);
let mut hit = false;
let mut last_digit: &u32 = &0;
let mut last_index: usize = 0;
for (needle, digit) in &digits {
let index = text.rfind(needle);
if index.is_some() && (!hit || index.unwrap() > last_index) {
hit = true;
last_digit = digit;
last_index = index.unwrap();
}
}
if hit { Some(*last_digit) } else { None }
}
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>