Go 연습 문제
Word Frequency Counter in Go
Count how often each word appears with a map and print the most common ones.
배울 내용
- strings.Fields
- counts[word]++
- Sorting by count
counts
"the"3"brown"1"dog"1The word is the key, the count is the value
Counting words is a typical job for a map: the word is the key and the number of times it appears is the value.
counts[word]++ works even for a new word, because a missing key reads as 0. The words are then sorted by count, highest first, and alphabetically when the counts are equal, so the output is always the same.
핵심 포인트
- A missing key reads as 0, so ++ just works.
- Sort by count, then by word.
words[:3]keeps the top three.
실행 가능한 Go 예제
Go
main.go
package main
import (
"fmt"
"sort"
"strings"
)
func main() {
text := "the quick brown fox jumps over the lazy dog the end"
counts := map[string]int{}
for _, word := range strings.Fields(text) {
counts[word]++
}
words := make([]string, 0, len(counts))
for word := range counts {
words = append(words, word)
}
sort.Slice(words, func(i, j int) bool {
if counts[words[i]] != counts[words[j]] {
return counts[words[i]] > counts[words[j]]
}
return words[i] < words[j]
})
for _, word := range words[:3] {
fmt.Printf("%s: %d\n", word, counts[word])
}
}
the: 3
brown: 1
dog: 1연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
모든 챌린지