How to remove every N‑th element from a vector in Rust

1 Answer

0 votes
// ------------------------------------------------------------
// A small program demonstrating how to remove every Nth element
// from a Vec<T> using clear, expressive Rust patterns.
// ------------------------------------------------------------

/*
    remove_every_nth returns a new Vec<T> with every Nth element removed.

    Rust vectors use zero‑based indexing, so we check (index + 1) % n != 0
    to keep elements that are *not* in the Nth position.

    The variable "size" captures the vector length before the loop,
    which avoids repeatedly calling items.len() inside the loop.

    A new vector is allocated with enough capacity to avoid repeated
    reallocations during push operations.
*/
fn remove_every_nth<T: Clone>(items: &Vec<T>, n: usize) -> Vec<T> {
    if n == 0 {
        panic!("n must be a positive integer");
    }

    let size: usize = items.len();      // capture size once
    let mut result: Vec<T> = Vec::with_capacity(size);

    for i in 0..size {
        if (i + 1) % n != 0 {
            result.push(items[i].clone());
        }
    }

    result
}

/*
    main demonstrates the function with a simple example.
    Keeping main small and focused makes the program easy to extend.
*/
fn main() {
    let mut data: Vec<i32> = Vec::with_capacity(20);
    for i in 1..=20 {
        data.push(i); // Example vector: numbers 1–20
    }

    let n: usize = 3; // Remove every 3rd element

    let cleaned: Vec<i32> = remove_every_nth(&data, n);

    println!("Original: {:?}", data);
    println!("After removing every {}-th element: {:?}", n, cleaned);
}



/*
run:

Original: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
After removing every 3-th element: [1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20]

*/

 



answered Aug 15 by avibootz
...