Menu
Coddy logo textTech

Math - Set Difference

Parte de la sección Lógica y Flujo del Journey de C# de Coddy — lección 64 de 66.

La operación de diferencia de conjuntos crea un nuevo conjunto con elementos que existen en el primer conjunto pero no en el segundo conjunto.

Crea dos HashSets:

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

Agregar elementos a ambos conjuntos:

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

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

Calcular la diferencia (elementos en set1 pero no en set2):

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

Después de ejecutar el código anterior, el conjunto diferencia contiene:

["Apple", "Cherry"]
challenge icon

Desafío

Fácil

Crea un método llamado GetSetDifference que tome dos HashSets de enteros (set1 y set2) y devuelva un nuevo HashSet que contenga la diferencia de conjuntos (elementos en set1 que no están en set2).

Hoja de referencia

La diferencia de conjuntos crea un nuevo conjunto con elementos que existen en el primer conjunto pero no en el segundo conjunto.

Crear HashSets:

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

Calcular la diferencia usando ExceptWith():

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

Pruébalo tú mismo

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) {
        // Escribe tu código aquí
        return null;
    }
    
    static void Main(string[] args) {
        // Leer la primera línea para el primer conjunto
        string line1 = Console.ReadLine();
        HashSet<int> set1 = new HashSet<int>();
        
        // Verificar si el primer conjunto está en formato de array JSON
        if (line1 != null && line1.StartsWith("[") && line1.EndsWith("]")) {
            try {
                // Extraer el contenido entre corchetes
                string arrayContent = line1.Substring(1, line1.Length - 2);
                
                // Intentar analizar el contenido del array JSON
                string[] values = Regex.Split(arrayContent, @",\s*");
                foreach (string value in values) {
                    // Eliminar las comillas si están presentes
                    string cleanValue = value.Trim();
                    if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\"")) {
                        cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
                    }
                    
                    // Analizar como entero y agregar al conjunto
                    if (int.TryParse(cleanValue, out int num)) {
                        set1.Add(num);
                    }
                }
            }
            catch (Exception ex) {
                Console.WriteLine($"Error parsing first set: {ex.Message}");
                return;
            }
        }
        else {
            // Procesar entrada tradicional separada por espacios para el primer conjunto
            string[] set1Input = line1.Split(' ');
            foreach (string item in set1Input) {
                if (int.TryParse(item, out int num)) {
                    set1.Add(num);
                }
            }
        }
        
        // Leer la segunda línea para el segundo conjunto
        string line2 = Console.ReadLine();
        HashSet<int> set2 = new HashSet<int>();
        
        // Verificar si el segundo conjunto está en formato de array JSON
        if (line2 != null && line2.StartsWith("[") && line2.EndsWith("]")) {
            try {
                // Extraer el contenido entre corchetes
                string arrayContent = line2.Substring(1, line2.Length - 2);
                
                // Intentar analizar el contenido del array JSON
                string[] values = Regex.Split(arrayContent, @",\s*");
                foreach (string value in values) {
                    // Eliminar las comillas si están presentes
                    string cleanValue = value.Trim();
                    if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\"")) {
                        cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
                    }
                    
                    // Analizar como entero y agregar al conjunto
                    if (int.TryParse(cleanValue, out int num)) {
                        set2.Add(num);
                    }
                }
            }
            catch (Exception ex) {
                Console.WriteLine($"Error parsing second set: {ex.Message}");
                return;
            }
        }
        else {
            // Procesar entrada tradicional separada por espacios para el segundo conjunto
            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);
        
        // Imprimir resultado
        List<int> sortedResult = new List<int>(difference);
        sortedResult.Sort();
        foreach (int item in sortedResult) {
            Console.WriteLine(item);
        }
    }
}
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Lógica y Flujo