bracket - support for parentheses calculation #3
|
@ -71,14 +71,15 @@ fn parse(pattern: String) -> (Vec<Symbol>, Vec<f32>) {
|
|||
(symbols, numbers)
|
||||
}
|
||||
|
||||
fn calcul(symbols: Vec<Symbol>, numbers: Vec<f32>) -> f32 {
|
||||
fn calculation(symbols: Vec<Symbol>, numbers: Vec<f32>) -> 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<Symbol>, numbers: Vec<f32>) -> 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<Symbol>, numbers: Vec<f32>) -> 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);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue