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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to group elements of a slice based on their first occurrence in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

func groupElements(arr []int) []int {
    frequency := make(map[int]int)
    order := []int{}
    result := []int{}

    // Count frequencies and track first occurrences
    for _, num := range arr {
        if _, exists := frequency[num]; !exists {
            order = append(order, num)
        }
        frequency[num]++
    }

    // Group elements based on first occurrence
    for _, num := range order {
        for i := 0; i < frequency[num]; i++ {
            result = append(result, num)
        }
    }

    return result
}

func main() {
    vec := []int{88, 33, 77, 88, 22, 55, 88, 55, 11, 99, 88, 11, 77}
    grouped := groupElements(vec)

    fmt.Print("Grouped vector: ")
    for _, num := range grouped {
        fmt.Printf("%d ", num)
    }
    fmt.Println()
}



/*
run:

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

*/

 



answered Oct 10, 2025 by avibootz
...