Menu
Coddy logo textTech

HashMap מקונן

חלק מהיחידה לוגיקה וזרימת תוכנית במסלול ה-C# של Coddy. שיעור 53 מתוך 66.

HashMap מקונן הוא HashMap שבו הערכים עצמם הם HashMaps. הדבר שימושי לארגון נתונים היררכיים.

צרו HashMap מקונן כדי לאחסן ציונים של תלמידים לפי מקצוע:

// צרו את ה-HashMap החיצוני (תלמיד -> מקצועות)
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();

// צרו HashMap פנימי עבור תלמיד (מקצוע -> ציון)
Dictionary<string, int> alexGrades = new Dictionary<string, int>();

// הוסיפו ציונים ל-HashMap הפנימי
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);

// הוסיפו את ה-HashMap הפנימי ל-HashMap החיצוני
studentGrades.Add("Alex", alexGrades);

גישה לערך מקונן:

// גישה לציון של Alex ב-Math
int mathGrade = studentGrades["Alex"]["Math"]; // מחזיר 90

הוסיפו תלמידה נוספת עם הציונים שלה:

// צור עוד HashMap פנימי
Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);

// הוסף ל-HashMap החיצוני
studentGrades.Add("Sarah", sarahGrades);
challenge icon

אתגר

בינוני

צרו מתודה בשם AddCourseGrade שמקבלת ארבעה ארגומנטים:

  1. מילון מקונן שמייצג את ציוני התלמידים: Dictionary<string, Dictionary<string, int>> grades
  2. שם של תלמיד (מחרוזת)
  3. שם של קורס (מחרוזת)
  4. ציון (מספר שלם)

המתודה צריכה:

  • אם התלמיד אינו קיים במילון, ליצור עבורו רשומה חדשה
  • להוסיף את הקורס ואת הציון לרשומה של התלמיד
  • אם הקורס כבר קיים עבור אותו תלמיד, לעדכן את הציון
  • להדפיס "Added [course] grade for [student]: [grade]" לאחר ההוספה או העדכון

נסו בעצמכם

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Program
{
    public static void AddCourseGrade(Dictionary<string, Dictionary<string, int>> grades, string student, string course, int grade)
    {
        // כתבו את הקוד שלכם כאן
    }
    
    // התעלמו מהקוד הראשי, הוא ממיר מחרוזת ל-HashMap
    static void Main(string[] args)
    {
        // בדקו אם השורה הראשונה עשויה להיות JSON
        string firstLine = Console.ReadLine();
        
        Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();
        string student;
        string course;
        int grade;
        
        // קלט בפורמט JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // נתחו את ציוני התלמידים הקיימים מתוך JSON
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                string studentPattern = @"""([^""]+)""\s*:\s*\{([^\}]+)\}";
                
                MatchCollection studentMatches = Regex.Matches(jsonContent, studentPattern);
                foreach (Match studentMatch in studentMatches)
                {
                    string studentName = studentMatch.Groups[1].Value;
                    string coursesJson = studentMatch.Groups[2].Value;
                    
                    Dictionary<string, int> courseGrades = new Dictionary<string, int>();
                    string coursePattern = @"""([^""]+)""\s*:\s*(\d+)";
                    
                    MatchCollection courseMatches = Regex.Matches(coursesJson, coursePattern);
                    foreach (Match courseMatch in courseMatches)
                    {
                        string courseName = courseMatch.Groups[1].Value;
                        int courseGrade = int.Parse(courseMatch.Groups[2].Value);
                        courseGrades.Add(courseName, courseGrade);
                    }
                    
                    studentGrades.Add(studentName, courseGrades);
                }
                
                // Parse student, course, and grade for the operation
                string studentInput = Console.ReadLine();
                Match studentNameMatch = Regex.Match(studentInput, @"""([^""]+)""");
                student = studentNameMatch.Success ? studentNameMatch.Groups[1].Value : studentInput;
                
                string courseInput = Console.ReadLine();
                Match courseNameMatch = Regex.Match(courseInput, @"""([^""]+)""");
                course = courseNameMatch.Success ? courseNameMatch.Groups[1].Value : courseInput;
                
                grade = int.Parse(Console.ReadLine());
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing JSON input: {ex.Message}");
                return;
            }
        }
        else
        {
            try
            {
                // Traditional input
                student = firstLine;
                course = Console.ReadLine();
                grade = int.Parse(Console.ReadLine());
                
                // Create an example entry
                Dictionary<string, int> johnGrades = new Dictionary<string, int>();
                johnGrades.Add("Math", 88);
                studentGrades.Add("John", johnGrades);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing traditional input: {ex.Message}");
                return;
            }
        }
        
        AddCourseGrade(studentGrades, student, course, grade);
    }
}
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה לוגיקה וזרימת תוכנית

תרגלו בעצמכם: קומפיילר C# אונליין