Golang Program to Find the Frequency of Each Element in an Array
Last Updated :
17 Oct, 2022
Given an array of some particular data type, we want to find the frequency(number of occurrences) of the elements in the array. We can do that with the help of maps in Golang. By creating a specific datatype map with integer we can iterate over the given array and add the count to the key as the frequency of that element in the array.
Integer Array
Let’s say we have a defined integer array of n elements, we simply want to map the elements with their frequency in the array using a map. Firstly, we will define an array, it can be generated or inputted from the user depending on the program’s usage. Here we will manually populate the array just for understanding the implementation. After we have an array of integers we can create a map that maps an integer to an integer as we have an integer array, the keys in the map would be elements of the array and the value as the frequency/count of the element.
freq := make(map[int]int)
We can use make for creating a map. Simply write the key type and the value type for the map you want to create.
After creating an empty map we can iterate over the integer array and set its key as the frequency. By default, the frequency of the first time occurring key is set as zero so we can increment it by one the first time we visit an element in the array.
for _ , num := range arr {
freq[num] = freq[num]+1
}
The blank identifier (_) is simply the index of the array and num is the element at that index, so we can iterate over the range in the array i.e. the number of elements in the array. We use the num as the key which is the element in the array and map[num] as the value to the key num. Thus we increment the value by one for each unique element as a key.
Below is the complete program.
Go
package main
import "fmt"
func main(){
arr := []int{ 90 , 70 , 30 , 30 , 10 , 80 , 40 , 50 , 40 , 30 }
freq := make( map [int]int)
for _ , num := range arr {
freq[num] = freq[num]+ 1
}
fmt.Println( "Frequency of the Array is : " , freq)
}
|
Output:
Frequency of the array is: map[10:1 30:3 40:2 50:1 70:1 80:1 90:1]
So, as we can see the frequency map was created that maps the elements in the array to their frequency of occurring.
Converting into a Function
We can even convert the logic to a function for creating a frequency map for a given array of integers. We simply need to parse the array as a parameter and the return type as a map of an integer with the integer as a function head. The logic remains the same for creating a frequency map and populating it with keys and values with elements and their frequencies.
Go
package main
import "fmt"
func main(){
arr := []int{ 90 , 70 , 30 , 30 , 10 , 80 , 40 , 50 , 40 , 30 }
freq_map := frequency_map(arr)
fmt.Println( "Frequency of the Array is : " , freq_map)
}
func frequency_map( arr []int) map [int]int{
freq := make( map [int]int)
for _ , num := range arr {
freq[num] = freq[num]+ 1
}
return freq
}
|
Output:
Frequency of Array is : map [10:1 30:3 40:2 50:1 70:1 80:1 90:1]
Thus, we were able to create a frequency map for an integer array using a map in Go lang.
String
Let’s say we have a string and we want to create a frequency count for each character in the string. In this case, we will create a map of string to an integer, we will store each character in the string as a string because it is convenient to display the content and store the count of that string character as the value in the map.
Note: We can even use rune or byte type in place of a string key, the problem with that is it displays the Unicode/ASCII code as the key and not the string itself.
Firstly we will define a string. Similar to the integer map we will create a map that maps a string to an integer like so:
freq := make(map[string]int)
After creating a map, we simply iterate over the string character by character and increment the value of the key, here the key is the character of the string. We will concatenate the character (byte/rune) type as a string just because it is convenient to read the map as a human. But you can keep it as it is then you might have to change the key type of the map to:
freq := make(map[byte]int) OR freq := make(map[rune]int)
This will create a map that stores the keys as Unicode values of the character in the string.
We then iterate over the string and increment the value of the character key in the string as follows:
for _ , char := range word {
freq[string(char)] = freq[(char)]+1
}
So, finally combining the pieces, we have a script that takes in a string and maps each character(string type) as the key and its frequency in the string as its value in the map.
Go
package main
import "fmt"
func main(){
arr := "geeksforgeeks"
freq := make( map [ string ]int)
for _ , char := range arr {
freq[ string (char)] = freq[ string (char)]+ 1
}
fmt.Println( "Frequency of Array is : " , freq)
}
|
Output:
Frequency of Array is : map[e:4 f:1 g:2 k:2 0:1 r:1 s:2]
Thus, we can see we get the map of each unique character in the given string with its frequency or count of its occurrence in the entire string.
Using rune/byte as keys in the map
Also if we use the rune/byte data type to create the map without concatenating the character to a string, we will get the output as below:
Go
package main
import "fmt"
func main(){
arr := "geeksforgeeks"
freq := make( map [ rune ]int)
for _ , char := range arr {
freq[char] = freq[char]+ 1
}
fmt.Println( "Frequency of Array is : " , freq)
}
|
Output:
Frequency of Array is : map[101:4 102:1 103:2 107:2 111:1 114:1 115:2]
The same is the output for byte except it won’t accept the characters which are not in ASCII (0 to 255) codes and hence quite limited in the sets of characters. The byte would give a compilation error if the value is out of bounds from its range for a byte. The default value selected if not specified for a character is a rune in Go lang. Still, if you want to use byte as a key in the map, you can specify it in the declaration just as a rune and therefore you also need to concatenate it with a byte.
Go
package main
import "fmt"
func main(){
arr := "geeksforgeeks"
freq := make( map [ byte ]int)
for _ , char := range arr {
freq[ byte (char)] = freq[ byte (char)]+ 1
}
fmt.Println( "Frequency of Array is : " , freq)
}
|
Output:
Frequency of Array is : map[101:4 102:1 103:2 107:2 111:1 114:1 115:2]
Converting to a function
Also, here we can convert the procedural code into a functional approach by creating a function for creating the frequency count of the characters in the string.
Go
package main
import "fmt"
func main(){
arr := "geeksforgeeks"
freq_map := frequency_map(arr)
fmt.Println( "Frequency of Array is : " , freq_map)
}
func frequency_map(arr string ) map [ string ]int{
freq := make( map [ string ]int)
for _ , char := range arr {
freq[ string (char)] = freq[ string (char)]+ 1
}
return freq
}
|
Output:
Frequency of Array is : map[e:4 f:1 g:2 k:2 o:1 r:1 s:2]
Hence the function frequency_map returns the map which is a string to integer mapping. So we were able to get a frequency map of string by just parsing the string to a function and storing the frequency in a variable.
Similar Reads
Golang Program to Find Largest Element in an Array
The task is to find the largest element of an array in Golang by taking input values from the user. Example: Input: Enter the number of elements: 4 Enter the number : 40 Enter the number : 69 Enter the number : 89 Enter the number : -54 Output: The largest number is : 89 In this program, the user ne
2 min read
Program to shift all zero to the end of array in Golang
The task is to shift all the zeroes appearing in the array to the end of the array. In Golang, this can be done as follows:Example:Â Input: 1 0 7 0 3 Output: 1 7 3 0 0[GFGTABS] Go // Golang program to shift all zero to the end of an array package main import ( "fmt" ) func main() { // Crea
1 min read
Golang Program that Removes Duplicate Elements From the Array
Arrays in Golang or Go programming language is much similar to other programming languages. In the program, sometimes we need to store a collection of data of the same type, like a list of student marks. Such type of collection is stored in a program using an Array. An array is a fixed-length sequen
4 min read
How to find the capacity of the pointer in Golang?
Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Pointers in Golang are also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always
2 min read
How to pass an Array to a Function in Golang?
In Go, arrays are used to store a fixed-length collection of data of the same type. To manage this data effectively, you may often need to pass arrays to functions. In this article we will learn "How to pass an Array to a Function in Golang". Example: [GFGTABS] Go package main import "fmt"
2 min read
reflect.ArrayOf() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.ArrayOf() Function in Golang is used to get the array type with the given count and element type, i.e., if x repr
2 min read
How to Count the Number of Repeated Characters in a Golang String?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go string, you can count some specific Unicode code points or the number o
2 min read
Searching an element of string type in Golang slice
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice, you can search
3 min read
fmt.Fscan() Function in Golang With Examples
In Go language, fmt package implements formatted I/O with functions analogous to C's printf() and scanf() function. The fmt.Fscan() function in Go language scans the specified text, read from r, and then stores the successive space-separated values into successive arguments. Here newlines get counte
3 min read
How to Calculate the Average using Arrays in Golang?
Given an array of n elements, your task is to find out the average of the array.Approach:Â Accept the size of the array.Accept the elements of the array.Store the sum of the elements using for loop.Calculate Average = (sum/size of array)Print the average. Example:Â Input: n = 4 array = 1, 2, 3, 4 Ou
2 min read