How to remove every N‑th element from a list in Kotlin

1 Answer

0 votes
// ------------------------------------------------------------
// A small program showing how to remove every Nth element from
// a list using clear, expressive Kotlin patterns.
// ------------------------------------------------------------

/*
    The function below returns a new list with every Nth element removed.
    It uses `mapIndexed` to pair each element with its index, and then
    filters based on the index. Kotlin's collection operators make this
    both concise and easy to read.

    Because indices start at 0, we check (index + 1) % n != 0 to keep
    elements that are *not* in the Nth position.
*/
fun <T> removeEveryNth(items: List<T>, n: Int): List<T> {
    require(n > 0) { "n must be a positive integer" }

    return items
        .mapIndexed { index, item -> index to item }
        .filter { (index, _) -> (index + 1) % n != 0 }
        .map { (_, item) -> item }
}

/*
    Keeping main focused and readable makes the program easy to extend.
    Here we demonstrate the function with a simple example.
*/
fun main() {
    val data = (1..20).toList()   // Example list: numbers 1–20
    val n = 3                     // Remove every 3rd element

    val cleaned = removeEveryNth(data, n)

    println("Original: $data")
    println("After removing every $n-th element: $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
...