day 1 (working but incorrect??)

This commit is contained in:
ari melody 2023-12-02 13:36:50 +00:00
parent f374eceb32
commit 8b177dfcce
Signed by: ari
GPG key ID: CF99829C92678188

View file

@ -2,24 +2,19 @@ fn main () {
let data: String = std::fs::read_to_string("input").unwrap(); let data: String = std::fs::read_to_string("input").unwrap();
let lines = data.lines(); let lines = data.lines();
let new_lines = lines let sum: u32 = lines.map(|line| { get_calibration_values(line) }).sum();
.map(|raw_line| replace_numbers(raw_line)) println!("the sum of all calibration values is {sum}!");
.fold(String::new(), |a, b| format!("{a}{b}\n"));
std::fs::write("new_lines", new_lines);
// let sum: u32 = lines.map(|line| { get_calibration_values(line) }).sum();
// println!("the sum of all calibration values is {sum}!");
} }
fn replace_numbers(raw_line: &str) -> String { fn replace_numbers<'a>(line: &str) -> String {
let numbers: [&str; 10] = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]; let numbers: [&str; 10] = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
let mut line: String = raw_line.to_string(); let mut processed: String = String::from(line);
loop { loop {
let mut clean = false; let mut clean = false;
for i in 0..numbers.len() { for i in 0..numbers.len() {
let old_line = line.clone(); let old_line = processed.clone();
line = line.replace(numbers[i], i.to_string().as_str()); processed = processed.replace(numbers[i], i.to_string().as_str());
if line.eq(&old_line) { if processed == old_line {
clean = true; clean = true;
} }
} }
@ -27,11 +22,11 @@ fn replace_numbers(raw_line: &str) -> String {
break; break;
} }
} }
line processed
} }
fn get_calibration_values(mut line: &str) -> u32 { fn get_calibration_values(raw_line: &str) -> u32 {
line = replace_numbers(line).clone().as_str(); let line: String = replace_numbers(raw_line);
let first: u32 = line.chars().find_map(|ch| { ch.to_digit(10) }).unwrap(); let first: u32 = line.chars().find_map(|ch| { ch.to_digit(10) }).unwrap();
let last: u32 = line.chars().rev().find_map(|ch| { ch.to_digit(10) }).unwrap(); let last: u32 = line.chars().rev().find_map(|ch| { ch.to_digit(10) }).unwrap();