diff --git a/Week-02/Day-10_Unique-Binary-Search-Trees/day10/Cargo.toml b/Week-02/Day-10_Unique-Binary-Search-Trees/day10/Cargo.toml new file mode 100644 index 0000000..3c916ef --- /dev/null +++ b/Week-02/Day-10_Unique-Binary-Search-Trees/day10/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "day10" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/Week-02/Day-10_Unique-Binary-Search-Trees/day10/src/lib.rs b/Week-02/Day-10_Unique-Binary-Search-Trees/day10/src/lib.rs new file mode 100644 index 0000000..4c3d0a9 --- /dev/null +++ b/Week-02/Day-10_Unique-Binary-Search-Trees/day10/src/lib.rs @@ -0,0 +1,9 @@ +pub fn catalan_number(n: u8) -> usize { + let mut result = 1f64; + + for k in 2..=n { + result *= (n as f64 + k as f64) / k as f64; + } + + result.round() as usize +} diff --git a/Week-02/Day-10_Unique-Binary-Search-Trees/day10/src/main.rs b/Week-02/Day-10_Unique-Binary-Search-Trees/day10/src/main.rs new file mode 100644 index 0000000..a27f306 --- /dev/null +++ b/Week-02/Day-10_Unique-Binary-Search-Trees/day10/src/main.rs @@ -0,0 +1,24 @@ +use std::io::{self, Write}; + +use day10::catalan_number; + +fn main() { + let mut buffer = String::new(); + + print!("Insert n: "); + io::stdout().flush().expect("Failed to flush stdout."); + + io::stdin() + .read_line(&mut buffer) + .expect("Failed to read from stdin."); + + let n: u8 = buffer + .trim() + .parse() + .expect("The input is not a positive integer"); + + println!( + "The number of structurally unique BST's that store values from 1 to n is {}", + catalan_number(n) + ); +} diff --git a/Week-02/Day-10_Unique-Binary-Search-Trees/day10/tests/example.rs b/Week-02/Day-10_Unique-Binary-Search-Trees/day10/tests/example.rs new file mode 100644 index 0000000..797470f --- /dev/null +++ b/Week-02/Day-10_Unique-Binary-Search-Trees/day10/tests/example.rs @@ -0,0 +1,14 @@ +use day10::catalan_number; + +#[test] +fn example() { + assert_eq!(catalan_number(3), 5); +} + +#[test] +fn examplu() { + let array = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786]; + for (i, a) in array.into_iter().enumerate() { + assert_eq!(catalan_number(i as u8), a); + } +}