Frequency Counter Program in Go

Published November 12, 2021

In this article, the frequency counter program is created with Go programming language.

These are the steps to create frequency counter.

  1. Create a variable to store frequency.
  2. Iterate through collections. If the data is exists inside collection then increase the frequency value by 1.
  3. Return the frequency result.

This is the implementation.

func getFrequency(n int, nums []int) int {
    // create a variable to store frequency value
    var frequency int

    // iterate through every items
    for _, num := range nums {
        // if the item inside slice is equals to
        // current item ("n")
        // increase the frequency value by 1
        if num == n {
            frequency++
        }
    }

    // return the frequency result
    return frequency
}

The getFrequency() is used inside main function.

package main

import (
    "fmt"
)

func main() {
    // create a slice of integers
    var numbers []int = []int{1, 1, 2, 3, 4, 4, 5, 6, 7, 8, 8, 8, 8, 9}

    // create a map to store frequency of every integers
    var frequencies map[int]int = make(map[int]int)

    // calculate the frequency of each integers
    for _, number := range numbers {
        frequencies[number] = getFrequency(number, numbers)
    }

    // print out the result
    fmt.Println("The frequencies: ", frequencies)
}

Output

The frequencies:  map[1:2 2:1 3:1 4:2 5:1 6:1 7:1 8:4 9:1]

I hope this article is helpful to learn about creating frequency counter in Go.

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

640 Views