Multiplying elements from two different arrays [duplicate]

☆樱花仙子☆ 提交于 2020-01-16 18:28:42

问题


I'm trying to multiply each element from two different arrays. I mean, I have array1 = [i1 , i2] and array2 = [j1, j2] so I need to do (i1 * j1) + (i2 * j2). How can I approach this in Rust? I've been researching in The Book and saw some methods that possibly could help: map and fold. But I'm a bit lost. Thanks in advance!

fn sum_product(a: [f32], b: [f32]) -> [f32] {
    unimplemented!();
}

fn main() {
    let a: [f32; 2] = [2.0, 3.0];
    let b: [f32; 2] = [0.0, 1.0];
}

回答1:


With a mix of zip and map:

fn sum_product(a: &[f32], b: &[f32]) -> f32 {
    a.iter()
        .zip(b.iter())
        .map(|(a, b)| a * b)
        .sum()
}

fn main() {
    let a = [2.0, 3.0];
    let b = [0.0, 1.0];

    assert_eq!(3.0, sum_product(&a, &b));
}


来源:https://stackoverflow.com/questions/56930343/multiplying-elements-from-two-different-arrays

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!