Menu
Coddy logo textTech

まとめ:キー・バリューストレージ

CoddyのGOジャーニー「基礎」セクションの一部 — レッスン 93/109。

challenge icon

チャレンジ

簡単

シンプルな単語カウンターを使って、マップの使用を練習しましょう!

あなたのタスクは、単語のリストの中で各単語が何回出現するかをカウントするプログラムを実装することです。

要件:

  1. カウンターマップに単語を追加する addWord() 関数を完成させてください
  2. 特定の単語のカウントを返す getCount() 関数を完成させてください
  3. カウンターから単語を削除する removeWord() 関数を完成させてください

これは、マップをキーバリューストレージとして使用する方法の簡単な復習です。

注意:一貫性を保つため、出力では単語のカウントがアルファベット順に表示されます。

自分で試してみよう

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)
}

基礎のすべてのレッスン