ctb_formats_math/
calculator_classic.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Mathematical utilities translated faithfully from the legacy calculator
21//! application suite (`old/calculator`), including Calculator 4.0, assistance/
22//! error solvers, the `6r2` unique random number generator, and the `R.P.S.`
23//! sidecar game.
24
25#[allow(
26    unused_imports,
27    clippy::wildcard_imports,
28    reason = "Standard workspace module prelude"
29)]
30use crate::utilities::*;
31
32pub use crate::constant::{CONST_E, CONST_PI};
33
34/// Result of a square root evaluation, representing real or imaginary output.
35#[derive(Debug, Clone, PartialEq)]
36pub enum SquareRootResult {
37    /// Real square root result for non-negative numbers.
38    Real(f64),
39    /// Imaginary square root result for negative numbers ($x \cdot i$).
40    Imaginary(f64),
41}
42
43/// Outcome of a Rock-Paper-Scissors game round.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum RpsOutcome {
46    /// User wins the round.
47    Win,
48    /// User loses the round.
49    Loss,
50    /// Round is a draw.
51    Draw,
52}
53
54/// Choice options in Rock-Paper-Scissors.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum RpsChoice {
57    /// Rock choice.
58    Rock = 1,
59    /// Paper choice.
60    Paper = 2,
61    /// Scissors choice.
62    Scissors = 3,
63}
64
65/// Structure holding the result of a prime number and factor verification test.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct PrimeVerificationResult {
68    /// Indicates whether the number is prime.
69    pub is_prime: bool,
70    /// Smallest non-trivial factor discovered if the number is composite.
71    pub factor_a: Option<i64>,
72    /// Complementary factor discovered if the number is composite.
73    pub factor_b: Option<i64>,
74}
75
76/// Performs addition of two floating-point numbers.
77pub fn add(a: f64, b: f64) -> f64 {
78    a + b
79}
80
81/// Performs subtraction of two floating-point numbers.
82pub fn subtract(a: f64, b: f64) -> f64 {
83    a - b
84}
85
86/// Performs multiplication of two floating-point numbers.
87pub fn multiply(a: f64, b: f64) -> f64 {
88    a * b
89}
90
91/// Performs floating-point division of two numbers.
92/// Returns an error if the divisor is zero.
93pub fn divide(a: f64, b: f64) -> Result<f64> {
94    if b == 0.0 {
95        bail!("Division by zero");
96    }
97    Ok(a / b)
98}
99
100/// Performs integer division (quotient without remainder).
101/// Returns an error if dividing by zero or overflowing.
102pub fn integer_divide(a: i64, b: i64) -> Result<i64> {
103    let Some(res) = a.checked_div(b) else {
104        bail!("Integer division by zero or overflow");
105    };
106    Ok(res)
107}
108
109/// Computes integer remainder (modulo).
110/// Returns an error if dividing by zero or overflowing.
111pub fn modulo(a: i64, b: i64) -> Result<i64> {
112    let Some(res) = a.checked_rem(b) else {
113        bail!("Modulo by zero or overflow");
114    };
115    Ok(res)
116}
117
118/// Computes both quotient and remainder for integer division.
119/// Faithfully models legacy Visual Basic modulo formatting logic.
120pub fn quotient_and_remainder(a: i64, b: i64) -> Result<(i64, i64)> {
121    let q = integer_divide(a, b)?;
122    let r = modulo(a, b)?;
123    Ok((q, r))
124}
125
126/// Formats modulo quotient and remainder into legacy output string (`"Q r R"`).
127/// FIXME: In original version, if n2 is 0 it looks like it returns "{ }" as output string. I guess that would need to be implemented in the UI code.
128pub fn format_modulo_result(quotient: i64, remainder: i64) -> String {
129    format!("{quotient} r{remainder}")
130}
131
132/// Performs exponentiation ($base^{exp}$).
133pub fn power(base: f64, exp: f64) -> f64 {
134    base.powf(exp)
135}
136
137/// Evaluates a basic arithmetic operation given an operator string.
138pub fn evaluate_basic_op(op: &str, a: f64, b: f64) -> Result<f64> {
139    match op {
140        "+" => Ok(add(a, b)),
141        "-" => Ok(subtract(a, b)),
142        "*" | "x" => Ok(multiply(a, b)),
143        "/" => divide(a, b),
144        "^" => Ok(power(a, b)),
145        "\\" => {
146            let ai = math::approx_float::f64_to_i64_approx(a)?;
147            let bi = math::approx_float::f64_to_i64_approx(b)?;
148            let res = integer_divide(ai, bi)?;
149            let res_i32 = i32::try_from(res).context(
150                "Integer division output out of i32 range for float conversion",
151            )?;
152            Ok(f64::from(res_i32))
153        }
154        "Mod" => {
155            let ai = math::approx_float::f64_to_i64_approx(a)?;
156            let bi = math::approx_float::f64_to_i64_approx(b)?;
157            let res = modulo(ai, bi)?;
158            let res_i32 = i32::try_from(res).context(
159                "Modulo output out of i32 range for float conversion",
160            )?;
161            Ok(f64::from(res_i32))
162        }
163        _ => bail!("Unsupported operator: {op}"),
164    }
165}
166
167/// Calculates the area of a circle given its radius ($\pi \cdot r^2$).
168pub fn circle_area(radius: f64) -> f64 {
169    CONST_PI * radius * radius
170}
171
172/// Calculates the area of a rectangle given base and height ($base \cdot height$).
173pub fn rectangle_area(base: f64, height: f64) -> f64 {
174    base * height
175}
176
177/// Calculates the perimeter of a rectangle ($2 \cdot (base + height)$).
178pub fn rectangle_perimeter(base: f64, height: f64) -> f64 {
179    2.0 * (base + height)
180}
181
182/// Computes the square root of a number. Supports negative inputs by returning
183/// an imaginary component representation.
184pub fn square_root(x: f64) -> SquareRootResult {
185    if x >= 0.0 {
186        SquareRootResult::Real(x.sqrt())
187    } else {
188        SquareRootResult::Imaginary((-x).sqrt())
189    }
190}
191
192/// Formats square root result into a human-readable display string.
193pub fn format_square_root(x: f64) -> String {
194    match square_root(x) {
195        SquareRootResult::Real(val) => val.to_string(),
196        SquareRootResult::Imaginary(val) => format!("{val}i"),
197    }
198}
199
200/// Converts temperature from Fahrenheit to Celsius.
201pub fn fahrenheit_to_celsius(fahrenheit: f64) -> f64 {
202    (fahrenheit - 32.0) * 5.0 / 9.0
203}
204
205/// Converts temperature from Celsius to Fahrenheit.
206pub fn celsius_to_fahrenheit(celsius: f64) -> f64 {
207    (celsius * 9.0 / 5.0) + 32.0
208}
209
210/// Checks prime status and calculates factors, matching legacy calculator interface.
211pub fn verify_prime_and_factors(n: i64) -> PrimeVerificationResult {
212    if n <= 1 {
213        return PrimeVerificationResult {
214            is_prime: false,
215            factor_a: None,
216            factor_b: None,
217        };
218    }
219
220    if let Ok(u_val) = u64::try_from(n) {
221        if crate::primality::is_prime_u64(u_val) {
222            return PrimeVerificationResult {
223                is_prime: true,
224                factor_a: None,
225                factor_b: None,
226            };
227        }
228    }
229
230    let mut divisor: i64 = 2;
231    while divisor.saturating_mul(divisor) <= n {
232        if n.checked_rem(divisor) == Some(0) {
233            let Some(complement) = n.checked_div(divisor) else {
234                break;
235            };
236            return PrimeVerificationResult {
237                is_prime: false,
238                factor_a: Some(divisor),
239                factor_b: Some(complement),
240            };
241        }
242        divisor = divisor.saturating_add(1);
243    }
244
245    PrimeVerificationResult {
246        is_prime: true,
247        factor_a: None,
248        factor_b: None,
249    }
250}
251
252/// Computes a scaled random number value based on a base $[0.0, 1.0)$ input.
253pub fn scaled_random(raw_rand: f64, multiplier: f64) -> f64 {
254    raw_rand * multiplier
255}
256
257/// Generates a triplet of non-repeating random integers within $[min, max]$.
258/// Faithfully reproduces the loop validation in sidecar `6r2`.
259pub fn generate_unique_random_triplet<R: FnMut() -> i32>(
260    mut rand_func: R,
261    min: i32,
262    max: i32,
263) -> Result<[i32; 3]> {
264    if min >= max || (max.saturating_sub(min)) < 2 {
265        bail!("Range too small to generate 3 unique random integers");
266    }
267
268    let mut attempts: u32 = 0;
269    while attempts < 1000 {
270        attempts = attempts.saturating_add(1);
271        let a = rand_func();
272        let b = rand_func();
273        let c = rand_func();
274
275        if a >= min && a <= max && b >= min && b <= max && c >= min && c <= max
276        {
277            if a != b && b != c && a != c {
278                return Ok([a, b, c]);
279            }
280        }
281    }
282
283    bail!("Failed to generate unique random numbers within attempt limit");
284}
285
286/// Evaluates a Rock-Paper-Scissors turn outcome.
287pub fn play_rps(user: RpsChoice, computer: RpsChoice) -> RpsOutcome {
288    if user == computer {
289        return RpsOutcome::Draw;
290    }
291
292    match (user, computer) {
293        (RpsChoice::Rock, RpsChoice::Scissors)
294        | (RpsChoice::Paper, RpsChoice::Rock)
295        | (RpsChoice::Scissors, RpsChoice::Paper) => RpsOutcome::Win,
296        _ => RpsOutcome::Loss,
297    }
298}
299
300/// Converts integer code ($1 \dots 3$) to `RpsChoice`.
301pub fn rps_choice_from_int(val: i32) -> Result<RpsChoice> {
302    match val {
303        1 => Ok(RpsChoice::Rock),
304        2 => Ok(RpsChoice::Paper),
305        3 => Ok(RpsChoice::Scissors),
306        _ => bail!("Invalid RPS choice integer: {val}"),
307    }
308}
309
310/// Standard scale multipliers for random table generation.
311pub const RANDOM_SCALES: [f64; 8] =
312    [1.0, 5.0, 10.0, 50.0, 100.0, 500.0, 1000.0, 5000.0];
313
314/// Generates a table of 8 scaled random numbers from a given base raw random value ($0 \dots 1$).
315pub fn generate_scaled_random_table(raw: f64) -> [f64; 8] {
316    [
317        scaled_random(raw, 1.0),
318        scaled_random(raw, 5.0),
319        scaled_random(raw, 10.0),
320        scaled_random(raw, 50.0),
321        scaled_random(raw, 100.0),
322        scaled_random(raw, 500.0),
323        scaled_random(raw, 1000.0),
324        scaled_random(raw, 5000.0),
325    ]
326}
327
328/// Evaluates a math expression string with standard operator precedence.
329pub fn evaluate_expression(expr: &str) -> Result<f64> {
330    crate::parsing::evaluate_expression(expr)
331}
332
333#[cfg(test)]
334#[allow(
335    clippy::panic,
336    clippy::expect_used,
337    clippy::unwrap_used,
338    clippy::unwrap_in_result,
339    clippy::panic_in_result_fn,
340    clippy::indexing_slicing,
341    clippy::arithmetic_side_effects,
342    reason = "Standard repository test boilerplate"
343)]
344mod tests {
345    use super::*;
346
347    #[crate::ctb_test]
348    fn test_basic_arithmetic() {
349        assert_eq!(add(2.0, 3.0), 5.0);
350        assert_eq!(subtract(10.0, 4.0), 6.0);
351        assert_eq!(multiply(3.0, 7.0), 21.0);
352        assert_eq!(divide(10.0, 2.0).unwrap(), 5.0);
353        divide(10.0, 0.0).unwrap_err();
354        assert_eq!(power(2.0, 3.0), 8.0);
355    }
356
357    #[crate::ctb_test]
358    fn test_integer_divide_and_modulo() {
359        assert_eq!(integer_divide(7, 3).unwrap(), 2);
360        assert_eq!(modulo(7, 3).unwrap(), 1);
361        assert_eq!(quotient_and_remainder(7, 3).unwrap(), (2, 1));
362        assert_eq!(format_modulo_result(2, 1), "2 r1");
363        integer_divide(5, 0).unwrap_err();
364        modulo(5, 0).unwrap_err();
365    }
366
367    #[crate::ctb_test]
368    fn test_evaluate_basic_op() {
369        assert_eq!(evaluate_basic_op("+", 4.0, 5.0).unwrap(), 9.0);
370        assert_eq!(evaluate_basic_op("-", 9.0, 2.0).unwrap(), 7.0);
371        assert_eq!(evaluate_basic_op("*", 3.0, 4.0).unwrap(), 12.0);
372        assert_eq!(evaluate_basic_op("/", 12.0, 3.0).unwrap(), 4.0);
373        assert_eq!(evaluate_basic_op("^", 2.0, 4.0).unwrap(), 16.0);
374        assert_eq!(evaluate_basic_op("\\", 9.0, 2.0).unwrap(), 4.0);
375        assert_eq!(evaluate_basic_op("Mod", 9.0, 2.0).unwrap(), 1.0);
376        evaluate_basic_op("invalid", 1.0, 1.0).unwrap_err();
377    }
378
379    #[crate::ctb_test]
380    fn test_geometry() {
381        let area = circle_area(2.0);
382        assert!((area - (CONST_PI * 4.0)).abs() < 1e-6);
383        assert_eq!(rectangle_area(4.0, 5.0), 20.0);
384        assert_eq!(rectangle_perimeter(4.0, 5.0), 18.0);
385    }
386
387    #[crate::ctb_test]
388    fn test_square_root() {
389        assert_eq!(square_root(9.0), SquareRootResult::Real(3.0));
390        assert_eq!(square_root(-4.0), SquareRootResult::Imaginary(2.0));
391        assert_eq!(format_square_root(9.0), "3");
392        assert_eq!(format_square_root(-4.0), "2i");
393        assert_eq!(square_root(13.0), SquareRootResult::Real(13.0f64.sqrt()));
394    }
395
396    #[crate::ctb_test]
397    fn test_temperature() {
398        assert_eq!(fahrenheit_to_celsius(32.0), 0.0);
399        assert_eq!(fahrenheit_to_celsius(212.0), 100.0);
400        assert_eq!(celsius_to_fahrenheit(0.0), 32.0);
401        assert_eq!(celsius_to_fahrenheit(100.0), 212.0);
402    }
403
404    #[crate::ctb_test]
405    fn test_prime_verification() {
406        let res7 = verify_prime_and_factors(7);
407        assert!(res7.is_prime);
408        assert_eq!(res7.factor_a, None);
409
410        let res12 = verify_prime_and_factors(12);
411        assert!(!res12.is_prime);
412        assert_eq!(res12.factor_a, Some(2));
413        assert_eq!(res12.factor_b, Some(6));
414
415        assert!(!verify_prime_and_factors(1).is_prime);
416        assert!(!verify_prime_and_factors(0).is_prime);
417        assert!(!verify_prime_and_factors(-5).is_prime);
418    }
419
420    #[crate::ctb_test]
421    fn test_random_generators() {
422        assert_eq!(scaled_random(0.5, 10.0), 5.0);
423
424        let mut seq = vec![1, 2, 3].into_iter();
425        let res =
426            generate_unique_random_triplet(|| seq.next().unwrap_or(0), 0, 5)
427                .unwrap();
428        assert_eq!(res, [1, 2, 3]);
429
430        let mut fail_seq = vec![1, 1, 1].into_iter();
431        let fail_res = generate_unique_random_triplet(
432            || fail_seq.next().unwrap_or(1),
433            0,
434            5,
435        );
436        fail_res.unwrap_err();
437    }
438
439    #[crate::ctb_test]
440    fn test_rps() {
441        assert_eq!(
442            play_rps(RpsChoice::Rock, RpsChoice::Rock),
443            RpsOutcome::Draw
444        );
445        assert_eq!(
446            play_rps(RpsChoice::Rock, RpsChoice::Scissors),
447            RpsOutcome::Win
448        );
449        assert_eq!(
450            play_rps(RpsChoice::Rock, RpsChoice::Paper),
451            RpsOutcome::Loss
452        );
453
454        assert_eq!(rps_choice_from_int(1).unwrap(), RpsChoice::Rock);
455        assert_eq!(rps_choice_from_int(2).unwrap(), RpsChoice::Paper);
456        assert_eq!(rps_choice_from_int(3).unwrap(), RpsChoice::Scissors);
457        rps_choice_from_int(4).unwrap_err();
458    }
459
460    #[crate::ctb_test]
461    fn test_evaluate_expression() {
462        assert_eq!(evaluate_expression("2 + 3 * 4").unwrap(), 14.0);
463        assert_eq!(evaluate_expression("(2 + 3) * 4").unwrap(), 20.0);
464        assert_eq!(evaluate_expression("10 - 4 - 2").unwrap(), 4.0);
465        assert_eq!(evaluate_expression("2 ^ 3").unwrap(), 8.0);
466        assert_eq!(evaluate_expression("10 \\ 3").unwrap(), 3.0);
467        assert_eq!(evaluate_expression("10 Mod 3").unwrap(), 1.0);
468        assert_eq!(evaluate_expression("-5 + 10").unwrap(), 5.0);
469        evaluate_expression("10 / 0").unwrap_err();
470        evaluate_expression("2 + (3 *").unwrap_err();
471    }
472
473    #[crate::ctb_test]
474    fn test_generate_scaled_random_table() {
475        let table = generate_scaled_random_table(0.1);
476        assert_eq!(table.len(), 8);
477        assert_eq!(table[0], 0.1);
478        assert_eq!(table[1], 0.5);
479        assert_eq!(table[2], 1.0);
480    }
481}