Adjacent Pairwise And Windows
Walk neighbor pairs with windows(2) and batch fixed groups with chunks, two complementary views over the same slice.
Code
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());
}How it works
Adjacent Pairwise And Windows comes down to the function main.
A single loop drives the file — for (index, batch) in readings.chunks(3).enumerate().
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
Using it
Signature: fn main()
Running the file prints labeled results such as rising steps:, batch, all windows: — each operation’s effect is visible in the output.
Key statements
let sum: u32 = batch.iter().sum();
.filter(|pair| pair[0] < pair[1])
.count();
Interactive Tools for This Topic
FAQ
- What does Adjacent Pairwise And Windows print when run?
- No setup needed: run the file and look for labeled lines like `rising steps:`, `batch`, `all windows:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.