Menu
Coddy logo textTech

数学 - HashSetの和集合

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

Union 操作は、2つの集合を組み合わせて、重複なしですべての要素を含む新しい集合を作成します。

2つの HashSet を作成します:

HashSet<int> set1 = new HashSet<int>() { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5 };

Union メソッドを使用して集合を結合します:

HashSet<int> unionSet = new HashSet<int>(set1);
unionSet.UnionWith(set2);

上記のコードを実行すると、unionSet には次の内容が含まれます:

[1, 2, 3, 4, 5]

要素 3 は結果に一度しか現れないことに注意してください。HashSet では重複が許可されないためです。

challenge icon

チャレンジ

簡単

2 つの整数の HashSet をパラメーターとして受け取り、両方の集合の和集合を含む新しい HashSet を返す、UnionSets という名前のメソッドを作成してください。

入力の読み取りと出力の表示はすでに処理されています。UnionSets メソッド本体の実装に集中してください。

自分で試してみよう

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

class Program
{
    public static HashSet<int> UnionSets(HashSet<int> set1, HashSet<int> set2)
    {
        // ここにコードを書いてください
        return null;
    }
    
    static void Main(string[] args)
    {
        // 最初のセットの形式を確認するために1行目を読み取る
        string line1 = Console.ReadLine();
        HashSet<int> set1 = new HashSet<int>();
        
        // 最初のセットがJSON配列形式かどうかを確認する
        if (line1 != null && line1.StartsWith("[") && line1.EndsWith("]"))
        {
            try
            {
                // 角括弧の間の内容を抽出する
                string arrayContent = line1.Substring(1, line1.Length - 2);
                
                // JSON配列の内容を解析する
                string[] values = Regex.Split(arrayContent, @",\s*");
                foreach (string value in values)
                {
                    // 引用符があれば削除する
                    string cleanValue = value.Trim();
                    if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\""))
                    {
                        cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
                    }
                    
                    // 整数として解析してセットに追加する
                    if (int.TryParse(cleanValue, out int num))
                    {
                        set1.Add(num);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing first set: {ex.Message}");
                return;
            }
        }
        else
        {
            // 最初のセットの従来のスペース区切り入力を処理する
            string[] input1 = line1.Split(' ');
            foreach (string num in input1)
            {
                if (int.TryParse(num, out int parsedNum))
                {
                    set1.Add(parsedNum);
                }
            }
        }
        
        // 2番目のセットの形式を確認するために2行目を読み取る
        string line2 = Console.ReadLine();
        HashSet<int> set2 = new HashSet<int>();
        
        // 2番目のセットがJSON配列形式かどうかを確認する
        if (line2 != null && line2.StartsWith("[") && line2.EndsWith("]"))
        {
            try
            {
                // 角括弧の間の内容を抽出する
                string arrayContent = line2.Substring(1, line2.Length - 2);
                
                // JSON配列の内容を解析する
                string[] values = Regex.Split(arrayContent, @",\s*");
                foreach (string value in values)
                {
                    // 引用符があれば削除する
                    string cleanValue = value.Trim();
                    if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\""))
                    {
                        cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
                    }
                    
                    // 整数として解析してセットに追加する
                    if (int.TryParse(cleanValue, out int num))
                    {
                        set2.Add(num);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing second set: {ex.Message}");
                return;
            }
        }
        else
        {
            // 2番目のセットの従来のスペース区切り入力を処理する
            string[] input2 = line2.Split(' ');
            foreach (string num in input2)
            {
                if (int.TryParse(num, out int parsedNum))
                {
                    set2.Add(parsedNum);
                }
            }
        }
        
        // 和集合を取得して結果を出力する
        HashSet<int> unionSet = UnionSets(set1, set2);
        Console.WriteLine(string.Join(" ", unionSet.OrderBy(x => x)));
    }
}
quiz icon腕試し

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

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

自分で練習してみよう: C#オンラインコンパイラ