Created
December 3, 2023 22:03
-
-
Save oisin/07878916b303f5e2145a21c5d9af285b to your computer and use it in GitHub Desktop.
AOC 23 Day 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::env; | |
use std::fs::File; | |
use std::io::{self, BufRead}; | |
fn main() { | |
let args: Vec<String> = env::args().collect(); | |
if args.len() != 2 { | |
eprintln!("Usage: {} <filename>", args[0]); | |
std::process::exit(1); | |
} | |
let filename = &args[1]; | |
let file = match File::open(filename) { | |
Ok(file) => file, | |
Err(error) => { | |
eprintln!("Error opening file {}: {}", filename, error); | |
std::process::exit(1); | |
} | |
}; | |
let reader = io::BufReader::new(file); | |
let mut accumulator : u32 = 0; | |
for (line_number, line) in reader.lines().enumerate() { | |
match line { | |
Ok(line_content) => { | |
let numbers = part2( | |
line_number + 1, | |
line_content.clone() | |
); | |
if numbers.len() != 0 { | |
println!("Numbers: {:?} / {}", numbers, line_content); | |
accumulator += format!("{}{}",numbers[0], numbers[numbers.len()-1]).parse::<u32>().expect(format!("Line {} does not produce a number", line_number).as_str()); | |
} | |
() | |
} | |
Err(error) => { | |
eprintln!("Error reading line {}: {}", line_number + 1, error); | |
() | |
} | |
} | |
} | |
println!("Total = {}", accumulator); | |
} | |
fn part1(_line_number: usize, line_content: String) -> Vec<char> { | |
let chars: Vec<char> = line_content.chars().collect(); | |
let mut result: Vec<char> = Vec::new(); | |
for i in chars.iter() { | |
match i { | |
'1'..='9' => result.push(*i), | |
_ => () | |
} | |
} | |
return result; | |
} | |
fn part2(_line_number: usize, line_content: String) -> Vec<char> { | |
let chars: Vec<char> = line_content.chars().collect(); | |
let mut result: Vec<char> = Vec::new(); | |
for (pos, i) in chars.iter().enumerate() { | |
match i { | |
'1'..='9' => result.push(*i), | |
_ => { | |
if pos+4 < chars.len() { | |
match &line_content[pos..=pos + 4] { | |
"three" => result.push('3'), | |
"eight" => result.push('8'), | |
"seven" => result.push('7'), | |
_ => () | |
} | |
} | |
if pos+3 < chars.len() { | |
match &line_content[pos..=pos + 3] { | |
"four" => result.push('4'), | |
"five" => result.push('5'), | |
"nine" => result.push('9'), | |
_ => () | |
} | |
} | |
if pos+2 < chars.len() { | |
match &line_content[pos..=pos + 2] { | |
"one" => result.push('1'), | |
"two" => result.push('2'), | |
"six" => result.push('6'), | |
_ => () | |
} | |
} | |
} | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment