Menu
Coddy logo textTech

요약 - 키-값 저장소

Coddy GO 여정의 기초 섹션에 포함된 레슨 — 109개 중 93번째.

challenge icon

챌린지

쉬움

간단한 단어 카운터를 통해 맵(map) 사용법을 연습해 봅시다!

여러분의 작업은 단어 목록에서 각 단어가 몇 번 나타나는지 세는 프로그램을 구현하는 것입니다.

요구 사항:

  1. 카운터 맵에 단어를 추가하는 addWord() 함수를 완성하세요.
  2. 특정 단어의 개수를 반환하는 getCount() 함수를 완성하세요.
  3. 카운터에서 단어를 제거하는 removeWord() 함수를 완성하세요.

이것은 맵을 키-값(key-value) 저장소로 사용하는 방법에 대한 간단한 요약입니다.

참고: 일관성을 위해 출력 결과는 단어 개수를 알파벳 순서로 표시합니다.

직접 해보기

package main

import (
	"fmt"
	"sort"
)

// addWord는 카운터 맵에 단어를 추가합니다
func addWord(counter map[string]int, word string) {
	// 여기에 코드를 작성하세요
}

// getCount는 특정 단어의 개수를 반환합니다
func getCount(counter map[string]int, word string) int {
	// 여기에 코드를 작성하세요
	return 0
}

// removeWord는 카운터에서 단어를 제거합니다
// 단어를 찾아 제거한 경우 true를 반환합니다
func removeWord(counter map[string]int, word string) bool {
	// 여기에 코드를 작성하세요
	return false
}

// printWordCounts는 단어 개수를 알파벳 순서로 출력합니다
func printWordCounts(counter map[string]int) {
	// 맵에서 모든 키(단어)를 가져옵니다
	words := make([]string, 0, len(counter))
	for word := range counter {
		words = append(words, word)
	}
	
	// 단어를 알파벳 순으로 정렬합니다
	sort.Strings(words)
	
	// 정렬된 순서대로 각 단어와 개수를 출력합니다
	for _, word := range words {
		fmt.Printf("%s: %d\n", word, counter[word])
	}
}

func main() {
	// 단어 카운터 맵을 초기화합니다
	wordCounter := make(map[string]int)
	
	// 몇 가지 단어를 추가합니다
	words := []string{"apple", "banana", "apple", "orange", "banana", "apple"}
	for _, word := range words {
		addWord(wordCounter, word)
	}
	
	// 단어 개수를 출력합니다
	fmt.Println("Word counts:")
	printWordCounts(wordCounter)
	
	// 특정 단어의 개수를 가져옵니다
	fmt.Printf("\nCount for 'apple': %d\n", getCount(wordCounter, "apple"))
	fmt.Printf("Count for 'grape': %d\n", getCount(wordCounter, "grape"))
	
	// 단어를 제거합니다
	removed := removeWord(wordCounter, "banana")
	fmt.Printf("\nRemoved 'banana': %v\n", removed)
	
	// 존재하지 않는 단어 제거를 시도합니다
	removed = removeWord(wordCounter, "grape")
	fmt.Printf("Removed 'grape': %v\n", removed)
	
	// 최종 단어 개수를 출력합니다
	fmt.Println("\nFinal word counts:")
	printWordCounts(wordCounter)
}

기초의 모든 레슨