繁体   English   中英

Rust,元组向量的类型定义

[英]Rust, type definition of vector of tuples

我正在遵循 excism rust track,我遇到了一个问题(我对 rust 非常非常陌生)

这是一个计算整数的毕达哥拉斯三元组的函数:

use std::collections::HashSet;
use rayon::prelude::*;

pub fn find(sum: u32) -> HashSet<[u32; 3]> {
    let a_b_plus_c: Vec<(u32; 2)> = (1_u32..(sum / 3_u32)).into_par_iter()
        .filter_map(|a| {
            let b_plus_c: u32 = sum - a;

            let whole_number_check: Option<u32> = (b_plus_c.pow(2) - a.pow(2)).checked_rem(b_plus_c * 2);

            match whole_number_check {
                Some(0) => Some((a, b_plus_c)),
                Some(_) => None,
                None => None,
            }
        }).collect::<Vec<(u32; 2)>>();

    a_b_plus_c.into_par_iter().filter_map(|a, b_plus_c| {
        let b: u32 = (b_plus_c.pow(2) - a.pow(2))/(b_plus_c * 2);
        let c: u32 = b_plus_c - b;

        match b {
            b if b > a => [a, b, c]
            _ => None,
        }}
        ).collect::<HashSet<[u32; 3]>>();

}

或者更确切地说,如果它有效的话......

当前的问题是:

let a_b_plus_c: Vec<(u32; 2)> = (1_u32..(sum / 3_u32)).into_par_iter()

它说它在解析a_b_plus_c的类型时需要多个符号之一,但找到了; . 从我所看到的一切(不多)来看,这是定义元组向量的正确方法,每个元组都有两个u32类型的元素。

正如我所说,这对我来说是一个学习练习,所以如果有人可以帮助我,我将不胜感激详细而详细的答案:)

对于它的价值,因为它可能会帮助您评论我的代码,这就是数学:

a + b + c = sum
a² + b² = c²
Rearrange for b:
b = ((b + c)² - a²) / (2(b + c))
So, iterate through a to get b+c, since (b+c) = sum - a
Then solve the above equation to get a, b+c, and b
Confirm that a < b
Then solve for c:
c = (b + c) - b

然后它应该将它们全部吐出到a,b,c数组的 HashSet 中

您应该在定义中枚举每个元组的元素类型。 这应该有效:

let a_b_plus_c: Vec<(u32, u32)> = (1_u32..(sum / 3_u32)).into_par_iter() 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM