Menu
Coddy logo textTech

Nested HashMap

CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 53/66。

ネストされた HashMap は、値自体が HashMap である HashMap です。これは階層的なデータを整理するのに便利です。

科目ごとの学生の成績を格納するためのネストされた HashMap を作成します:

// 外側の HashMap を作成 (student -> subjects)
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();

// 学生のための内側の HashMap を作成 (subject -> grade)
Dictionary<string, int> alexGrades = new Dictionary<string, int>();

// 内側の HashMap に成績を追加
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);

// 内側の HashMap を外側の HashMap に追加
studentGrades.Add("Alex", alexGrades);

ネストされた値にアクセス:

// Access Alex's Math grade
int mathGrade = studentGrades["Alex"]["Math"]; // Returns 90

もう一人の生徒とその成績を追加:

// Create another inner HashMap
Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);

// Add to the outer HashMap
studentGrades.Add("Sarah", sarahGrades);
challenge icon

チャレンジ

中級

AddCourseGrade という名前のメソッドを作成し、4つの引数を受け取るようにします:

  1. 学生の成績を表すネストされた Dictionary: Dictionary<string, Dictionary<string, int>> grades
  2. 学生名 (string)
  3. コース名 (string)
  4. 成績 (int)

このメソッドは次のことを行うべきです:

  • 辞書に学生が存在しない場合、新しいエントリを作成する
  • 学生の記録にコースと成績を追加する
  • その学生のコースがすでに存在する場合、成績を更新する
  • 追加/更新後に "Added [course] grade for [student]: [grade]" を出力する

チートシート

ネストされた HashMap は、値自体が HashMap である HashMap で、階層的なデータを整理するのに便利です。

ネストされた HashMap を作成:

Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();

// Create inner HashMap
Dictionary<string, int> alexGrades = new Dictionary<string, int>();
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);

// Add to outer HashMap
studentGrades.Add("Alex", alexGrades);

ネストされた値にアクセス:

int mathGrade = studentGrades["Alex"]["Math"]; // Returns 90

別のエントリを追加:

Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);
studentGrades.Add("Sarah", sarahGrades);

自分で試してみよう

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腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

ロジックとフローのすべてのレッスン