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

1 Answer

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

object RemoveEveryNthApp {

  /*
      removeEveryNth returns a new List[T] with every Nth element removed.

      Scala 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 calling items.size inside the loop.

      A mutable ListBuffer is used internally for efficient building,
      and then converted back to an immutable List at the end.
  */
  def removeEveryNth[T](items: List[T], n: Int): List[T] = {
    if (n <= 0)
      throw new IllegalArgumentException("n must be a positive integer")

    val size: Int = items.size            // capture size once
    val buffer = scala.collection.mutable.ListBuffer[T]()

    var i: Int = 0
    while (i < size) {
      if ((i + 1) % n != 0) {
        buffer += items(i)
      }
      i += 1
    }

    buffer.toList
  }

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

    val cleaned: List[Int] = removeEveryNth(data, n)

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



/*
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
...