How to print the distinct elements of an array in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

// Counts how many times each number appears in the array
func countFrequency(nums []int) map[int]int {
    freq := make(map[int]int)
    for _, num := range nums {
        freq[num]++
    }
    return freq
}

// Collects elements that occur only once
func collectUniques(freq map[int]int) []int {
    var unique []int
    for num, count := range freq {
        if count == 1 {
            unique = append(unique, num)
        }
    }
    return unique
}

func main() {
    array := []int{3, 5, 9, 1, 7, 8, 1, 9, 0, 3, 9}

    freq := countFrequency(array)
    unique := collectUniques(freq)

    fmt.Println(unique)
}



/*
run:

[5 7 8 0]

*/

 



answered Jul 13, 2025 by avibootz
...