Vec Every Nth Element
This page was last reviewed on Feb 1, 2024.
Dot Net Perls
Nth element. Suppose you have a Vector in Rust, and wish to filter out every other element, or every N elements. This is similar to the Nth-child selector from CSS.
The retain function in Rust acts upon an element value, not its index. But we can pass a local variable (and increment that variable) to retain().
Output requirement. Consider a Vector of 4 i32 integers in Rust. When we get every other integer, we want a Vector that has the first, and third, elements remaining.
Input: 1, 2, 3, 4 Output: 1, 3 (Every Nth(2))
To start, we introduce the every_nth_element—this receives a Vector of integers. We call every_nth_element twice in the program.
Part 1 We filter the Vector and get every other element—we must pass the argument 2 to indicate "every other."
Part 2 We get every third element from the Vector. Notice how the first and fourth elements, 10 and 40, are the ones remaining here.
Info In every_nth_element we start the index counter "c" at -1 as it is incremented before being tested.
fn every_nth_element(values: &mut Vec<i32>, n: i32) { // Retain elements with evenly divisible indexes. let mut c = -1; values.retain(|_| { c += 1; return c % n == 0 }); } fn main() { // Part 1: retain every other element. // Be sure to borrow vectors mutably. let mut values1 = vec![1, 2, 3, 4]; every_nth_element(&mut values1, 2); println!("EVERY OTHER: {:?}", values1); // Part 2: retain every third element. let mut values2 = vec![10, 20, 30, 40, 50, 60]; every_nth_element(&mut values2, 3); println!("EVERY NTH(3): {:?}", values2); }
EVERY OTHER: [1, 3] EVERY NTH(3): [10, 40]
We can pass a function argument to retain() on a vector to keep certain elements in the vector. And we can filter on indexes with a local variable.
String Array
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 1, 2024 (edit).
© 2007-2024 Sam Allen.