数学 - HashSetの共通部分
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部。レッスン 63/66。
2つの集合の共通部分には、両方の集合に含まれる要素だけが含まれます。
2つのHashSetを作成します。
HashSet<int> set1 = new HashSet<int>() { 1, 2, 3, 4, 5 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5, 6, 7 };共通部分を見つけるには、IntersectWith メソッドを使います。
set1.IntersectWith(set2);このコードを実行すると、set1には次の値が含まれます。
{ 3, 4, 5 }IntersectWithメソッドは、呼び出し元のセットを変更し、両方のセットに存在する要素だけを残します。
元のセットを変更せずに、積集合を持つ新しいセットを作成するには、次のようにします。
HashSet<int> intersection = new HashSet<int>(set1);
intersection.IntersectWith(set2);チャレンジ
中級FindCommonElementsという名前のメソッドを作成します。このメソッドは次の2つの引数を受け取ります。
- 整数のHashSet(set1)
- 整数のHashSet(set2)
このメソッドは、両方のセットに含まれる要素(共通部分)のみを含む新しいHashSetを返します。
自分で試してみよう
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program {
public static HashSet<int> FindCommonElements(HashSet<int> set1, HashSet<int> set2) {
// ここにコードを記述する
return null;
}
static void Main(string[] args) {
// 1つ目の集合用に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 s in input1) {
if (int.TryParse(s, out int num)) {
set1.Add(num);
}
}
}
// 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 s in input2) {
if (int.TryParse(s, out int num)) {
set2.Add(num);
}
}
}
// 共通する要素を見つける
HashSet<int> common = FindCommonElements(set1, set2);
// 結果を表示する(ソート済み)
Console.WriteLine(string.Join(" ", common.OrderBy(x => x)));
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
自分で練習してみよう: C#オンラインコンパイラ