Menu
Coddy logo textTech

Math - Set Difference

Part of the Logic & Flow section of Coddy's C# journey — lesson 64 of 66.

The Set Difference operation creates a new set with elements that exist in the first set but not in the second set.

Create two HashSets:

HashSet<string> set1 = new HashSet<string>();
HashSet<string> set2 = new HashSet<string>();

Add elements to both sets:

set1.Add("Apple");
set1.Add("Banana");
set1.Add("Cherry");

set2.Add("Banana");
set2.Add("Kiwi");

Calculate the difference (elements in set1 but not in set2):

HashSet<string> difference = new HashSet<string>(set1);
difference.ExceptWith(set2);

After executing the above code, the difference set contains:

["Apple", "Cherry"]
challenge icon

Challenge

Easy

Create a method named GetSetDifference that takes two HashSets of integers (set1 and set2) and returns a new HashSet containing the set difference (elements in set1 that are not in set2).

Cheat sheet

Set Difference creates a new set with elements that exist in the first set but not in the second set.

Create HashSets:

HashSet<string> set1 = new HashSet<string>();
HashSet<string> set2 = new HashSet<string>();

Calculate the difference using ExceptWith():

HashSet<string> difference = new HashSet<string>(set1);
difference.ExceptWith(set2);

Try it yourself

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) {
        // 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[] set1Input = line1.Split(' ');
            foreach (string item in set1Input) {
                if (int.TryParse(item, 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[] set2Input = line2.Split(' ');
            foreach (string item in set2Input) {
                if (int.TryParse(item, out int num)) {
                    set2.Add(num);
                }
            }
        }
        
        HashSet<int> difference = GetSetDifference(set1, set2);
        
        // Print result
        List<int> sortedResult = new List<int>(difference);
        sortedResult.Sort();
        foreach (int item in sortedResult) {
            Console.WriteLine(item);
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow