Menu
CoddyTech

HashMap Bersarang

Termasuk bagian Logika dan Alur dalam perjalanan C# di Coddy. Pelajaran 53 dari 66.

HashMap bertingkat adalah HashMap yang nilainya berupa HashMap. Ini berguna untuk mengatur data hierarkis.

Buat HashMap bersarang untuk menyimpan nilai siswa berdasarkan mata pelajaran:

// Buat HashMap luar (siswa -> mata pelajaran)
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();

// Buat HashMap dalam untuk seorang siswa (mata pelajaran -> nilai)
Dictionary<string, int> alexGrades = new Dictionary<string, int>();

// Tambahkan nilai ke HashMap dalam
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);

// Tambahkan HashMap dalam ke HashMap luar
studentGrades.Add("Alex", alexGrades);

Akses nilai yang bersarang:

// Akses nilai Math milik Alex
int mathGrade = studentGrades["Alex"]["Math"]; // Mengembalikan 90

Tambahkan siswa lain beserta nilainya:

// Buat HashMap bagian dalam lainnya
Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);

// Tambahkan ke HashMap bagian luar
studentGrades.Add("Sarah", sarahGrades);
challenge icon

Tantangan

Sedang

Buat method bernama AddCourseGrade yang menerima empat argumen:

  1. Dictionary bertingkat yang merepresentasikan nilai siswa: Dictionary<string, Dictionary<string, int>> grades
  2. Nama siswa (string)
  3. Nama kursus (string)
  4. Nilai (int)

Method tersebut harus:

  • Jika siswa belum ada di dictionary, buat entri baru untuk siswa tersebut
  • Tambahkan kursus dan nilai ke catatan siswa
  • Jika kursus sudah ada untuk siswa tersebut, perbarui nilainya
  • Cetak "Added [course] grade for [student]: [grade]" setelah menambahkan atau memperbarui

Coba sendiri

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)
    {
        // Tulis kodemu di sini
    }
    
    // Abaikan kode utama, kode ini mengubah string menjadi HashMap
    static void Main(string[] args)
    {
        // Periksa apakah baris pertama mungkin berisi JSON
        string firstLine = Console.ReadLine();
        
        Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();
        string student;
        string course;
        int grade;
        
        // Input berformat JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Uraikan nilai siswa yang sudah ada dari 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 iconUji dirimu

Pelajaran ini berisi kuis singkat. Mulai pelajarannya untuk menjawab kuis dan melacak progresmu.

Semua pelajaran di Logika dan Alur

Latihan sendiri: Compiler C# online