是否有更有效/惯用的方法来计算多个点之间的总距离?
https://play.rust-lang.org/?version=stable&mode=调试&edition=2018&gist=60c95a1c6f0e7719e653520fe0227e6e
输入:calculate_distance("100 100 200 200 300 300")
输出:282.842712474619
fn calculate_distance(vertices: &str) -> f64 {
let vertices: Vec<_> = vertices
.split_whitespace()
.filter_map(|s| s.parse::<f64>().ok())
.collect();
vertices.windows(4).step_by(2).fold(0.0, |total, p| {
let (x1, y1, x2, y2) = (p[0], p[1], p[2], p[3]);
total + ((x2 - x1).powf(2.0) + (y2 - y1).powf(2.0)).sqrt()
})
}
编辑:https://play.rust-lang.org/?version=stable&mode=调试&edition=2018&gist=4f7553fcd97db2957b3963dc5476920d
现在您有一个固有的约束,即输入字符串的格式为"x0y0x1y1。。。xnyn";。一个更惯用的解决方案是首先解析这个";结构化的";字符串转换为您定义的Point
结构的数组,并在calculate_distance()
之外执行此操作。然后让calculate_distance()
对Point
s的阵列进行操作。
这里的想法是,解析代码有责任处理错误的输入。通过允许calculate_distance()
对比&str
更严格约束的类型进行操作,它大大减少了函数出错的次数。