Menu
Coddy logo textTech
flag Ar iconالعربيةdown icon

ملخص - تخزين (مفتاح-قيمة)

جزء من قسم Fundamentals في رحلة GO على Coddy — الدرس 93 من 109.

challenge icon

التحدي

سهل

دعونا نتدرب على استخدام الخرائط (maps) مع عداد كلمات بسيط!

مهمتك هي تنفيذ برنامج يقوم بعد عدد مرات ظهور كل كلمة في قائمة من الكلمات.

المتطلبات:

  1. أكمل دالة addWord() التي تضيف كلمة إلى خريطة العداد
  2. أكمل دالة getCount() التي تعيد عدد مرات ظهور كلمة معينة
  3. أكمل دالة removeWord() التي تحذف كلمة من العداد

هذا ملخص بسيط لكيفية استخدام الخرائط (maps) كمخزن للمفاتيح والقيم (key-value storage).

ملاحظة: سيتم عرض أعداد الكلمات بترتيب أبجدي لضمان الاتساق.

جرّب بنفسك

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

جميع دروس Fundamentals