Day 7 parse input
This commit is contained in:
9
day_07/small_input.txt
Normal file
9
day_07/small_input.txt
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
190: 10 19
|
||||||
|
3267: 81 40 27
|
||||||
|
83: 17 5
|
||||||
|
156: 15 6
|
||||||
|
7290: 6 8 6 15
|
||||||
|
161011: 16 10 13
|
||||||
|
192: 17 8 14
|
||||||
|
21037: 9 7 18 13
|
||||||
|
292: 11 6 16 20
|
||||||
@@ -1,3 +1,77 @@
|
|||||||
fn main() {
|
// https://adventofcode.com/2024/day/7
|
||||||
println!("Hello, world!");
|
//
|
||||||
|
// Run command: cargo run ./input.txt
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
env,
|
||||||
|
error::Error,
|
||||||
|
fs::File,
|
||||||
|
io::{BufReader, prelude::*},
|
||||||
|
path::Component,
|
||||||
|
sync::RwLockWriteGuard,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
enum Ops {
|
||||||
|
Multiply,
|
||||||
|
Add,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Equation {
|
||||||
|
answer: i32,
|
||||||
|
components: Vec<i32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Equation {
|
||||||
|
fn new(equation_str: &str) -> Result<Equation, String> {
|
||||||
|
let split_equation: Vec<_> = equation_str.split(":").collect();
|
||||||
|
if split_equation.len() != 2 {
|
||||||
|
return Err(format!("Invalid equation string: {}", equation_str));
|
||||||
|
}
|
||||||
|
let answer = match split_equation[0].parse() {
|
||||||
|
Ok(a) => a,
|
||||||
|
Err(_) => {
|
||||||
|
return Err(format!(
|
||||||
|
"Error parsing answer {} in equation: {}",
|
||||||
|
split_equation[0], equation_str
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let components = split_equation[1]
|
||||||
|
.split_whitespace()
|
||||||
|
.map(|c| match c.parse::<i32>() {
|
||||||
|
Ok(a) => Ok(a),
|
||||||
|
Err(_) => Err(format!(
|
||||||
|
"Error parsing component {} in equation: {}",
|
||||||
|
c, equation_str
|
||||||
|
)),
|
||||||
|
})
|
||||||
|
.collect::<Result<Vec<i32>, String>>()?;
|
||||||
|
Ok(Equation { answer, components })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
// Handle command input
|
||||||
|
let args: Vec<String> = env::args().collect();
|
||||||
|
if args.len() != 2 {
|
||||||
|
panic!(
|
||||||
|
"{} must be run with a single argument of file name!",
|
||||||
|
&args[0]
|
||||||
|
)
|
||||||
|
}
|
||||||
|
let input_file = &args[1];
|
||||||
|
|
||||||
|
let file = File::open(input_file)?;
|
||||||
|
let buffer = BufReader::new(file);
|
||||||
|
|
||||||
|
let mut equations = Vec::new();
|
||||||
|
for line in buffer.lines() {
|
||||||
|
let line = line?;
|
||||||
|
equations.push(Equation::new(&line)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("{:?}", equations);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user