1#[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#[derive(Debug, Clone, PartialEq)]
36pub enum SquareRootResult {
37 Real(f64),
39 Imaginary(f64),
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum RpsOutcome {
46 Win,
48 Loss,
50 Draw,
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum RpsChoice {
57 Rock = 1,
59 Paper = 2,
61 Scissors = 3,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct PrimeVerificationResult {
68 pub is_prime: bool,
70 pub factor_a: Option<i64>,
72 pub factor_b: Option<i64>,
74}
75
76pub fn add(a: f64, b: f64) -> f64 {
78 a + b
79}
80
81pub fn subtract(a: f64, b: f64) -> f64 {
83 a - b
84}
85
86pub fn multiply(a: f64, b: f64) -> f64 {
88 a * b
89}
90
91pub 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
100pub 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
109pub 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
118pub 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
126pub fn format_modulo_result(quotient: i64, remainder: i64) -> String {
129 format!("{quotient} r{remainder}")
130}
131
132pub fn power(base: f64, exp: f64) -> f64 {
134 base.powf(exp)
135}
136
137pub 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
167pub fn circle_area(radius: f64) -> f64 {
169 CONST_PI * radius * radius
170}
171
172pub fn rectangle_area(base: f64, height: f64) -> f64 {
174 base * height
175}
176
177pub fn rectangle_perimeter(base: f64, height: f64) -> f64 {
179 2.0 * (base + height)
180}
181
182pub 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
192pub 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
200pub fn fahrenheit_to_celsius(fahrenheit: f64) -> f64 {
202 (fahrenheit - 32.0) * 5.0 / 9.0
203}
204
205pub fn celsius_to_fahrenheit(celsius: f64) -> f64 {
207 (celsius * 9.0 / 5.0) + 32.0
208}
209
210pub 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
252pub fn scaled_random(raw_rand: f64, multiplier: f64) -> f64 {
254 raw_rand * multiplier
255}
256
257pub 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
286pub 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
300pub 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
310pub const RANDOM_SCALES: [f64; 8] =
312 [1.0, 5.0, 10.0, 50.0, 100.0, 500.0, 1000.0, 5000.0];
313
314pub 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
328pub 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}