Go Program to Count Frequencies of Elements in an Array

 

 

Program Explanation

This Go program counts the frequencies of elements in an array using a hash map (or dictionary).
The hash map allows for efficient counting by using the elements of the array as keys and their counts as values.

Program Structure

  • Import Statements:
    The program imports the necessary packages, including fmt for formatted I/O.
  • Function countFrequencies:
    This function takes an integer slice as input and returns a map containing the counts of each element.
  • Main Function:
    This function initializes an array, calls countFrequencies, and prints the results.

Go Code

package main

import (
    "fmt"
)

// countFrequencies counts the frequencies of elements in the given array.
func countFrequencies(arr []int) map[int]int {
    freqMap := make(map[int]int) // Create a map to hold the frequencies.

    // Iterate over the array and count the occurrences of each element.
    for _, num := range arr {
        freqMap[num]++ // Increment the count for the element.
    }

    return freqMap // Return the frequency map.
}

func main() {
    // Example array to count frequencies.
    arr := []int{1, 2, 2, 3, 4, 4, 4, 5}

    // Call the function to count frequencies.
    frequencies := countFrequencies(arr)

    // Print the frequencies.
    fmt.Println("Frequencies of elements:")
    for num, count := range frequencies {
        fmt.Printf("Element %d: %d times\n", num, count)
    }
}

How to Run the Program

  1. Install Go on your machine if you haven’t already.
  2. Create a new file named frequency_counter.go.
  3. Copy the above code into the file.
  4. Open a terminal and navigate to the directory where the file is located.
  5. Run the program using the command: go run frequency_counter.go.

Output

When you run the program, you should see an output similar to the following:

Frequencies of elements:
Element 1: 1 times
Element 2: 2 times
Element 3: 1 times
Element 4: 3 times
Element 5: 1 times

Explanation of the Code

  • Importing Packages: The program begins by importing the fmt package, which is essential for formatted input and output.
  • countFrequencies Function: This function accepts a slice of integers and initializes a hash map. It iterates through the slice, incrementing the count for each element in the map.
  • Main Function: Here, we define an example array and call the countFrequencies function to get the frequency map. Finally, it prints out the results.

Conclusion

This program efficiently counts the frequency of each element in an integer array using hashing.
By utilizing a map, we can achieve an average time complexity of O(n) for counting elements,
making this approach suitable for large datasets.

 

Leave a Reply

Your email address will not be published. Required fields are marked *