Skip to content

Commit 2490f6f

Browse files
committed
Add Lecture 20 (+Code)
1 parent b33bcc9 commit 2490f6f

File tree

12 files changed

+695
-0
lines changed

12 files changed

+695
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net7.0</TargetFramework>
6+
<RootNamespace>_01_OperacionesConDiccionarios</RootNamespace>
7+
<ImplicitUsings>enable</ImplicitUsings>
8+
<Nullable>enable</Nullable>
9+
</PropertyGroup>
10+
11+
</Project>
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
using System;
2+
using System.Collections;
3+
using System.Collections.Generic;
4+
using System.Diagnostics;
5+
6+
namespace Programacion
7+
{
8+
class Program
9+
{
10+
[STAThread]
11+
static void Main(string[] args)
12+
{
13+
14+
Dictionary<string, string> agenda = new Dictionary<string, string>();
15+
16+
string nombre, telefono;
17+
while (true)
18+
{
19+
#region CREANDO AGENDA VERSION 1
20+
Console.Write("\nEntre nombre: ");
21+
nombre = Console.ReadLine();
22+
if (nombre.Length == 0) break;
23+
24+
if (agenda.ContainsKey(nombre)) //Aquí estaría buscando dos veces. Primero por el Contains
25+
Console.WriteLine("{0} ya esta en agenda su num es {1}", nombre, agenda[nombre]);
26+
else
27+
{
28+
Console.Write("Entra su numero de telefono: ");
29+
telefono = Console.ReadLine();
30+
agenda.Add(nombre, telefono);
31+
}
32+
#endregion
33+
34+
#region VERSION 2 UN POCO MÁS EFICIENTE
35+
//Console.Write("\nEntra nombre en inglés (Enter para terminar): ");
36+
//nombre = Console.ReadLine();
37+
//if (nombre.Length == 0) break;
38+
//if (agenda.TryGetValue(nombre, out telefono)) //Si está devuelve true y a la vez el telefono en el parámetro
39+
// Console.WriteLine("{0} => {1}", nombre, telefono);
40+
41+
//else
42+
//{
43+
// Console.Write("Entre su numero de telefono: ");
44+
// telefono = Console.ReadLine();
45+
// if (telefono.Length == 0) continue;
46+
// else
47+
// agenda.Add(nombre, telefono);
48+
//}
49+
#endregion
50+
51+
}
52+
//Ejecutar el codigo anterior pero entrando el nombre con alguna mayuscula
53+
//Dictionary se basa en el Equals de string que es sensible a la diferencia
54+
//y por tanto juan no es igual a Juan
55+
56+
#region PRUEBA DE EXCEPCIÓN POR USAR LLAVE INEXISTENTE
57+
//Probar con un nombre que se diferencie en las mayusc minus
58+
//supongamos que esta juan pero no Juan
59+
//lo siguiente debe dar excepcion
60+
61+
//Console.WriteLine(agenda["Juan"]);
62+
#endregion
63+
64+
#region QUITANDO DEL DICCIONARIO
65+
//while (true)
66+
//{
67+
// Console.Write("\nEntre nombre a quitar: ");
68+
// nombre = Console.ReadLine();
69+
// if (nombre.Length == 0) break;
70+
// agenda.Remove(nombre);
71+
// //Si no esta da excepcion
72+
73+
// ////De esta forma no da excepción si no está
74+
// //Console.WriteLine("{0} es {1}",
75+
// // nombre,
76+
// // agenda.TryGetValue(nombre, out telefono) ? telefono : "No esta en la agenda");
77+
//}
78+
#endregion
79+
80+
#region RECORRER DICCIONARIO COMO IENUMERABLE
81+
//Ver las tres formas de hacer lo mismo
82+
//Console.WriteLine("\nLISTANDO LOS NOMBRES DE LA AGENDA\n");
83+
//Console.WriteLine(" Listar recorriendo los KeyValuePairs");
84+
//foreach (KeyValuePair<string, string> kv in agenda)
85+
// Console.WriteLine(" {0, -20}{1, -20}", kv.Key, kv.Value);
86+
87+
//Console.WriteLine("\nListar infiriendo el tipo segun la parte derecha");
88+
//foreach (var kv1 in agenda)
89+
// Console.WriteLine(" {0, -20}{1, -20}", kv1.Key, kv1.Value);
90+
91+
//Console.WriteLine("\nListar deconstruyendolo como tuplo");
92+
//foreach ((string name,string phone) in agenda)
93+
// Console.WriteLine(" {0, -20}{1, -20}", name, phone);
94+
#endregion
95+
96+
#region RECORRER DICCIONARIO ESCRIBIENDO SU GETHASHCODE
97+
//Ver las tres formas de hacer lo mismo
98+
Console.WriteLine("\nLISTANDO LOS NOMBRES DE LA AGENDA\n");
99+
Console.WriteLine("\nListar tambien el GetHashCode");
100+
foreach ((string name, string phone) in agenda)
101+
Console.WriteLine(" {0, -20}{1, -20}{2, -20}", name, phone, name.GetHashCode());
102+
#endregion
103+
}
104+
}
105+
}
106+
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net7.0</TargetFramework>
6+
<RootNamespace>_02_UsandoIEqualityComparer</RootNamespace>
7+
<ImplicitUsings>enable</ImplicitUsings>
8+
<Nullable>enable</Nullable>
9+
</PropertyGroup>
10+
11+
</Project>
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
using System;
2+
using System.Collections;
3+
using System.Collections.Generic;
4+
using System.Diagnostics;
5+
using System.Diagnostics.CodeAnalysis;
6+
7+
namespace Programacion
8+
{
9+
class StringEqualityComparer : IEqualityComparer<string>
10+
{
11+
public bool Equals(string? x, string? y)
12+
{
13+
return x.ToUpper().Equals(y.ToUpper());
14+
}
15+
16+
public int GetHashCode(string obj)
17+
{
18+
return obj.ToUpper().GetHashCode();
19+
20+
//Comentar arriba y descomentar abajo
21+
//Ver que funciona
22+
//Llaves iguales deben tener el mismo GetHashCode
23+
//pero llaves diferentes tambien pueden tener un mismo GetHashCode
24+
//es un concepto que se usa para eficiencia de implementacion como se vera
25+
//mas adelante
26+
27+
//return 1000;
28+
}
29+
}
30+
static class ProgramIqualityComparer
31+
{
32+
[STAThread]
33+
static void Main(string[] args)
34+
{
35+
//Ver la sobrecarga del constructor de Dictionary
36+
Dictionary<string, string> agenda =
37+
new Dictionary<string, string>(new StringEqualityComparer());
38+
39+
string nombre, telefono;
40+
while (true)
41+
{
42+
#region
43+
Console.Write("\nEntre nombre: ");
44+
nombre = Console.ReadLine();
45+
if (nombre.Length == 0) break;
46+
47+
if (agenda.ContainsKey(nombre)) //Aquí estaría buscando dos veces. Primero por el Contains
48+
Console.WriteLine("{0} ya esta en agenda su num es {1}", nombre, agenda[nombre]);
49+
else
50+
{
51+
Console.Write("Entra su numero de telefono: ");
52+
telefono = Console.ReadLine();
53+
agenda.Add(nombre, telefono);
54+
}
55+
}
56+
#endregion
57+
58+
#region RECORRER DICCIONARIO ESCRIBIENDO SU GETHASHCODE
59+
//Ver las tres formas de hacer lo mismo
60+
Console.WriteLine("\nLISTANDO LOS NOMBRES DE LA AGENDA\n");
61+
Console.WriteLine("\nListar tambien el GetHashCode");
62+
foreach ((string name, string phone) in agenda)
63+
Console.WriteLine(" {0, -20}{1, -20}{2, -20}", name, phone, name.GetHashCode());
64+
#endregion
65+
}
66+
}
67+
}
68+
#region EJERCICIOS PARA CLASE PRACTICA
69+
//1) Implemente un metodo que dado un diccionario dicc de tipo Dictionary<TKet, TValue)
70+
//devuelva un IEnumerable de la forma IEnumerable<TValue, IEnumerable<TKey>>
71+
//donde IEnumerable<TKey> regresenta a la coleccion de todos los valores que tienen
72+
//La misma llave en el diccionario original
73+
#endregion
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net7.0</TargetFramework>
6+
<RootNamespace>_03_FibonnaciConDiccionarios</RootNamespace>
7+
<ImplicitUsings>enable</ImplicitUsings>
8+
<Nullable>enable</Nullable>
9+
</PropertyGroup>
10+
11+
</Project>
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
using System;
2+
using System.Collections;
3+
using System.Collections.Generic;
4+
using System.Diagnostics;
5+
6+
namespace Programacion
7+
{
8+
9+
class PruebaFibMemorizado
10+
{
11+
[STAThread]
12+
13+
#region Fibonacci Recursivo Ineficiente
14+
static long Fibonacci(int n)
15+
{
16+
if (n == 1 || n == 2) return 1L;
17+
else return Fibonacci(n - 2) +
18+
Fibonacci(n - 1);
19+
}
20+
#endregion
21+
22+
#region Fibonacci Memorizado con un diccionario
23+
static Dictionary<int, long> dic = new Dictionary<int, long>();
24+
static long FibonacciMemorizado(int n)
25+
{
26+
long result;
27+
if (!dic.TryGetValue(n, out result))
28+
//Si está es porque ya ha sido calculado para ese valor.
29+
//Si no esta lo calculamos y lo guardamos en el diccionario
30+
{
31+
//Si no está en el diccionario entonces no ha sido calculado.
32+
if (n == 1 || n == 2) result = 1L;
33+
else result = FibonacciMemorizado(n - 2) +
34+
FibonacciMemorizado(n - 1);
35+
dic.Add(n, result);
36+
//El nuevo Fibonacci valculado para n lo guardamos en el diccionarioCalcularlo y Guardarlo
37+
}
38+
return result;
39+
}
40+
41+
#endregion
42+
43+
static void Main(string[] args)
44+
{
45+
#region USANDO DICCIONARIO PARA EL PATRÓN MEMOIZE CON FIBONACCI
46+
//Empezar con el recursivo para recordar por qué es ineficiente
47+
Stopwatch crono = new Stopwatch();
48+
int valor; long result;
49+
while (true)
50+
{
51+
Console.Write("\nEntre número a calcular Fibonacci ");
52+
string s = Console.ReadLine();
53+
if (int.TryParse(s, out valor))
54+
{
55+
//Empezar con el ineficiente para mostrar demora
56+
crono.Start();
57+
result = Fibonacci(valor);
58+
crono.Stop();
59+
Console.WriteLine("Fibonacci Recursivo de {0} = {1} calculado en {2} ms", valor, result, crono.ElapsedMilliseconds);
60+
61+
//PRUEBA DE FIBONACCI MEMORIZADO. Descomentar este para probar con diccionario
62+
//crono.Restart();
63+
//result = FibonacciMemorizado(valor);
64+
//crono.Stop();
65+
//Console.WriteLine("Fibonacci Memorizado de {0} = {1} calculado en {2} ms", valor, result, crono.ElapsedMilliseconds);
66+
67+
//Descomentar para ver la cantidad de entradas(llaves) que se han guardado en el diccionario
68+
//Console.WriteLine("Hay {0} entradas en el diccionario", dic.Count);
69+
}
70+
else break;
71+
}
72+
#endregion
73+
}
74+
}
75+
}
76+
#region EJERCICIOS CLASE PRACTICA
77+
//Defina una funcion que reciba como parametro una funcion y devuelva una funcion
78+
//que haga lo mismo pero con capacidad de memorizacion
79+
#endregion
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net7.0</TargetFramework>
6+
<RootNamespace>_04_ImplementacionDeDiccionarioUsandoHashing</RootNamespace>
7+
<ImplicitUsings>enable</ImplicitUsings>
8+
<Nullable>enable</Nullable>
9+
</PropertyGroup>
10+
11+
</Project>

0 commit comments

Comments
 (0)