Skip to content

Commit

Permalink
Merge pull request #16 from VadimYarovoy/feat/recursion
Browse files Browse the repository at this point in the history
merge: Recursion block
  • Loading branch information
VadimYarovoy authored Aug 18, 2024
2 parents 362bf0d + 8586483 commit 88b57b9
Show file tree
Hide file tree
Showing 5 changed files with 124 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
mod arrays;
mod linked_lists;
mod recursion;
36 changes: 36 additions & 0 deletions src/recursion/factorial.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#![allow(dead_code)]
fn factorial_recursion(num: i32) -> i32 {
match num {
1 => {
return 1;
}
n => {
return n * factorial_recursion(n - 1);
}
}
}

// Better
fn factorial_cycle(mut num: i32) -> i32 {
let mut fact = 1;
while num > 0 {
fact *= num;
num -= 1;
}

fact
}

#[cfg(test)]
mod factorial_tests {
use super::{factorial_cycle, factorial_recursion};

#[test]
fn calculate_factorial() {
assert_eq!(factorial_recursion(3), 6);
assert_eq!(factorial_recursion(4), 24);

assert_eq!(factorial_cycle(3), 6);
assert_eq!(factorial_cycle(4), 24);
}
}
56 changes: 56 additions & 0 deletions src/recursion/fibonacci.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#[allow(dead_code)]
fn fibonacci_recursion(n: i32) -> i32 {
match n {
1 => {
return 1;
}
0 => {
return 0;
}
_ => {
return fibonacci_recursion(n - 1) + fibonacci_recursion(n - 2);
}
}
}

#[allow(dead_code)]
fn fibonacci_cycle(n: i32) -> i32 {
match n {
0 => {
return 0;
}
1 => {
return 1;
}
_ => {}
}

let (mut num1, mut num2) = (0, 1);

for _ in 0..n - 1 {
let temp = num1 + num2;
num1 = num2;
num2 = temp;
}

num2
}

#[cfg(test)]
mod fibonacci_tests {
use super::{fibonacci_cycle, fibonacci_recursion};

#[test]
fn small_fibonacci_numbers_with_recursion() {
assert_eq!(fibonacci_recursion(2), 1);
assert_eq!(fibonacci_recursion(4), 3);
assert_eq!(fibonacci_recursion(8), 21);
}

#[test]
fn small_fibonacci_numbers_with_cycle() {
assert_eq!(fibonacci_cycle(2), 1);
assert_eq!(fibonacci_cycle(4), 3);
assert_eq!(fibonacci_cycle(8), 21);
}
}
28 changes: 28 additions & 0 deletions src/recursion/leetcode_70.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#[allow(dead_code)]
pub fn climb_stairs(n: i32) -> i32 {
if n < 3 {
return n;
}

let mut res = 0;
let (mut prev, mut curr) = (1, 1);

for _ in 2..n + 1 {
res = prev + curr;
prev = curr;
curr = res;
}

res
}

#[cfg(test)]
mod climb_stairs_tests {
use super::climb_stairs;

#[test]
fn basic_cases() {
assert_eq!(climb_stairs(3), 3);
assert_eq!(climb_stairs(2), 2);
}
}
3 changes: 3 additions & 0 deletions src/recursion/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
mod factorial;
mod fibonacci;
mod leetcode_70;

0 comments on commit 88b57b9

Please sign in to comment.