Math - Intersection of HashSet
Part of the Logic & Flow section of Coddy's C# journey — lesson 63 of 66.
The intersection of two sets contains only the elements that appear in both sets.
Create two HashSets:
HashSet<int> set1 = new HashSet<int>() { 1, 2, 3, 4, 5 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5, 6, 7 };To find the intersection, use the IntersectWith method:
set1.IntersectWith(set2);After executing this code, set1 will contain:
{ 3, 4, 5 }The IntersectWith method modifies the set it's called on, keeping only elements that exist in both sets.
To create a new set with the intersection without modifying the original sets, you can:
HashSet<int> intersection = new HashSet<int>(set1);
intersection.IntersectWith(set2);Challenge
MediumCreate a method named FindCommonElements that takes two arguments:
- A HashSet of integers (set1)
- A HashSet of integers (set2)
The method should return a new HashSet containing only the elements that appear in both sets (the intersection).
Cheat sheet
The intersection of two sets contains only elements that appear in both sets.
Use IntersectWith method to find intersection:
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 now contains { 3, 4, 5 }The IntersectWith method modifies the original set. To preserve the original set, create a copy first:
HashSet<int> intersection = new HashSet<int>(set1);
intersection.IntersectWith(set2);Try it yourself
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) {
// Write your code here
return null;
}
static void Main(string[] args) {
// Read first line for first set
string line1 = Console.ReadLine();
HashSet<int> set1 = new HashSet<int>();
// Check if first set is in JSON array format
if (line1 != null && line1.StartsWith("[") && line1.EndsWith("]")) {
try {
// Extract content between square brackets
string arrayContent = line1.Substring(1, line1.Length - 2);
// Try to parse the JSON array content
string[] values = Regex.Split(arrayContent, @",\s*");
foreach (string value in values) {
// Remove any quotes if present
string cleanValue = value.Trim();
if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\"")) {
cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
}
// Parse as integer and add to set
if (int.TryParse(cleanValue, out int num)) {
set1.Add(num);
}
}
}
catch (Exception ex) {
Console.WriteLine($"Error parsing first set: {ex.Message}");
return;
}
}
else {
// Process traditional space-separated input for first set
string[] input1 = line1.Split();
foreach (string s in input1) {
if (int.TryParse(s, out int num)) {
set1.Add(num);
}
}
}
// Read second line for second set
string line2 = Console.ReadLine();
HashSet<int> set2 = new HashSet<int>();
// Check if second set is in JSON array format
if (line2 != null && line2.StartsWith("[") && line2.EndsWith("]")) {
try {
// Extract content between square brackets
string arrayContent = line2.Substring(1, line2.Length - 2);
// Try to parse the JSON array content
string[] values = Regex.Split(arrayContent, @",\s*");
foreach (string value in values) {
// Remove any quotes if present
string cleanValue = value.Trim();
if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\"")) {
cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
}
// Parse as integer and add to set
if (int.TryParse(cleanValue, out int num)) {
set2.Add(num);
}
}
}
catch (Exception ex) {
Console.WriteLine($"Error parsing second set: {ex.Message}");
return;
}
}
else {
// Process traditional space-separated input for second set
string[] input2 = line2.Split();
foreach (string s in input2) {
if (int.TryParse(s, out int num)) {
set2.Add(num);
}
}
}
// Find common elements
HashSet<int> common = FindCommonElements(set1, set2);
// Print result (sorted)
Console.WriteLine(string.Join(" ", common.OrderBy(x => x)));
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
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