Hast Table - Diccionario - Ejercicio de Programacion C# Sharp

En este ejercicio, se debe crear un diccionario utilizando una tabla hash. El propósito de este ejercicio es practicar la implementación de una estructura de datos eficiente para almacenar pares de clave-valor.

Una tabla hash es una estructura de datos que asocia claves a valores, permitiendo búsquedas, inserciones y eliminaciones rápidas. En este ejercicio, tendrás que implementar un diccionario que almacene palabras como claves y sus respectivas definiciones como valores.

Este ejercicio te permitirá entender cómo funciona una tabla hash en C#, su implementación básica y cómo gestionar las colisiones. Para llevar a cabo este ejercicio, necesitarás manejar la inserción de datos, así como la búsqueda de definiciones usando las claves proporcionadas por el usuario.

Este tipo de estructuras son fundamentales para aplicaciones que requieren acceso rápido a datos, como en búsquedas y almacenamiento de información.

 Categoría

Gestión Dinámica de Memoria

 Ejercicio

Hast Table - Diccionario

 Objectivo

Entregue aquí su diccionario usando Hash Table

 Ejemplo Ejercicio C#

 Copiar Código C#
// Importing necessary namespaces for handling collections
using System;  // Basic namespace for console input/output and other fundamental operations
using System.Collections;  // To use Hashtable, a collection type for key-value pairs

class Program
{
    // Creating a Hashtable to store key-value pairs
    static Hashtable dictionary = new Hashtable();  // Hashtable for storing dictionary entries with keys and values

    // Method to add a word and its meaning to the dictionary
    static void AddWord(string word, string meaning)
    {
        // Check if the word already exists in the dictionary
        if (!dictionary.ContainsKey(word))  // If the word is not already in the dictionary
        {
            dictionary.Add(word, meaning);  // Add the word and its meaning to the dictionary
            Console.WriteLine($"Added '{word}' to the dictionary.");  // Inform the user that the word was added
        }
        else
        {
            Console.WriteLine($"'{word}' already exists in the dictionary.");  // If the word is already present, inform the user
        }
    }

    // Method to search for a word in the dictionary
    static void SearchWord(string word)
    {
        // Check if the word exists in the dictionary
        if (dictionary.ContainsKey(word))  // If the word is found in the dictionary
        {
            // Retrieve and display the meaning of the word
            Console.WriteLine($"{word}: {dictionary[word]}");  // Display the meaning of the word
        }
        else
        {
            Console.WriteLine($"'{word}' not found in the dictionary.");  // If the word doesn't exist, inform the user
        }
    }

    // Main program method to interact with the user and manage the dictionary
    static void Main(string[] args)
    {
        // Add some words to the dictionary
        AddWord("Apple", "A round fruit with red or green skin and a whitish interior.");
        AddWord("Banana", "A long, curved fruit with a yellow skin.");
        AddWord("Computer", "An electronic device for storing and processing data.");

        // Ask the user to input a word to search
        Console.Write("Enter a word to search in the dictionary: ");
        string wordToSearch = Console.ReadLine();  // Read the user's input for the word to search

        // Search and display the meaning of the entered word
        SearchWord(wordToSearch);  // Call the SearchWord method to find and display the meaning

        // Optionally, display the entire dictionary (all words and their meanings)
        Console.WriteLine("\nFull Dictionary:");
        foreach (DictionaryEntry entry in dictionary)  // Iterate over all entries in the dictionary
        {
            Console.WriteLine($"{entry.Key}: {entry.Value}");  // Display each word and its meaning
        }
    }
}

 Salida

Added 'Apple' to the dictionary.
Added 'Banana' to the dictionary.
Added 'Computer' to the dictionary.
Enter a word to search in the dictionary: Banana
Banana: A long, curved fruit with a yellow skin.

Full Dictionary:
Banana: A long, curved fruit with a yellow skin.
Computer: An electronic device for storing and processing data.
Apple: A round fruit with red or green skin and a whitish interior.

 Comparte este Ejercicio C# Sharp

 Más Ejercicios de Programacion C# Sharp de Gestión Dinámica de Memoria

¡Explora nuestro conjunto de ejercicios de programación C# Sharp! Estos ejercicios, diseñados específicamente para principiantes, te ayudarán a desarrollar una sólida comprensión de los conceptos básicos de C#. Desde variables y tipos de datos hasta estructuras de control y funciones simples, cada ejercicio está diseñado para desafiarte de manera gradual a medida que adquieres confianza en la codificación en C#.

  •  Paréntesis

    En este ejercicio, se debe implementar una función que verifique si una secuencia de paréntesis abiertos y cerrados está balanceada. En otras palabras, la función debe compr...

  •  Mezclar y ordenar archivos

    En este ejercicio, se debe crear un programa que lea el contenido de dos archivos diferentes, los combine y los ordene alfabéticamente. El programa debe ser capaz de tomar e...

  •  ArrayList de puntos

    En este ejercicio, debes crear una estructura llamada "Point3D" para representar un punto en un espacio tridimensional con las coordenadas X, Y y Z. La estructura debe permi...

  •  Buscar en archivo

    En este ejercicio, debes crear un programa que lea el contenido de un archivo de texto, guarde ese contenido en un ArrayList y permita al usuario ingresar oraciones p...

  •  Implementación de una cola usando una matriz

    En este ejercicio, deberás implementar una cola (queue) en C#. Una cola es una estructura de datos que sigue el principio FIFO (First In, First Out), es decir,...

  •  Implementar una pila usando una matriz

    En este ejercicio, deberás implementar una pila (stack) en C#. Una pila es una estructura de datos que sigue el principio LIFO (Last In, First Out), es decir, ...