Last active
April 30, 2022 16:09
-
-
Save belkarx/0527afb6870d82317ceda26ac7f2f484 to your computer and use it in GitHub Desktop.
symb_diff.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io::{stdin,stdout,Write}; | |
use regex::Regex; | |
/* Polynomial: involves only the operations | |
* of addition, subtraction, multiplication, | |
* and non-negative integer exponentiation | |
* of variables | |
*/ | |
fn main() { | |
//get user input | |
let mut s = String::new(); | |
print!("Equation: "); | |
let _=stdout().flush(); | |
stdin().read_line(&mut s).expect("Did not enter a correct string"); | |
//validate input | |
let re = Regex::new(r"^(\d?[a-z]\^\d(\+|\-)?|[a-z](\+|\-)?|\d(\+|\-)?)+\r?\n$").unwrap(); | |
assert!(re.is_match(&s)); | |
let mut tmp: u32 = 0; //used for storing intermediate values in chars -> integer | |
let mut prev: u32 = 0; //used to store the multiplicand, if applicable | |
let mut x_flag = false; //checking if x has been encountered in the block | |
let mut eq = String::new(); | |
for c in s.chars() { | |
match c { | |
'0'..='9' => { | |
tmp = tmp * 10 + (c as u8 - b'0') as u32; //char to integer | |
}, | |
'^' => { | |
//^ -> will encounter a second digit (the exponent) | |
prev = tmp; | |
tmp = 0 | |
}, | |
'x' => x_flag = true, | |
'-' | '+' | '\n' => { | |
if x_flag { | |
if prev == 0 { //no exponent, as prev has not been assigned to tmp upon '^' | |
eq.push_str(&format!(" {} {}", tmp, c)); //ie 8x+ -> 8 + | |
} | |
else { | |
if tmp == 2 { | |
eq.push_str(&format!(" {}x {}", prev*tmp, c)); //3x^2 -> 6x [as opposed to 6x^1] | |
} else { | |
eq.push_str(&format!(" {}x^{} {}", prev*tmp, tmp-1, c)); | |
} | |
} | |
} | |
tmp = 0; | |
prev = 0; | |
x_flag = false; | |
}, | |
_ => () | |
} | |
} | |
println!("d/dx = {}", eq.trim()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cargo.toml