数学:集合差集
本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 64 课,共 66 课。
集合差运算会创建一个新集合,其中包含存在于第一个集合中、但不存在于第二个集合中的元素。
创建两个 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 的方法,它接收两个整数 HashSet(set1 和 set2),并返回一个新的 HashSet,其中包含集合差集(存在于 set1 中但不存在于 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);
}
}
}
// 读取第二行,作为第二个集合
string line2 = Console.ReadLine();
HashSet<int> set2 = new HashSet<int>();
// 检查第二个集合是否为 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 {
// 处理第二个集合以空格分隔的传统输入
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);
}
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程中的所有课
自己练习: C# 在线编译器