Refactoring stuff

main
Eric 2025-07-30 09:19:29 +02:00
parent a54aed634f
commit 2260fb9d86
No known key found for this signature in database
2 changed files with 16 additions and 12 deletions

View File

@ -1,18 +1,15 @@
use issue_77::{climb_stairs, climb_stairs2};
fn main() { fn main() {
divan::main(); divan::main();
} }
#[divan::bench(args = [1, 2, 4, 8, 16, 32, 64, 128])] #[divan::bench(args = [1, 2, 4, 8, 16, 32, 64, 128])]
pub fn fibonacci_loop(n: i32) -> i32 { pub fn fibonacci_loop(n: i32) -> i32 {
let mut a = 0; climb_stairs2(n)
let mut b = 1;
for _ in 0..n {
(a, b) = (b, a + b);
}
b
} }
#[divan::bench(args = [1, 2, 4, 8, 16, 32, 64, 128])] #[divan::bench(args = [1, 2, 4, 8, 16, 32, 64, 128])]
pub fn fibonacci_fold(n: i32) -> i32 { pub fn fibonacci_fold(n: i32) -> i32 {
(0..n).fold((0, 1), |(a, b), _| (b, a + b)).1 climb_stairs(n)
} }

View File

@ -1,8 +1,5 @@
// Rust Bytes Issue 77: Climbing Stairs
pub fn main() {}
pub fn climb_stairs2(n: i32) -> i32 { pub fn climb_stairs2(n: i32) -> i32 {
let mut a = 0; let (mut a, mut b) = (0, 1);
let mut b = 1;
for _ in 0..n { for _ in 0..n {
(a, b) = (b, a + b); (a, b) = (b, a + b);
} }
@ -15,55 +12,65 @@ pub fn climb_stairs(n: i32) -> i32 {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::climb_stairs; use super::*;
#[test] #[test]
fn test_zero_steps() { fn test_zero_steps() {
assert_eq!(climb_stairs(0), 1); assert_eq!(climb_stairs(0), 1);
assert_eq!(climb_stairs2(0), 1);
} }
#[test] #[test]
fn test_one_step() { fn test_one_step() {
assert_eq!(climb_stairs(1), 1); assert_eq!(climb_stairs(1), 1);
assert_eq!(climb_stairs2(1), 1);
} }
#[test] #[test]
fn test_two_steps() { fn test_two_steps() {
assert_eq!(climb_stairs(2), 2); assert_eq!(climb_stairs(2), 2);
assert_eq!(climb_stairs2(2), 2);
} }
#[test] #[test]
fn test_three_steps() { fn test_three_steps() {
assert_eq!(climb_stairs(3), 3); assert_eq!(climb_stairs(3), 3);
assert_eq!(climb_stairs2(3), 3);
} }
#[test] #[test]
fn test_four_steps() { fn test_four_steps() {
assert_eq!(climb_stairs(4), 5); assert_eq!(climb_stairs(4), 5);
assert_eq!(climb_stairs2(4), 5);
} }
#[test] #[test]
fn test_five_steps() { fn test_five_steps() {
assert_eq!(climb_stairs(5), 8); assert_eq!(climb_stairs(5), 8);
assert_eq!(climb_stairs2(5), 8);
} }
#[test] #[test]
fn test_six_steps() { fn test_six_steps() {
assert_eq!(climb_stairs(6), 13); assert_eq!(climb_stairs(6), 13);
assert_eq!(climb_stairs2(6), 13);
} }
#[test] #[test]
fn test_small_negative() { fn test_small_negative() {
assert_eq!(climb_stairs(-1), 1); assert_eq!(climb_stairs(-1), 1);
assert_eq!(climb_stairs2(-1), 1);
} }
#[test] #[test]
fn test_seven_steps() { fn test_seven_steps() {
assert_eq!(climb_stairs(7), 21); assert_eq!(climb_stairs(7), 21);
assert_eq!(climb_stairs2(7), 21);
} }
#[test] #[test]
fn test_ten_steps() { fn test_ten_steps() {
assert_eq!(climb_stairs(10), 89); assert_eq!(climb_stairs(10), 89);
assert_eq!(climb_stairs2(10), 89);
} }
} }