Menu
Coddy logo textTech

Math - Intersection of HashSet

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

La intersección de dos conjuntos contiene solo los elementos que aparecen en ambos conjuntos.

Crea dos HashSets:

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

Para encontrar la intersección, utiliza el método IntersectWith:

set1.IntersectWith(set2);

Después de ejecutar este código, set1 contendrá:

{ 3, 4, 5 }

El método IntersectWith modifica el conjunto sobre el que se llama, manteniendo solo los elementos que existen en ambos conjuntos.

Para crear un nuevo conjunto con la intersección sin modificar los conjuntos originales, puedes:

HashSet<int> intersection = new HashSet<int>(set1);
intersection.IntersectWith(set2);
challenge icon

Desafío

Intermedio

Crea un método llamado FindCommonElements que tome dos argumentos:

  • Un HashSet de enteros (set1)
  • Un HashSet de enteros (set2)

El método debe devolver un nuevo HashSet que contenga solo los elementos que aparecen en ambos conjuntos (la intersección).

Hoja de referencia

La intersección de dos conjuntos contiene solo los elementos que aparecen en ambos conjuntos.

Utilice el método IntersectWith para encontrar la intersección:

HashSet<int> set1 = new HashSet<int>() { 1, 2, 3, 4, 5 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5, 6, 7 };
set1.IntersectWith(set2); // set1 ahora contiene { 3, 4, 5 }

El método IntersectWith modifica el conjunto original. Para preservar el conjunto original, cree una copia primero:

HashSet<int> intersection = new HashSet<int>(set1);
intersection.IntersectWith(set2);

Pruébalo tú mismo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

class Program {
    public static HashSet<int> FindCommonElements(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[] input1 = line1.Split();
            foreach (string s in input1) {
                if (int.TryParse(s, 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[] input2 = line2.Split();
            foreach (string s in input2) {
                if (int.TryParse(s, out int num)) {
                    set2.Add(num);
                }
            }
        }
        
        // Encontrar elementos comunes
        HashSet<int> common = FindCommonElements(set1, set2);
        
        // Imprimir resultado (ordenado)
        Console.WriteLine(string.Join(" ", common.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