kubosuke
kubosuke

Reputation: 105

is there a good way to calculate sum of product in Rust?

I'm new to Rust, and I'm looking for a good way to calculate the sum of products in Rust.

I mean if there is a Vector like [3, 4, 5], I wanna calculate (3 * 4) + (3 * 5) + (4 * 5).

this is my method,

fn main() {
    let a = [3, 4, 5];
    assert_eq!(
        47,
        [3, 4, 5].iter().enumerate().fold(0, |mut s, (i, v)| {
            for ii in i + 1..a.len() {
                s += *v * a[ii];
            }
            s
        })
    );
}

If you know the better one, I'd love to know!

Upvotes: 2

Views: 435

Answers (1)

Joe_Jingyu
Joe_Jingyu

Reputation: 1279

You can use combinations, map and sum or combinations andfold to implement the product.

use itertools::Itertools;
fn main() {
    let a = [3, 4, 5];

    let b: i32 = a.iter().combinations(2).map(|x| x[0] * x[1]).sum();
    assert_eq!(b, 47);

    let c: i32 = a.iter().combinations(2).fold(0, |acc, x| acc + (x[0] * x[1]) );
    assert_eq!(c, 47);

}

playground

Upvotes: 4

Related Questions