In Rust, how do I avoid writing these loops? The code takes a vector and multiplies three adjacent elements to a product. Hence, the outer loop goes over all elements that can form a group of three and the inner loop does the multiplication.
在Rust中,如何避免编写这些循环?代码采用向量并将三个相邻元素乘以产品。因此,外部循环遍历可以形成一组三个的所有元素,并且内部循环执行乘法。
The difficulty lies, I think, in the incomplete iteration of the outer loop (from element 0
to last - 3
). Further, the inner loop must use a sub-range.
我认为,难点在于外循环的不完整迭代(从元素0到最后-3)。此外,内环必须使用子范围。
Is there a way to avoid writing the 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);
}
1 个解决方案
#1
8
The function you are searching for is [T]::windows()
. You can specify the size of the overlapping windows and it will return an iterator over sub-slices.
您要搜索的函数是[T] :: windows()。您可以指定重叠窗口的大小,它将在子切片上返回迭代器。
You can obtain the product of all elements within a sub-slice by making an iterator out of it and using Iterator::product()
.
您可以通过使用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();
(操场)
Here we collect all products into a new vector.
在这里,我们将所有产品收集到新的载体中。
A last note: instead of writing down all numbers in the vector manually you could write this instead:
最后一点:不要手动写下向量中的所有数字,而是可以写下来:
let v: Vec<_> = (1..10).chain(1..10).collect();
#1
8
The function you are searching for is [T]::windows()
. You can specify the size of the overlapping windows and it will return an iterator over sub-slices.
您要搜索的函数是[T] :: windows()。您可以指定重叠窗口的大小,它将在子切片上返回迭代器。
You can obtain the product of all elements within a sub-slice by making an iterator out of it and using Iterator::product()
.
您可以通过使用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();
(操场)
Here we collect all products into a new vector.
在这里,我们将所有产品收集到新的载体中。
A last note: instead of writing down all numbers in the vector manually you could write this instead:
最后一点:不要手动写下向量中的所有数字,而是可以写下来:
let v: Vec<_> = (1..10).chain(1..10).collect();