数学 - HashSetの和集合
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部。レッスン 62/66。
和集合演算は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 では重複が許可されないためです。
チャレンジ
簡単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>();
// 1つ目の集合が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
{
// 1つ目の集合について、従来のスペース区切りの入力を処理する
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)));
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
自分で練習してみよう: C#オンラインコンパイラ