Last active
April 27, 2020 15:51
-
-
Save huangsam/3b6daae566cfb370ee12df5aabb15b46 to your computer and use it in GitHub Desktop.
Classic algorithms in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//! A module with classic algorithms from CS 101 classes. | |
//! Consider using this as a way to learn how Rust works | |
//! in general while solving safe + simple problems. | |
/// Returns a `Result` from computing factorial | |
/// | |
/// # Arguments | |
/// | |
/// * `n` - An integer | |
pub fn fact(n: i32) -> Result<i32, i32> { | |
match n { | |
n if n < 0 => Err(n), | |
0 | 1 => Ok(1), | |
n => { | |
let mut result = 1; | |
for i in 1..n+1 { | |
result = result * i; | |
} | |
Ok(result) | |
} | |
} | |
} | |
/// Returns a `Result` from computing fibonacci | |
/// | |
/// # Arguments | |
/// | |
/// * `n` - An integer | |
pub fn fib(n: i32) -> Result<i32, i32> { | |
match n { | |
n if n < 0 => Err(n), | |
0 => Ok(0), | |
1 => Ok(1), | |
n => { | |
let mut current = 0; | |
let mut next = 1; | |
for _ in 1..n { | |
let temp = next; | |
next = next + current; | |
current = temp; | |
} | |
Ok(next) | |
} | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn fact_0() { | |
match fact(0) { | |
Ok(v) => assert_eq!(v, 1), | |
Err(f) => panic!("error: {}", f) | |
} | |
} | |
#[test] | |
fn fact_6() { | |
match fact(6) { | |
Ok(v) => assert_eq!(v, 720), | |
Err(f) => panic!("error: {}", f) | |
} | |
} | |
#[test] | |
fn fib_0() { | |
match fib(0) { | |
Ok(v) => assert_eq!(v, 0), | |
Err(f) => panic!("error: {}", f) | |
} | |
} | |
#[test] | |
fn fib_1() { | |
match fib(1) { | |
Ok(v) => assert_eq!(v, 1), | |
Err(f) => panic!("error: {}", f) | |
} | |
} | |
#[test] | |
fn fib_6() { | |
match fib(6) { | |
Ok(v) => assert_eq!(v, 8), | |
Err(f) => panic!("error: {}", f) | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mod classic; | |
fn main() { | |
for n in -1..9 { | |
match classic::fact(n) { | |
Err(e) => println!("fact({}) [Err] => {}", n, e), | |
Ok(r) => println!("fact({}) [Ok] => {}", n, r), | |
}; | |
} | |
for n in -1..9 { | |
match classic::fib(n) { | |
Err(e) => println!("fib({}) [Err] => {}", n, e), | |
Ok(r) => println!("fib({}) [Ok] => {}", n, r), | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment