From 908726e3c6921a938373641a370c1769ea645cff Mon Sep 17 00:00:00 2001 From: Alexandre Stein Date: Fri, 9 Dec 2022 15:18:30 +0100 Subject: [PATCH] Fixes priority issue --- rust-calc/src/main.rs | 44 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/rust-calc/src/main.rs b/rust-calc/src/main.rs index fd0ab86..ec3be19 100644 --- a/rust-calc/src/main.rs +++ b/rust-calc/src/main.rs @@ -71,14 +71,15 @@ fn parse(pattern: String) -> (Vec, Vec) { (symbols, numbers) } -fn calcul(symbols: Vec, numbers: Vec) -> f32 { +fn calculation(symbols: Vec, numbers: Vec) -> f32 { let mut counter = 0; let mut n1 = *numbers.get(0).expect("expect at least the first value"); + while counter < symbols.len() { let s = symbols .get(counter) .expect("expect at least a symbol value"); - let n2 = *numbers + let mut n2 = *numbers .get(counter + 1) .expect("expect at least a second value"); @@ -103,10 +104,11 @@ fn calcul(symbols: Vec, numbers: Vec) -> f32 { .expect("during the priority, we expect at least the first value"); while counter_2 < symbols.len() { let nn2 = *numbers - .get(counter_2) + .get(counter_2 + 1) .expect("during the priority, we expect at least the second value"); if ss.priority() { + println!("next is prio: {:?}\n{nn1} and {nn2}", ss); match ss { Symbol::Multiply => { nn1.mul_assign(nn2); @@ -118,11 +120,13 @@ fn calcul(symbols: Vec, numbers: Vec) -> f32 { } } else { counter = counter_2; - n1 = nn1; + n2 = nn1; break; } + n2 = nn1; counter_2 += 1; + counter = counter_2; } } } @@ -165,6 +169,36 @@ fn main() { process::exit(2); } - let res = calcul(symbols, numbers); + let res = calculation(symbols, numbers); println!("{res}"); } + +#[cfg(test)] +mod tests { + use crate::{calculation, parse}; + + #[test] + fn basics() { + let (s, n) = parse("2+2".to_string()); + assert_eq!(calculation(s, n), 4.0); + let (s, n) = parse("4-9".to_string()); + assert_eq!(calculation(s, n), -5.0); + let (s, n) = parse("7*3".to_string()); + assert_eq!(calculation(s, n), 21.0); + let (s, n) = parse("9/3".to_string()); + assert_eq!(calculation(s, n), 3.0); + + let (s, n) = parse("15*20".to_string()); + assert_ne!(calculation(s, n), 0.0); + } + + #[test] + fn signs_2() { + let (s, n) = parse("2*4+4".to_string()); + assert_eq!(calculation(s, n), 12.0); + let (s, n) = parse("2+2*4".to_string()); + assert_eq!(calculation(s, n), 10.0); + let (s, n) = parse("30/4-9".to_string()); + assert_eq!(calculation(s, n), -1.5); + } +}