c3: init
This commit is contained in:
parent
f28b29841a
commit
5b59d5661f
4 changed files with 60 additions and 0 deletions
4
Cargo.lock
generated
4
Cargo.lock
generated
|
@ -16,6 +16,10 @@ dependencies = [
|
|||
"geometry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "challenge-3"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "geometry"
|
||||
version = "0.1.0"
|
||||
|
|
|
@ -8,4 +8,5 @@ members = [
|
|||
# Challenge
|
||||
"challenges/december-2024/c1",
|
||||
"challenges/december-2024/c2",
|
||||
"challenges/december-2024/c3",
|
||||
]
|
||||
|
|
7
challenges/december-2024/c3/Cargo.toml
Normal file
7
challenges/december-2024/c3/Cargo.toml
Normal file
|
@ -0,0 +1,7 @@
|
|||
[package]
|
||||
name = "challenge-3"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
|
||||
|
48
challenges/december-2024/c3/src/main.rs
Normal file
48
challenges/december-2024/c3/src/main.rs
Normal 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);
|
||||
}
|
Loading…
Reference in a new issue