Math - Union of HashSets
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 が1回だけ表示されていることに注意してください。HashSet は重複を許可しません。
チャレンジ
簡単UnionSets という名前のメソッドを作成してください。このメソッドは、2 つの整数の HashSet をパラメータとして受け取り、両方のセットの和集合を含む新しい HashSet を返します。
入力の読み取りと出力の印刷はすでにあなたのために処理されています — UnionSets メソッドの本体を実装することに集中してください。
チートシート
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);結果には両方のセットからすべての一意の要素が含まれ、重複は自動的に削除されます。
自分で試してみよう
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)
{
// 最初のセットの形式を確認するために最初の行を読み取る
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)));
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety9HashMap Part 1
What is a HashMap?Declare a HashMapCheck If Key ExistsAccessing ValuesModifying DictionariesRecap - HashMap12HashSet Part 2
Math - Union of HashSetsMath - Intersection of HashSetMath - Set DifferenceMath - Symmetric DifferenceIterating Over Sets