How to group elements of an array based on their first occurrence in Scala

1 Answer

0 votes
object GroupElementsApp {
  val MAX_VALUE = 100 // Assumes values are between 0 and 99

  def groupElements(arr: Array[Int]): Array[Int] = {
    val frequency = Array.fill(MAX_VALUE)(0)
    val order = scala.collection.mutable.ArrayBuffer[Int]()
    val result = scala.collection.mutable.ArrayBuffer[Int]()

    // Count frequencies and track order of first occurrences
    for (num <- arr) {
      if (frequency(num) == 0) {
        order += num
      }
      frequency(num) += 1
    }

    // Group elements based on their first occurrence
    for (num <- order) {
      result ++= Array.fill(frequency(num))(num)
    }

    result.toArray
  }

  def main(args: Array[String]): Unit = {
    val arr = Array(88, 33, 77, 88, 22, 55, 88, 55, 11, 99, 88, 11, 77)
    val grouped = groupElements(arr)

    print("Grouped vector: ")
    println(grouped.mkString(" "))
  }
}



/*
run:

Grouped vector: 88 88 88 88 33 77 77 22 55 55 11 11 99

*/



 



answered Oct 11, 2025 by avibootz
...