How to remove every N‑th element from an array in Kotlin

1 Answer

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

/*
    removeEveryNth returns a new List<T> with every Nth element removed.

    Kotlin lists 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 list length before the loop,
    which avoids repeatedly accessing items.size inside the loop.

    A mutable list is used internally for efficient building,
    and then converted back to an immutable List at the end.
*/
fun <T> removeEveryNth(items: List<T>, n: Int): List<T> {
    require(n > 0) { "n must be a positive integer" }

    val size: Int = items.size            // capture size once
    val result: MutableList<T> = ArrayList(size)

    for (i: Int in 0 until size) {
        if ((i + 1) % n != 0) {
            result.add(items[i])
        }
    }

    return result.toList()
}

/*
    main demonstrates the function with a simple example.
    Keeping main small and focused makes the program easy to extend.
*/
fun main() {
    val data: List<Int> = (1..20).toList()   // Example list: numbers 1–20
    val n: Int = 3                           // Remove every 3rd element

    val cleaned: List<Int> = removeEveryNth(data, n)

    println("Original: ${data.joinToString(" ")}")
    println("After removing every $n-th element: ${cleaned.joinToString(" ")}")
}



/*
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 16 by avibootz
...