// Week 11 – Counting frequencies with the built-in map (hash table)
// Run: go run ./w11/wordcount
package main

import (
	"fmt"
	"maps"
	"slices"
	"strings"
)

func main() {
	text := "the quick brown fox jumps over the lazy dog the fox runs and the dog sleeps"
	freq := map[string]int{}
	for _, w := range strings.Fields(text) {
		freq[w]++ // a missing key has the value 0 (zero value)
	}
	fmt.Println("frequencies:", freq) // fmt prints the map keys sorted

	// Top 3: sorting the keys by frequency
	keys := slices.Collect(maps.Keys(freq))
	slices.SortFunc(keys, func(a, b string) int {
		if freq[a] != freq[b] {
			return freq[b] - freq[a]
		}
		return strings.Compare(a, b)
	})
	fmt.Print("top 3: ")
	for _, k := range keys[:3] {
		fmt.Printf("%s=%d ", k, freq[k])
	}
	fmt.Println()

	v, ok := freq["cat"] // "comma ok": distinguishes a missing key from the value 0
	fmt.Println(`freq["cat"] =`, v, ", present?", ok)
	delete(freq, "the")
	fmt.Println(`after delete len =`, len(freq))
}
