Menu
Coddy logo textTech

Math - Union of HashSets

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

La operación de unión combina dos conjuntos para crear un nuevo conjunto que contiene todos los elementos de ambos conjuntos, sin duplicados.

Crear dos HashSets:

HashSet<int> set1 = new HashSet<int>() { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5 };

Usa el método Union para combinar los conjuntos:

HashSet<int> unionSet = new HashSet<int>(set1);
unionSet.UnionWith(set2);

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

[1, 2, 3, 4, 5]

Nota que el elemento 3 aparece solo una vez en el resultado, ya que HashSet no permite duplicados.

challenge icon

Desafío

Fácil

Crea un método llamado UnionSets que tome dos HashSets de enteros como parámetros y devuelva un nuevo HashSet que contenga la unión de ambos conjuntos.

La lectura de entrada y la impresión de salida ya están manejadas para ti — enfócate en implementar el cuerpo del método UnionSets.

Hoja de referencia

La operación Union combina dos conjuntos para crear un nuevo conjunto que contiene todos los elementos de ambos conjuntos, sin duplicados.

Cree dos HashSets:

HashSet<int> set1 = new HashSet<int>() { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5 };

Use el método Union para combinar los conjuntos:

HashSet<int> unionSet = new HashSet<int>(set1);
unionSet.UnionWith(set2);

El resultado contiene todos los elementos únicos de ambos conjuntos. Los duplicados se eliminan automáticamente.

Pruébalo tú mismo

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)
    {
        // Escribe tu código aquí
        return null;
    }
    
    static void Main(string[] args)
    {
        // Leer la primera línea para verificar el formato del 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[] input1 = line1.Split(' ');
            foreach (string num in input1)
            {
                if (int.TryParse(num, out int parsedNum))
                {
                    set1.Add(parsedNum);
                }
            }
        }
        
        // Leer la segunda línea para verificar el formato del 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[] input2 = line2.Split(' ');
            foreach (string num in input2)
            {
                if (int.TryParse(num, out int parsedNum))
                {
                    set2.Add(parsedNum);
                }
            }
        }
        
        // Obtener la unión e imprimir el resultado
        HashSet<int> unionSet = UnionSets(set1, set2);
        Console.WriteLine(string.Join(" ", unionSet.OrderBy(x => x)));
    }
}
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