Avoiding loops when iterating over adjacent elements of a vector

In Rust, how do I avoid writing these loops? The code takes a vector and multiplies three adjacent elements by a product. Therefore, the outer loop covers all the elements that can form a group of three, and the inner loop performs multiplication.

The difficulty lies, I think, in the incomplete iteration of the outer loop (from element 0to last - 3). In addition, the inner loop must use a subrange.

Is there a way to avoid writing loops?

let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let mut products = Vec::new();
for seq in 0..v.len() - 3 {
    let mut product = 1;
    for offset in 0..3 {
        product *= v[seq + offset];
    }
    products.push(product);
}
+6
source share
1 answer

, , [T]::windows(). , -.

-, Iterator::product().

let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let products: Vec<u64> = v.windows(3)
    .map(|win| win.iter().product())
    .collect();

( )

.


: :

let v: Vec<_> = (1..10).chain(1..10).collect();
+8

Source: https://habr.com/ru/post/1016670/


All Articles