math_test/equation/onevariable/
mod.rs

1use std::fmt;
2
3use crate::{
4    number,
5    question::Question,
6    question_type::{EquationType, QuestionType},
7};
8
9use super::Equation;
10
11#[derive(Debug)]
12pub struct OneVariable {
13    a: i32,
14    x: i32,
15    b: i32,
16    result: i32,
17}
18impl fmt::Display for OneVariable {
19    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20        if self.b < 0 {
21            write!(f, "{}x{} = {}", self.a, self.b, self.result)
22        } else {
23            write!(f, "{}x+{} = {}", self.a, self.b, self.result)
24        }
25    }
26}
27
28impl Equation for OneVariable {}
29
30impl Question for OneVariable {
31    type Output = i32;
32
33    fn new(equation: QuestionType, max: i32) -> Self {
34        if let QuestionType::Equation(EquationType::OneVariable) = equation {
35            //ax+b=result
36            let x: i32 = <Self as Equation>::choose_variable(max);
37            let a: i32 = <Self as Equation>::choose_variable(max);
38            let b: i32 = <Self as Equation>::choose_variable(max);
39
40            let result = OneVariable::calculate(&Self { a, b, result: 0, x });
41            Self { a, x, b, result }
42        } else {
43            panic!("Unexpected Behaviour");
44        }
45    }
46
47    fn get_correct_answer(&self) -> i32 {
48        self.x
49    }
50
51    fn calculate(&self) -> i32 {
52        let ax = (self.a * self.x) as i32;
53        let result: i32 = (ax + self.b as i32) as i32;
54        return result;
55    }
56
57    fn post_to_cmd(&self) -> bool {
58        let correct_answer = self.get_correct_answer();
59        self.print();
60
61        let answer = OneVariable::read_answer_from_cmd();
62        OneVariable::verify_answer(correct_answer, answer)
63    }
64
65    fn read_answer_from_cmd() -> i32 {
66        println!("Guess x:");
67        number::read_number(-1000000, 1000000)
68    }
69
70    fn correct_answer_to_string(&self) -> String {
71        format!("x = {}", self.x)
72    }
73}
74
75#[cfg(test)]
76mod tests;