How to multiply every N consecutive items in a vector with Rust

2 Answers

0 votes
fn products_n_consecutive_items(vec: &Vec<i32>, n_consecutive_items: usize) -> Vec<i32> {
    let mut products = Vec::new();

    if n_consecutive_items == 0 || vec.len() < n_consecutive_items {
        return products; // empty
    }

    let out_size = vec.len() - n_consecutive_items + 1;
    products.reserve(out_size);

    for i in 0..out_size {
        let mut prod = 1;

        // Multiply vec[i] * vec[i+1] * ... * vec[i+n_consecutive_items-1]
        for j in 0..n_consecutive_items {
            prod *= vec[i + j];
        }

        products.push(prod);

        /*
         * Example for n_consecutive_items = 3:
         * 2 * 3 * 4  = 24
         * 3 * 4 * 5  = 60
         * 4 * 5 * 6  = 120
         * 5 * 6 * 7  = 210
         * 6 * 7 * 8  = 336
         * 7 * 8 * 9  = 504
         * 8 * 9 * 10 = 720
         */
    }

    products
}

fn main() {
    let vec = vec![2, 3, 4, 5, 6, 7, 8, 9, 10];
    let n = 3;

    let products = products_n_consecutive_items(&vec, n);
    println!("{:?}", products);
}



/*
run:

[24, 60, 120, 210, 336, 504, 720]

*/

 



answered Feb 2 by avibootz
0 votes
fn products_n_consecutive_items(vec: &Vec<i32>, n_consecutive_items: usize) -> Vec<i32> {
    if n_consecutive_items == 0 || vec.len() < n_consecutive_items {
        return Vec::new();
    }

    vec.windows(n_consecutive_items)
        .map(|window| window.iter().product())
        .collect()
}

fn main() {
    let vec = vec![2, 3, 4, 5, 6, 7, 8, 9, 10];
    let n = 3;

    let products = products_n_consecutive_items(&vec, n);
    println!("{:?}", products);
}



/*
run:

[24, 60, 120, 210, 336, 504, 720]

*/

 



answered Feb 2 by avibootz

Related questions

...