Cod sursa(job #3313252)

Utilizator game_difficultyCalin Crangus game_difficulty Data 2 octombrie 2025 22:56:03
Problema Evaluarea unei expresii Scor 80
Compilator rs Status done
Runda Arhiva educationala Marime 2.43 kb
use std::error::Error;
use std::fs::File;
#[allow(unused_imports)]
use std::io::{BufRead, BufReader, Read, Write};

const FILE: &'static str = "evaluare";

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(())
}