Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

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