Counting Frequencies
One of the most common uses of a map: counting how many times something appears. Since a key that doesn't exist yet reads as 0, you can increment it directly without any check:
suara := []string{"nasi goreng", "bakso", "nasi goreng", "soto"}
hitungan := make(map[string]int)
for _, menu := range suara {
hitungan[menu]++ // kunci baru otomatis mulai dari 0
}
// map[bakso:1 nasi goreng:2 soto:1]
Finding the largest value
To find the one that appears most often, iterate over the map while keeping track of the "current winner". Careful: because map iteration order is random, if there's a tie the result can differ each time the program runs. The fix is to set a clear tie-breaking rule, such as "pick the one that comes first alphabetically":
juara := ""
maks := 0
for menu, n := range hitungan {
if n > maks || (n == maks && menu < juara) {
juara = menu
maks = n
}
}
Strings can be compared with < and >; the comparison follows byte order, which for plain lowercase letters is the same as alphabetical order.
Task
A chat app stores the emoji reactions on a message as a slice of strings, for example []string{"👍", "❤️", "👍", "😂"}.
- Complete
hitungReaksi(reaksi []string) map[string]int, which returns how many times each reaction appears. For an empty slice, return an empty map (notnil). - Complete
reaksiTeratas(hitungan map[string]int) string, which returns the reaction with the highest count. If there's a tie, pick the one with the smallest string value (compare with<). If the map is empty, return"".