Menu
Coddy logo textTech

Zagnieżdżona HashMap

Część sekcji Logika i sterowanie przepływem ścieżki C# w Coddy. Lekcja 53 z 66.

Zagnieżdżona mapa HashMap to mapa HashMap, w której wartości same są mapami HashMap. Przydaje się do organizowania danych hierarchicznych.

Utwórz zagnieżdżoną strukturę HashMap do przechowywania ocen uczniów według przedmiotów:

// Utwórz zewnętrzny HashMap (uczeń -> przedmioty)
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();

// Utwórz wewnętrzny HashMap dla ucznia (przedmiot -> ocena)
Dictionary<string, int> alexGrades = new Dictionary<string, int>();

// Dodaj oceny do wewnętrznego HashMap
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);

// Dodaj wewnętrzny HashMap do zewnętrznego HashMap
studentGrades.Add("Alex", alexGrades);

Uzyskaj dostęp do zagnieżdżonej wartości:

// Odczytaj ocenę Alexa z Math
int mathGrade = studentGrades["Alex"]["Math"]; // Zwraca 90

Dodaj kolejnego ucznia wraz z jego ocenami:

// Utwórz kolejną wewnętrzną HashMap
Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);

// Dodaj do zewnętrznej HashMap
studentGrades.Add("Sarah", sarahGrades);
challenge icon

Wyzwanie

Średni

Utwórz metodę o nazwie AddCourseGrade, która przyjmuje cztery argumenty:

  1. Zagnieżdżony słownik reprezentujący oceny uczniów: Dictionary<string, Dictionary<string, int>> grades
  2. Imię i nazwisko ucznia (string)
  3. Nazwę kursu (string)
  4. Ocenę (int)

Metoda powinna:

  • Jeśli ucznia nie ma w słowniku, utworzyć dla niego nowy wpis
  • Dodać kurs i ocenę do rekordu ucznia
  • Jeśli kurs już istnieje dla tego ucznia, zaktualizować ocenę
  • Po dodaniu lub zaktualizowaniu wypisać "Added [course] grade for [student]: [grade]"

Spróbuj swoich sił

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)
    {
        // Wpisz tutaj swój kod
    }
    
    // Zignoruj kod główny, który przekształca ciąg znaków w HashMap
    static void Main(string[] args)
    {
        // Sprawdź, czy pierwsza linia może zawierać JSON
        string firstLine = Console.ReadLine();
        
        Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();
        string student;
        string course;
        int grade;
        
        // Dane wejściowe w formacie JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Odczytaj istniejące oceny uczniów z 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 iconSprawdź się

Ta lekcja zawiera krótki quiz. Zacznij lekcję, żeby na niego odpowiedzieć i śledzić swoje postępy.

Wszystkie lekcje w sekcji Logika i sterowanie przepływem

Poćwicz samodzielnie: Kompilator C# online