Tribonacci序列在Rust中的惯用实现 [英] Idiomatic implementation of the tribonacci sequence in Rust
问题描述
我是Rust的新手,但是作为Haskell的粉丝,我非常感谢match
在Rust中的工作方式.现在,我遇到了我确实需要彻底解决的罕见情况-从某种意义上说,我希望执行多个重叠案例的所有匹配案例.这有效:
I’m new to Rust, but as a fan of Haskell, I greatly appreciate the way match
works in Rust. Now I’m faced with the rare case where I do need fall-through – in the sense that I would like all matching cases of several overlapping ones to be executed. This works:
fn options(stairs: i32) -> i32 {
if stairs == 0 {
return 1;
}
let mut count: i32 = 0;
if stairs >= 1 {
count += options(stairs - 1);
}
if stairs >= 2 {
count += options(stairs - 2);
}
if stairs >= 3 {
count += options(stairs - 3);
}
count
}
我的问题是,这在Rust中是惯用的还是有更好的方法.
My question is whether this is idiomatic in Rust or whether there is a better way.
上下文是破解编码面试中的一个问题:一个孩子正在以 n 步长跑上楼梯,可以跳1步,2步或一次3个步骤.实施一种方法来计算孩子上楼梯的可能方式."
The context is a question from Cracking the Coding Interview: "A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs."
推荐答案
基于 Tribonacci序列的定义我发现您可以像这样更简洁地编写它:
Based on the definition of the tribonacci sequence I found you could write it in a more concise manner like this:
fn options(stairs: i32) -> i32 {
match stairs {
0 => 0,
1 => 1,
2 => 1,
3 => 2,
_ => options(stairs - 1) + options(stairs - 2) + options(stairs - 3)
}
}
我还建议您将功能定义更改为仅接受正整数,例如u32
.
I would also recommend changing the funtion definition to only accept positive integers, e.g. u32
.
这篇关于Tribonacci序列在Rust中的惯用实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!