Brackets are fuly operational

This commit is contained in:
Alexandre Stein 2022-11-13 17:51:35 +01:00
parent fc31bfc38f
commit 327917e29a
1 changed files with 70 additions and 13 deletions

View File

@ -3,7 +3,7 @@ use std::{
process,
};
#[derive(Debug)]
#[derive(Clone, Debug)]
enum Symbol {
Minus,
Plus,
@ -19,9 +19,6 @@ impl Symbol {
Symbol::Multiply => true,
Symbol::Divide => true,
Symbol::OpenBracket => true,
Symbol::CloseBracket => true,
_ => false,
}
}
@ -30,6 +27,20 @@ impl Symbol {
Symbol::OpenBracket => true,
Symbol::CloseBracket => true,
_ => false,
}
}
fn open_bracket(&self) -> bool {
match self {
Symbol::OpenBracket => true,
_ => false,
}
}
fn close_bracket(&self) -> bool {
match self {
Symbol::CloseBracket => true,
_ => false,
}
}
@ -46,12 +57,14 @@ impl TmpNum {
self.s.push(c);
}
fn get(&mut self) -> f64 {
println!("{}", self.s);
let n = self.s.parse::<f64>().ok().expect("number is malformed");
self.s = String::new();
n
}
fn len(&self) -> usize {
self.s.len()
}
}
fn parse(pattern: String) -> (Vec<Symbol>, Vec<f64>) {
@ -60,7 +73,9 @@ fn parse(pattern: String) -> (Vec<Symbol>, Vec<f64>) {
let mut number = TmpNum::new();
for c in pattern.chars() {
let mut i = 0;
while i < pattern.len() {
let c = pattern.chars().nth(i).expect("some char");
let s: Option<Symbol> = match c {
'-' => Some(Symbol::Minus),
'+' => Some(Symbol::Plus),
@ -75,25 +90,67 @@ fn parse(pattern: String) -> (Vec<Symbol>, Vec<f64>) {
match s {
Some(s) => {
if number.s.len() == 0 {
number.push(c);
if s.bracket() {
let mut nb_bracket = 1;
let mut i2 = i + 1;
while i2 < pattern.len() {
let c2 = pattern.chars().nth(i2).expect("some char");
let s2: Option<Symbol> = match c2 {
'(' => Some(Symbol::OpenBracket),
')' => Some(Symbol::CloseBracket),
_ => None,
};
match s2 {
Some(s2) => {
if s2.bracket() {
if s2.open_bracket() {
nb_bracket += 1;
} else if s2.close_bracket() {
nb_bracket -= 1;
if nb_bracket == 0 {
let new_pattern = pattern
.get(i..i2)
.expect("expect the sub string")
.to_string();
let (tmp_symbols, tmp_numbers) = parse(new_pattern);
let tmp_result =
calculation(&tmp_symbols, &tmp_numbers);
numbers.push(tmp_result);
i = i2;
}
}
}
}
None => {}
}
i2 += 1;
}
} else {
symbols.push(s);
numbers.push(number.get());
if number.s.len() == 0 {
number.push(c);
} else {
symbols.push(s);
numbers.push(number.get());
}
}
}
None => {
number.push(c);
}
}
i += 1;
}
numbers.push(number.get());
if number.len() != 0 {
numbers.push(number.get());
}
(symbols, numbers)
}
fn calcul(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");
while counter < symbols.len() {
@ -187,6 +244,6 @@ fn main() {
process::exit(2);
}
let res = calcul(symbols, numbers);
let res = calculation(&symbols, &numbers);
println!("{res}");
}