This commit is contained in:
raf 2024-12-01 18:26:38 +03:00
parent f28b29841a
commit 5b59d5661f
Signed by: NotAShelf
GPG key ID: AF26552424E53993
4 changed files with 60 additions and 0 deletions

4
Cargo.lock generated
View file

@ -16,6 +16,10 @@ dependencies = [
"geometry", "geometry",
] ]
[[package]]
name = "challenge-3"
version = "0.1.0"
[[package]] [[package]]
name = "geometry" name = "geometry"
version = "0.1.0" version = "0.1.0"

View file

@ -8,4 +8,5 @@ members = [
# Challenge # Challenge
"challenges/december-2024/c1", "challenges/december-2024/c1",
"challenges/december-2024/c2", "challenges/december-2024/c2",
"challenges/december-2024/c3",
] ]

View file

@ -0,0 +1,7 @@
[package]
name = "challenge-3"
version = "0.1.0"
edition = "2021"

View file

@ -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<T: std::str::FromStr>(prompt: &str) -> Result<T, String> {
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::<T>()
.map_err(|_| "Invalid input. Please enter a valid number.".to_string())
}
fn get_input_value<T: std::str::FromStr>(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);
}