Add parser for don't

This commit is contained in:
Felix Suchert 2024-12-15 23:33:21 +01:00
parent 481270abaf
commit 8e9c34571d
Signed by: feliix42
GPG key ID: 24363525EA0E8A99

View file

@ -10,6 +10,12 @@ enum ParserState {
ExpectLParen,
ReadNum1,
ReadNum2,
ExpectO,
ExpectNorLParen,
ExpectApostrophe,
ExpectT,
ExpectDontLParen,
ExpectRParen(bool),
}
pub fn run(mut args: env::Args) -> std::io::Result<()> {
@ -20,10 +26,13 @@ pub fn run(mut args: env::Args) -> std::io::Result<()> {
let f = File::open(filename)?;
let reader = BufReader::new(f);
let mut sum = 0;
let mut sum_a = 0;
let mut sum_b = 0;
let mut num_buf = String::with_capacity(3);
let mut a = 0;
let mut mul_enabled = true;
for line in reader.lines() {
let l = line.unwrap();
if l.is_empty() {
@ -37,6 +46,8 @@ pub fn run(mut args: env::Args) -> std::io::Result<()> {
ParserState::Search => {
if c == 'm' {
ParserState::ExpectU
} else if c == 'd' {
ParserState::ExpectO
} else {
ParserState::Search
}
@ -86,7 +97,10 @@ pub fn run(mut args: env::Args) -> std::io::Result<()> {
if c == ')' && !num_buf.is_empty() {
// parse the number, assign to b, set to ParserState::ReadNum2
let b = u32::from_str(&num_buf).unwrap();
sum += a * b;
sum_a += a * b;
if mul_enabled {
sum_b += a * b;
}
}
// teardown in any case
@ -95,15 +109,58 @@ pub fn run(mut args: env::Args) -> std::io::Result<()> {
ParserState::Search
}
}
ParserState::ExpectO => {
if c == 'o' {
ParserState::ExpectNorLParen
} else {
ParserState::Search
}
}
ParserState::ExpectNorLParen => {
if c == '(' {
ParserState::ExpectRParen(true)
} else if c == 'n' {
ParserState::ExpectApostrophe
} else {
ParserState::Search
}
}
ParserState::ExpectApostrophe => {
if c == '\'' {
ParserState::ExpectT
} else {
ParserState::Search
}
}
ParserState::ExpectT => {
if c == 't' {
ParserState::ExpectDontLParen
} else {
ParserState::Search
}
}
ParserState::ExpectDontLParen => {
if c == '(' {
ParserState::ExpectRParen(false)
} else {
ParserState::Search
}
}
ParserState::ExpectRParen(enable) => {
if c == ')' {
mul_enabled = enable;
}
ParserState::Search
}
};
}
}
// Task 1
println!("Sum of all multiplications: {sum}");
println!("Sum of all multiplications: {sum_a}");
// Task 2
// TBD
println!("Sum of all multiplications (do/don't): {sum_b}");
Ok(())
}