find the mode of all elements in an array in go

To find the mode of all elements in an array in Go, we can use a frequency map. We iterate through the array and keep track of the frequency of each element in the map. Once we have the frequency map, we can iterate through it and find the element with the highest frequency.

Here's the code snippet to find the mode of an array in Go using a frequency map:

main.go
func findMode(arr []int) int {
    freqMap := make(map[int]int)

    for _, num := range arr {
        freqMap[num]++
    }

    var mode int
    maxFreq := 0

    for num, freq := range freqMap {
        if freq > maxFreq {
            mode = num
            maxFreq = freq
        }
    }

    return mode
}
310 chars
20 lines

In this code, arr is the input array. We create a freqMap map to keep track of the frequency of each element in the array. We iterate through the array using a for loop and increment the frequency of each element in the map. Once we have the frequency map, we iterate through it using another for loop and find the element with the highest frequency. We update the mode variable to the element with the highest frequency.

Finally, we return the mode variable, which contains the mode of the array.

related categories

gistlibby LogSnag