Math - Set Difference
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 64/66。
Set Difference 操作は、最初のセットに存在し、2番目のセットに存在しない要素で構成される新しいセットを作成します。
2 つの HashSet を作成:
HashSet<string> set1 = new HashSet<string>();
HashSet<string> set2 = new HashSet<string>();両方のセットに要素を追加:
set1.Add("Apple");
set1.Add("Banana");
set1.Add("Cherry");
set2.Add("Banana");
set2.Add("Kiwi");差集合を計算(set1 に含まれるが set2 に含まれない要素):
HashSet<string> difference = new HashSet<string>(set1);
difference.ExceptWith(set2);上記のコードを実行した後、差集合には次のものが含まれています:
["Apple", "Cherry"]チャレンジ
簡単GetSetDifference という名前のメソッドを作成してください。このメソッドは、整数型の 2 つの HashSet(set1 と set2)を受け取り、集合差分(set1 にあり set2 にない要素)を含む新しい HashSet を返します。
チートシート
差集合は、最初のセットに存在するが 2 番目のセットには存在しない要素で新しいセットを作成します。
HashSet を作成:
HashSet<string> set1 = new HashSet<string>();
HashSet<string> set2 = new HashSet<string>();ExceptWith() を使用して差分を計算:
HashSet<string> difference = new HashSet<string>(set1);
difference.ExceptWith(set2);自分で試してみよう
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program {
public static HashSet<int> GetSetDifference(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[] set1Input = line1.Split(' ');
foreach (string item in set1Input) {
if (int.TryParse(item, 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[] set2Input = line2.Split(' ');
foreach (string item in set2Input) {
if (int.TryParse(item, out int num)) {
set2.Add(num);
}
}
}
HashSet<int> difference = GetSetDifference(set1, set2);
// 結果を出力
List<int> sortedResult = new List<int>(difference);
sortedResult.Sort();
foreach (int item in sortedResult) {
Console.WriteLine(item);
}
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
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