1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use nexsys_math::Variable;
use std::collections::HashMap;
use super::re::*;

/// Represents an equation and gives info about its known and unknown variables
#[derive(Clone)]
#[derive(Debug)]
#[derive(PartialEq)]
pub struct Equation {
    text: String,
    vars: Vec<String>,
    n: usize
}
impl Equation {
    /// Initializes a new `Equation` struct
    pub fn new(text: &str) -> Equation {
        let mut vars = legal_variable(text);

        vars.sort();

        let n = vars.len();

        Equation { text: text.to_string(), vars, n }
    }

    /// Returns the equation as an expression that evaluates to 0 when the system is solved.
    pub fn as_expr(&self) -> String {
        let terms = self.text.split("=").collect::<Vec<&str>>();
        format!("{} - ({})", terms[0], terms[1])
    }

    /// Returns the equation as a `&str`.
    pub fn as_text(&self) -> String {
        self.text.clone()
    }

    /// Returns a list of variables used in the equation
    pub fn vars(&self) -> Vec<String> {
        self.vars.clone()
    }

    /// Returns the number of unknown variables in the equation.
    pub fn n_unknowns(&self, ctx: &HashMap<String, Variable>) -> usize {
        self.n - self.vars.iter().filter(
            |&i| ctx.contains_key(i)
        ).collect::<Vec<&String>>().len()
    }

    /// Returns a `Vec` containing the variables that are unknowns in the equation.
    pub fn unknowns(&self, ctx: &HashMap<String, Variable>) -> Vec<String> {
        self.vars.iter().filter(
            |&i| !ctx.contains_key(i)
        ).map(
            |i| i.clone()
        ).collect::<Vec<String>>()
    }

}