![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a Golang program to find the frequency of each element in an array
Examples
Input Array = [1, 3, 4, 3, 2, 3, 4, 0, 2]
Element | 1 | 3 | 4 | 2 | 0 |
Frequency | 1 | 3 | 2 | 2 | 1 |
Approach to solve this problem
- Step 1: Define a method that accepts an array.
- Step 2: Define a map, where key would be the array’s elements and the starting value is 0.
- Step 3: Start iterating the input array. If an element is present in the map, then increment the count.
- Step 4: If the element is not present in the map, then store in map and make its value 1.
Program
package main import ( "fmt" ) func findFrequencyOfArray(arr []int){ frequency := make(map[int]int) for _, item := range arr{ if frequency[item] == 0{ frequency[item] = 1 } else { frequency[item]++ } } for item, count := range frequency{ fmt.Printf("%d occurring %d times.\n", item, count) } } func main(){ findFrequencyOfArray([]int{2, 2, 5, 1, 3, 5, 0}) }
Output
2 occurring 2 times. 5 occurring 2 times. 1 occurring 1 times. 3 occurring 1 times. 0 occurring 1 times.
Advertisements