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 0
to 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);
}
source
share