Merge branch 'fix-brakets' into bracket

This commit is contained in:
Alexandre Stein 2022-12-09 15:33:18 +01:00
commit 26601e548e
1 changed files with 20 additions and 13 deletions

View File

@ -140,7 +140,7 @@ fn parse(pattern: String) -> (Vec<Symbol>, Vec<f64>) {
// Send it to the parse function
let (tmp_symbols, tmp_numbers) = parse(new_pattern);
// Do the calculation
let tmp_result = calculation(&tmp_symbols, &tmp_numbers);
let tmp_result = calculation(tmp_symbols, tmp_numbers);
// Add the calculated value to the list of numbers
numbers.push(tmp_result);
// Change the position in the list
@ -211,16 +211,17 @@ fn parse(pattern: String) -> (Vec<Symbol>, Vec<f64>) {
}
// Run the calculation based on the 2 different lists of symbols and numbers
fn calculation(symbols: &Vec<Symbol>, numbers: &Vec<f64>) -> f64 {
fn calculation(symbols: Vec<Symbol>, numbers: Vec<f64>) -> f64 {
let mut counter = 0;
let mut n1 = *numbers.get(0).expect("expect at least the first value");
// Iterate the list of symbols
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");
@ -248,7 +249,7 @@ fn calculation(symbols: &Vec<Symbol>, numbers: &Vec<f64>) -> f64 {
.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() {
@ -265,12 +266,14 @@ fn calculation(symbols: &Vec<Symbol>, numbers: &Vec<f64>) -> f64 {
// Change the position in the list, save the new value as n1 and stop the priority loop
} else {
counter = counter_2;
n1 = nn1;
n2 = nn1;
break;
}
n2 = nn1;
// Increment the position in the list
counter_2 += 1;
counter = counter_2;
}
}
}
@ -319,7 +322,8 @@ fn main() {
process::exit(2);
}
let res = calculation(&symbols, &numbers);
let res = calculation(symbols, numbers);
println!("{res}");
}
@ -330,23 +334,26 @@ mod tests {
#[test]
fn basics() {
let (s, n) = parse("2+2".to_string());
assert_eq!(calculation(&s, &n), 4.0);
assert_eq!(calculation(s, n), 4.0);
let (s, n) = parse("4-9".to_string());
assert_eq!(calculation(&s, &n), -5.0);
assert_eq!(calculation(s, n), -5.0);
let (s, n) = parse("7*3".to_string());
assert_eq!(calculation(&s, &n), 21.0);
assert_eq!(calculation(s, n), 21.0);
let (s, n) = parse("9/3".to_string());
assert_eq!(calculation(&s, &n), 3.0);
assert_eq!(calculation(s, n), 3.0);
let (s, n) = parse("15*20".to_string());
assert_ne!(calculation(&s, &n), 0.0);
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);
assert_eq!(calculation(s, n), 10.0);
let (s, n) = parse("30/4-9".to_string());
assert_eq!(calculation(&s, &n), -1.5);
assert_eq!(calculation(s, n), -1.5);
}
}