reuler/
lib.rs

1//! `reuler` provide Rust implementation for the
2//! [Project Euler](https://projecteuler.net/).
3//!
4//! ## Example of library usage
5//! You can call the `solve()` function to run any of the implemented solution.
6//!
7//! ```rust
8//! use reuler;
9//!
10//! let res = reuler::solve(1).unwrap();
11//! println!("Solution : {res}");
12//! ```
13//!
14//! ## Example of commandline usage
15//! You can also call the command line `reuler` directly to get the result.
16//!
17//! ```console
18//! reuler 1
19//! ```
20
21pub mod problems;
22pub mod utils;
23
24/// Solve the given problem and return the solution as a string.
25///
26/// # Errors
27/// If the given problem ID is invalid or doesn't have an implementation yet,
28/// an error is returned.
29pub fn solve(problem_id: isize) -> Result<String, String> {
30    if problem_id < 1 {
31        return Err(format!("The provided problem ID is not valid (0 or negative number : `{problem_id}`). Please provide a valid ID."));
32    }
33
34    match problem_id {
35        1 => return Ok(problems::prob_1::solve()),
36        2 => return Ok(problems::prob_2::solve()),
37        _ => return Err(format!("The solution for the problem #{problem_id} is not yet implemented. Consider contributing !")),
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn test_solve_problem_1() {
47        assert_eq!(solve(1).unwrap(), "233168");
48    }
49
50    #[test]
51    fn test_invalid_id() {
52        match solve(-1) {
53            Ok(_val) => assert!(
54                false,
55                "No error raised, even though the given ID was invalid."
56            ),
57            Err(e) => assert!(e.contains("not valid"), "Wrong error message"),
58        }
59    }
60
61    #[test]
62    fn test_not_implemented() {
63        match solve(9999999) {
64            Ok(_val) => assert!(
65                false,
66                "No error raised, even though the given ID was invalid."
67            ),
68            Err(e) => assert!(e.contains("not yet implemented"), "Wrong error message"),
69        }
70    }
71}