Find the frequency of each element in an array in golang
Go program for Find the frequency of each element in an array. Here more information.
package main
import "fmt"
/*
Go program
Count frequency of each element in array
*/
// Function which is display array elements
func display(arr[] int) {
for i := 0 ; i < len(arr) ; i++ {
fmt.Print(" ", arr[i])
}
fmt.Print("\n")
}
// Count occurrence of given array
func frequency(arr[] int) {
// Display given array
display(arr)
// Create a empty map
var m = make(map[int] int)
for i := 0 ; i < len(arr) ; i++ {
if _, found := m[arr[i]] ; found {
// When key exists then update value
m[arr[i]] = m[arr[i]] + 1
} else {
// Add new element
m[arr[i]] = 1
}
}
fmt.Println(" Occurrence ")
// Display calculated result
for k, v := range m {
fmt.Println(" ", k, " : ", v)
}
}
func main() {
// Array element
var arr = [] int {
1,
3,
2,
1,
4,
2,
7,
9,
1,
3,
3,
4,
7,
}
frequency(arr)
}
Output
1 3 2 1 4 2 7 9 1 3 3 4 7
Occurrence
1 : 3
2 : 2
3 : 3
4 : 2
7 : 2
9 : 1
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment