From 5b59d5661fae915d4d962da3b8946fd59584d454 Mon Sep 17 00:00:00 2001 From: NotAShelf Date: Sun, 1 Dec 2024 18:26:38 +0300 Subject: [PATCH] c3: init --- Cargo.lock | 4 +++ Cargo.toml | 1 + challenges/december-2024/c3/Cargo.toml | 7 ++++ challenges/december-2024/c3/src/main.rs | 48 +++++++++++++++++++++++++ 4 files changed, 60 insertions(+) create mode 100644 challenges/december-2024/c3/Cargo.toml create mode 100644 challenges/december-2024/c3/src/main.rs 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); +}