Pagini recente » Cod sursa (job #3342617) | Cod sursa (job #3322512) | Cod sursa (job #3323636) | Cod sursa (job #3322517) | Cod sursa (job #3313251)
use std::error::Error;
use std::fs::File;
#[allow(unused_imports)]
use std::io::{BufRead, BufReader, Read, Write};
const FILE: &'static str = "strmatch";
fn apply(op: char, x: i32, y: i32) -> i32 {
match op {
'+' => x + y,
'-' => x - y,
'*' => x * y,
'/' => x / y,
_ => panic!(),
}
}
fn precedence(op: char) -> i32 {
match op {
'(' | ')' => 3,
'*' | '/' => 2,
'+' | '-' => 1,
_ => panic!(),
}
}
fn main() -> Result<(), Box<dyn Error>> {
let mut fin = BufReader::new(File::open(format!("{}.in", FILE)).unwrap());
let mut fout = File::create(format!("{}.out", FILE)).unwrap();
let mut input = String::new();
fin.read_line(&mut input)?;
let input: Vec<char> = format!("({})", input.trim()).chars().collect();
let l = input.len();
let mut operands: Vec<i32> = vec![];
let mut operators = vec![];
let mut i = 0;
while i < l {
if input[i].is_digit(10) {
let mut x = input[i].to_digit(10).unwrap();
while input[i + 1].is_digit(10) {
i += 1;
x = x * 10 + input[i].to_digit(10).unwrap();
}
operands.push(x as i32);
} else {
if input[i] == ')' {
while operators[operators.len() - 1] != '(' {
let y = operands.pop().unwrap();
let x = operands.pop().unwrap();
let op = operators.pop().unwrap();
let res = apply(op, x, y);
operands.push(res);
}
operators.pop();
} else if input[i] == '(' {
operators.push(input[i]);
} else {
let prec = precedence(input[i]);
while prec <= precedence(operators[operators.len() - 1]) {
if operators[operators.len() - 1] == '(' {
break;
}
let y = operands.pop().unwrap();
let x = operands.pop().unwrap();
let op = operators.pop().unwrap();
let res = apply(op, x, y);
operands.push(res);
}
operators.push(input[i]);
}
}
println!("i: {i:>2} | i[i]: {} | nr: {:?} | ops: {:?}", input[i], operands, operators);
i += 1;
}
write!(&mut fout, "{}", operands[0])?;
Ok(())
}