实现说明
相邻窗口与固定分组以函数 main为骨架。
for (index, batch) in readings.chunks(3).enumerate() 是唯一的迭代点——其余代码顺序执行一遍。
使用要点
- 演示输出是带标签的(
rising steps:、batch、all windows:),每个操作都会留下自己的一行标注。
常见问题
运行「相邻窗口与固定分组」会打印什么?
整个文件跑完,输出行以 rising steps:、batch、all windows: 这类前缀开头。
主要签名是 fn main()
核心语句
let sum: u32 = batch.iter().sum();
.filter(|pair| pair[0] < pair[1])
.count();
代码示例
fn main() {
let readings = [3u32, 5, 4, 9, 12, 11, 15];
// windows(2):相邻对,逐个比较相邻读数是否单调上升
let rises = readings
.windows(2)
.filter(|pair| pair[0] < pair[1])
.count();
println!("rising steps: {}/{}", rises, readings.len() - 1);
// chunks(3):固定分组,用于分批处理
for (index, batch) in readings.chunks(3).enumerate() {
println!("batch {} avg: {:.1}", index, {
let sum: u32 = batch.iter().sum();
sum as f64 / batch.len() as f64
});
}
// windows 滑动重叠,chunks 不重叠:同一数据两种切法
println!("all windows: {:?}", readings.windows(2).count());
println!("all chunks: {:?}", readings.chunks(3).count());
}