Recap - Word Frequency Counter
Part of the Logic & Flow section of Coddy's GO journey — lesson 30 of 68.
Challenge
EasyBuild a text analysis tool that counts word frequencies in a document. This challenge demonstrates how maps excel at aggregating data by tracking how many times each unique word appears in a piece of text.
You will receive two inputs:
- A string representing the text to analyze (e.g.,
"the quick brown fox jumps over the lazy dog the fox is quick") - A string representing the minimum frequency threshold (e.g.,
"2")
Important: The input text may contain spaces, so you must read the full line using bufio.NewReader with ReadString('\n') or a bufio.Scanner — do not use fmt.Scanln for the text input, as it stops reading at the first space.
Your task is to:
- Create a function called
countWordsthat takes a string of text and returns amap[string]intwhere:- Keys are individual words (strings)
- Values are the frequency count of each word (integers)
- Parse the input text by splitting it into individual words using
strings.Fields(which splits on any whitespace) - Count the frequency of each word in the text:
- Convert all words to lowercase for consistent counting
- For each word, increment its count in the map
- If a word doesn't exist in the map yet, it will start at 0 and be incremented to 1
- Filter the results to show only words that appear at least as many times as the threshold
- Display the results in the following format:
- Header:
"Word Frequency Analysis:" - For each qualifying word:
"[word]: [count]" - Display words in alphabetical order
- Header:
- Calculate and display summary statistics:
"Total unique words: [total_unique_count]""Words above threshold: [filtered_count]""Most frequent word: [word] ([count] times)"
For example, given the input text "hello hello world" and threshold "2", the output should be:
Word Frequency Analysis: hello: 2 Total unique words: 2 Words above threshold: 1 Most frequent word: hello (2 times)
Use the bufio package to read full lines of input, the strings package to split the text and convert to lowercase, the strconv package to convert the threshold string to an integer, and the sort package to sort the words alphabetically. This challenge demonstrates how maps provide an elegant solution for counting and aggregating data, with the zero-value behavior of maps making the counting logic simple and efficient.
Try it yourself
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
// Read the full line of text (including spaces)
scanner.Scan()
text := scanner.Text()
// Read the threshold value
scanner.Scan()
thresholdStr := scanner.Text()
// Convert threshold to integer
threshold, _ := strconv.Atoi(thresholdStr)
// TODO: Write your code below
// 1. Create the countWords function that returns a map[string]int
// Hint: use strings.Fields and strings.ToLower to split and normalize words
// 2. Use the function to count word frequencies
// 3. Filter words that appear at least 'threshold' times
// 4. Sort the filtered words alphabetically and display them
// 5. Calculate and display summary statistics
_ = text
_ = threshold
fmt.Println("Word Frequency Analysis:")
}All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors