Go course

MapsCounting Frequencies

Go

Display

Theme

Maps · Test exercise

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{"👍", "❤️", "👍", "😂"}.

  1. Complete hitungReaksi(reaksi []string) map[string]int, which returns how many times each reaction appears. For an empty slice, return an empty map (not nil).
  2. 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 "".
main.go
package main

import "fmt"

func hitungReaksi(reaksi []string) map[string]int {
	// TODO: hitung kemunculan setiap reaksi
	return nil
}

func reaksiTeratas(hitungan map[string]int) string {
	// TODO: cari reaksi terbanyak, seri -> string terkecil
	return ""
}

func main() {
	reaksi := []string{"👍", "❤️", "👍", "😂", "❤️", "👍"}
	h := hitungReaksi(reaksi)
	fmt.Println(h)
	fmt.Println("Teratas:", reaksiTeratas(h))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)