diff --git a/Cargo.lock b/Cargo.lock index 1b6c76c..2478cc5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -16,6 +16,10 @@ dependencies = [ "geometry", ] +[[package]] +name = "challenge-3" +version = "0.1.0" + [[package]] name = "geometry" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 7607500..078c9aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,4 +8,5 @@ members = [ # Challenge "challenges/december-2024/c1", "challenges/december-2024/c2", + "challenges/december-2024/c3", ] diff --git a/challenges/december-2024/c3/Cargo.toml b/challenges/december-2024/c3/Cargo.toml new file mode 100644 index 0000000..95fab2d --- /dev/null +++ b/challenges/december-2024/c3/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "challenge-3" +version = "0.1.0" +edition = "2021" + + + diff --git a/challenges/december-2024/c3/src/main.rs b/challenges/december-2024/c3/src/main.rs new file mode 100644 index 0000000..7de3964 --- /dev/null +++ b/challenges/december-2024/c3/src/main.rs @@ -0,0 +1,48 @@ +use std::io::{self, Write}; + +// Sudan function is quite simple, here's the basics:the basics: +// When n = 0, `F(n, x, y) = x + y` +// When y = 0, `F(n, x, y) = x` +// Otherwise, `F(n, x, y) = F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y)` +fn sudan(n: i64, x: i64, y: i64) -> i64 { + if n == 0 { + x + y + } else if y == 0 { + x + } else { + sudan(n - 1, sudan(n, x, y - 1), sudan(n, x, y - 1) + y) + } +} + +fn get_input(prompt: &str) -> Result { + print!("{}", prompt); + io::stdout().flush().expect("Failed to flush stdout"); + + let mut input = String::new(); + io::stdin() + .read_line(&mut input) + .map_err(|_| "Failed to read line".to_string())?; + + input + .trim() + .parse::() + .map_err(|_| "Invalid input. Please enter a valid number.".to_string()) +} + +fn get_input_value(prompt: &str) -> T { + loop { + match get_input(prompt) { + Ok(value) => return value, + Err(e) => eprintln!("{}", e), + } + } +} + +fn main() { + let n: i64 = get_input_value("Enter the value for n: "); + let x: i64 = get_input_value("Enter the value for x: "); + let y: i64 = get_input_value("Enter the value for y: "); + + let result = sudan(n, x, y); + println!("The result of F({}, {}, {}) is: {}", n, x, y, result); +}