2

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!

kubosuke
  • 45
  • 5
  • 1
    `a.iter().enumerate().flat_map(|(i, x)| a[i + 1..].iter().map(move |y| x * y)).sum()` (not putting this as an answer because I'm not too sure if this question is appropriate for Stack Overflow) – Lauren Yim Nov 27 '21 at 07:08
  • 1
    The value you are after is `((sum a[i])**2 - sum (a[i]**2))/2`. Linear time complexity. – user58697 Nov 27 '21 at 17:44

1 Answers1

3

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

Joe_Jingyu
  • 1,024
  • 6
  • 9