Math - Intersection of HashSet
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 63/66。
二つの集合の共通部分は、両方の集合に含まれる要素のみを含みます。
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 を返す必要があります(共通部分)。
チートシート
2 つのセットの共通部分は、両方のセットに含まれる要素のみを含みます。
共通部分を求めるには IntersectWith メソッドを使用します:
HashSet<int> set1 = new HashSet<int>() { 1, 2, 3, 4, 5 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5, 6, 7 };
set1.IntersectWith(set2); // set1 は現在 { 3, 4, 5 } を含みますIntersectWith メソッドは元のセットを変更します。元のセットを保持するには、まずコピーを作成します:
HashSet<int> intersection = new HashSet<int>(set1);
intersection.IntersectWith(set2);自分で試してみよう
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) {
// 最初のセット用の最初の行を読み込む
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 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)));
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
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