簡體   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