Math - Union of HashSets
Part of the Logic & Flow section of Coddy's C# journey — lesson 62 of 66.
The Union operation combines two sets to create a new set that contains all elements from both sets, without duplicates.
Create two HashSets:
HashSet<int> set1 = new HashSet<int>() { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5 };Use the Union method to combine the sets:
HashSet<int> unionSet = new HashSet<int>(set1);
unionSet.UnionWith(set2);After executing the above code, the unionSet contains:
[1, 2, 3, 4, 5]Notice that the element 3 appears only once in the result, as HashSet doesn't allow duplicates.
Challenge
EasyCreate a method named UnionSets that takes two HashSets of integers as parameters and returns a new HashSet containing the union of both sets.
The input reading and output printing are already handled for you — focus on implementing the UnionSets method body.
Cheat sheet
The Union operation combines two sets to create a new set that contains all elements from both sets, without duplicates.
Create two HashSets:
HashSet<int> set1 = new HashSet<int>() { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5 };Use the Union method to combine the sets:
HashSet<int> unionSet = new HashSet<int>(set1);
unionSet.UnionWith(set2);The result contains all unique elements from both sets. Duplicates are automatically removed.
Try it yourself
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
public static HashSet<int> UnionSets(HashSet<int> set1, HashSet<int> set2)
{
// Write your code here
return null;
}
static void Main(string[] args)
{
// Read first line to check format 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 num in input1)
{
if (int.TryParse(num, out int parsedNum))
{
set1.Add(parsedNum);
}
}
}
// Read second line to check format 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 num in input2)
{
if (int.TryParse(num, out int parsedNum))
{
set2.Add(parsedNum);
}
}
}
// Get union and print result
HashSet<int> unionSet = UnionSets(set1, set2);
Console.WriteLine(string.Join(" ", unionSet.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