Interleave Two Sequences With Zip And Chain
Interleave two sequences by zipping until the shorter side runs out and chaining the leftover tail, so no element from either input drops.
Code
fn interleave<T: Clone>(a: &[T], b: &[T]) -> Vec<T> {
// zip stops when the shorter of the two sequences ends; chain appends the tail
let head: Vec<T> = a
.iter()
.zip(b)
.flat_map(|(x, y)| [x.clone(), y.clone()])
.collect();
let rest = if a.len() >= b.len() {
&a[b.len()..]
} else {
&b[a.len()..]
};
head.into_iter().chain(rest.iter().cloned()).collect()
}
fn main() {
let front = ["w1", "w2", "w3", "w4"];
let back = ["b1", "b2"];
let mixed = interleave(&front, &back);
println!("interleave: {mixed:?}");
let even = [2, 4, 6];
let odd = [1, 3, 5];
let merged: Vec<i32> = interleave(&even, &odd);
println!("merged: {merged:?}");
}How the snippet works
Structurally, expect the functions interleave and main and nothing else.
Applying it
Labels (interleave:, merged:) ride along on the demo’s output, keeping line and origin connected.
Launch the file; main takes over and steps through interleave.
Statements that matter
head.into_iter().chain(rest.iter().cloned()).collect()
}
Interactive Tools for This Topic
FAQ
- What does Interleave Two Sequences With Zip And Chain print when run?
- Running the file directly is enough — expect labeled output lines such as `interleave:`, `merged:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.