Math - Symmetric Difference
Part of the Logic & Flow section of Coddy's C# journey — lesson 65 of 66.
The symmetric difference of two sets contains elements that are in either of the sets, but not in their intersection (elements that appear in exactly one of the sets).
Create two HashSet objects:
HashSet<int> set1 = new HashSet<int>() { 1, 2, 3, 4 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5, 6 };Create a new HashSet for the result:
HashSet<int> symmetricDifference = new HashSet<int>(set1);Use the SymmetricExceptWith method to compute the symmetric difference:
symmetricDifference.SymmetricExceptWith(set2);After executing the above code, the symmetricDifference set contains:
{ 1, 2, 5, 6 }The elements 3 and 4 are in both sets, so they don't appear in the symmetric difference.
Challenge
EasyCreate a method named FindSymmetricDifference that takes two arguments:
- A HashSet of integers (
set1) - A HashSet of integers (
set2)
The method should return a new HashSet<int> containing the symmetric difference of the two sets. The rest of the program (reading input, sorting, and printing results) is already provided for you.
Cheat sheet
The symmetric difference of two sets contains elements that are in either set, but not in both (elements that appear in exactly one of the sets).
To find the symmetric difference, create a new HashSet from one set and use SymmetricExceptWith():
HashSet<int> set1 = new HashSet<int>() { 1, 2, 3, 4 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5, 6 };
HashSet<int> symmetricDifference = new HashSet<int>(set1);
symmetricDifference.SymmetricExceptWith(set2);Result: { 1, 2, 5, 6 } (elements 3 and 4 are excluded because they appear in both sets)
Try it yourself
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static HashSet<int> FindSymmetricDifference(HashSet<int> set1, HashSet<int> set2)
{
// Write your code here
}
static void Main(string[] args)
{
string[] input1 = Console.ReadLine().Split(',');
string[] input2 = Console.ReadLine().Split(',');
HashSet<int> set1 = new HashSet<int>();
HashSet<int> set2 = new HashSet<int>();
foreach (string s in input1)
{
if (int.TryParse(s.Trim(), out int num))
{
set1.Add(num);
}
}
foreach (string s in input2)
{
if (int.TryParse(s.Trim(), out int num))
{
set2.Add(num);
}
}
HashSet<int> result = FindSymmetricDifference(set1, set2);
// Print the result in ascending order
int[] orderedResult = result.OrderBy(x => x).ToArray();
foreach (int num in orderedResult)
{
Console.WriteLine(num);
}
}
}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