Wrote program for Day 10

https://en.wikipedia.org/wiki/Catalan_number
This commit is contained in:
Mariano Riefolo 2024-08-04 16:37:26 +02:00
parent 7c5fdc5242
commit b3f9c09f44
4 changed files with 53 additions and 0 deletions

View File

@ -0,0 +1,6 @@
[package]
name = "day10"
version = "0.1.0"
edition = "2021"
[dependencies]

View File

@ -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
}

View File

@ -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)
);
}

View File

@ -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);
}
}