Foro de elhacker.net

Programación => Ejercicios => Mensaje iniciado por: [D4N93R] en 8 Septiembre 2010, 18:44 pm



Título: Retos .Net
Publicado por: [D4N93R] en 8 Septiembre 2010, 18:44 pm
Siguendo el legado de otros temas, como el de Retos C++ y Retos en Python, ahora tenemos Retos en .Net

Las reglas:
  • Cualquier lenguaje .Net es permitido.
  • Cualquier tipo de aplicación es permitida, pero solo en casos de necesitarlo, sino, Consola.
  • Solo está permitido usar la librería de clases de .Net.
  • Solo posteen Soluciones a codes, si tienen dudas comunicarse con el que creó el reto.
  • El que soluciona el reto, postea uno, así de simple.
  • El que deje morir este hilo no le hablo más xD
  • Cada reto nuevo debe incrementarse su dificultad.

RETO #1
Si listamos todos los números naturales por debajo del 10 que sean múltiplos de 3 o 5, obtendremos 3, 5, 6 y 9. La suma de dichos números es 23.

Encuentra la suma de todos los multiplos de 3 o 5 por debajo de 1000

Suerte!


Título: Re: Retos .Net
Publicado por: madpitbull_99 en 8 Septiembre 2010, 19:27 pm
Solucion #Reto 1
Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Reto1_NET
  7. {
  8.    class Program
  9.    {
  10.        static void Main(string[] args)
  11.        {
  12.            const int numero = 1000;
  13.            int suma = 0;
  14.  
  15.            Console.WriteLine("======================================================== ");
  16.            Console.WriteLine("                      RETO #1                            ");
  17.            Console.WriteLine("Suma de todos los multiplos de 3 y 5 por debajo de 1000  ");
  18.            Console.WriteLine("======================================================== ");
  19.  
  20.            for (int i = 0; i < numero; i++)
  21.                if ((i % 3 == 0) || (i % 5 == 0))
  22.                {
  23.                    Console.WriteLine(i);
  24.                    suma = suma + i;
  25.                }
  26.            Console.WriteLine("La suma de los multiplos es : ");
  27.            Console.WriteLine(suma);
  28.            Console.ReadLine();
  29.        }
  30.    }
  31. }

De momento no se me ocurre ningún reto, si alguien quiere poner algo : Que lo ponga xD


Título: Re: Retos .Net
Publicado por: criskapunk en 8 Septiembre 2010, 19:33 pm
Estaba esperando un post asi por aca ;D

Aca lo dejo en vb.net:

Código
  1. Module Module1
  2.  
  3.    Dim i, acu As Integer
  4.  
  5.    Sub Main()
  6.        For i = 1 To 1000
  7.            If (i Mod 3 = 0) Or (i Mod 5 = 0) Then
  8.                acu += i
  9.            End If
  10.        Next
  11.        Console.WriteLine("La suma de los numeros es: ")
  12.        Console.WriteLine(acu)
  13.        Console.ReadLine()
  14.    End Sub
  15.  
  16. End Module

Un saludo ;)


Título: Re: Retos .Net
Publicado por: final_frontier en 8 Septiembre 2010, 19:37 pm
Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Reto1_Net
  7. {
  8.    class Program
  9.    {
  10.        static void Main(string[] args)
  11.        {
  12.            int suma = 0, i;
  13.            for (i = 1; i < 1000; i++)
  14.            {
  15.                if (((i % 3) == 0) || ((i % 5) == 0))
  16.                {
  17.                    suma += i;
  18.                    //Console.Write(i+" ");
  19.                    //Por si queréis ver los números
  20.                }
  21.            }
  22.  
  23.            Console.WriteLine("El total de las sumas es: "+suma);
  24.            Console.Read();
  25.            //El resultado es 233168
  26.        }
  27.    }
  28. }

Reto2: Teniendo los extremos de un intervalo, mostrar todos los números primos comprendidos entre ellos incluyendo dichos extremos


Título: Re: Retos .Net
Publicado por: [D4N93R] en 8 Septiembre 2010, 20:12 pm
Acá esta mi solución en F# para el Reto #2:
Código
  1. let isPrime (n:int) =
  2.   let bound = int (System.Math.Sqrt(float n))
  3.   seq {2 .. bound} |> Seq.exists (fun x -> n % x = 0) |> not
  4.  
  5. let primes m n =
  6.    seq {m .. n}
  7.  
  8. primes 53 1042
  9.    |>  Seq.iter(fun x -> if isPrime x then printfn "%d" x)
  10.  
  11. System.Console.ReadKey();
  12.  

Reto #3
145 es un numero curioso, es decir: 1! + 4! + 5! = 1 + 24 + 120 = 145  ;-)
Dado un intervalo, encuentra todos los números curiosos en el.




Título: Re: Retos .Net
Publicado por: final_frontier en 8 Septiembre 2010, 21:10 pm
Quiero que sepas que te odio por estos ejercicios raros :xD

Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Reto3_Net
  7. {
  8.    class Program
  9.    {
  10.        static void Main(string[] args)
  11.        {
  12.            curious obj = new curious();
  13.            int a, b, aux;
  14.  
  15.            try
  16.            {
  17.                Console.Write("Número 1: ");
  18.                a = Convert.ToInt32(Console.ReadLine());
  19.  
  20.                Console.Write("Número 2: ");
  21.                b = Convert.ToInt32(Console.ReadLine());
  22.  
  23.                if (a > b)
  24.                {
  25.                    aux = a;
  26.                    a = b;
  27.                    b = aux;
  28.                }
  29.  
  30.                for (aux = a; aux <= b; aux++)
  31.                    if (obj.curioso(aux))
  32.                        Console.Write(aux + " ");
  33.            }
  34.            catch(Exception e)
  35.            {
  36.                Console.WriteLine(e.Message);
  37.            }
  38.            Console.Read();
  39.        }
  40.    }
  41.  
  42.    class curious
  43.    {
  44.        private int num(char a)
  45.        {
  46.            int b = 0;
  47.            switch (a)
  48.            {
  49.                case '0': b = 0;
  50.                    break;
  51.  
  52.                case '1': b = 1;
  53.                    break;
  54.  
  55.                case '2': b = 2;
  56.                    break;
  57.  
  58.                case '3': b = 3;
  59.                    break;
  60.  
  61.                case '4': b = 4;
  62.                    break;
  63.  
  64.                case '5': b = 5;
  65.                    break;
  66.  
  67.                case '6': b = 6;
  68.                    break;
  69.  
  70.                case '7': b = 7;
  71.                    break;
  72.  
  73.                case '8': b = 8;
  74.                    break;
  75.  
  76.                case '9': b = 9;
  77.                    break;
  78.            }
  79.  
  80.            return b;
  81.        }
  82.        public bool curioso(int a)
  83.        {
  84.            int aux = 0;
  85.            String cad = a.ToString();
  86.            for (int i = 0; i < cad.Length; i++)
  87.                aux += factorial(num(cad[i]));
  88.  
  89.            if (aux == a)
  90.                return true;
  91.  
  92.            else
  93.                return false;
  94.        }
  95.        public int factorial(int a)
  96.        {
  97.            if (a <= 1)
  98.                return 1;
  99.            else
  100.                return a * factorial(a - 1);
  101.        }
  102.    }
  103. }

Si al comprobarlo ves que no es un FAIL, me mandas un mp y pongo el cuarto reto :B


Título: Re: Retos .Net
Publicado por: [D4N93R] en 8 Septiembre 2010, 21:45 pm
Si está bien , pero ehm, bueno, creo que no es la mejor forma de hacerlo xD, esperemos que alguien postee una CON RETO INCLUIDO! xD


Título: Re: Retos .Net
Publicado por: carlitos_jajajajaja en 9 Septiembre 2010, 06:31 am
Esta forma es mas eficiente ya que solo calcula los factoriales 10 veces,
faltaria implementar factorial de manera no recursiva...

Tambien le falta agragar un poco de elegancia al codigo, no me gusta tanto el hecho de que Program.Fact sea static, deberia inclurilo dentro de una clase curious como el codigo anterior, pero eso ya no lo hago yo :P

El codigo esta en c#:

Código
  1. using System;
  2.  
  3. namespace Problema2Mejorado
  4. {
  5.    class Program
  6.    {
  7.        static Factorial fact = new Factorial(10);
  8.        static void Main(string[] args)
  9.        {
  10.            int inicio, final;
  11.            Console.WriteLine("Introduzca el primer numero del intervalo");
  12.            inicio = int.Parse(Console.ReadLine());
  13.            Console.WriteLine("Introduzca el ultimo numero del intervalo");
  14.            final = int.Parse(Console.ReadLine());
  15.            for (int probar = inicio; probar <= final; probar++)
  16.            {
  17.                if (EsCurioso(probar))
  18.                    Console.WriteLine("{0}, ", probar);
  19.            }
  20.            Console.ReadKey();
  21.        }
  22.        //Para omitir conversiones inutiles recibo el numero como string ya q necesito analizar sus digitos
  23.        static bool EsCurioso(int Numero)
  24.        {
  25.            string Num = Numero.ToString();
  26.            int sumador = 0;
  27.            foreach (char digito in Num)
  28.            {
  29.                //Con esto me ahorro todo el switch case del otro codigo :p
  30.                int ValorDigito = int.Parse(digito.ToString());
  31.                sumador += fact[ValorDigito];
  32.            }
  33.            if (sumador == int.Parse(Num))
  34.                return true;
  35.            else
  36.                return false;
  37.        }
  38.    }
  39.  
  40.    class Factorial
  41.    {
  42.        //En este arreglo guardaremos los factoriales de 0 hasta 9, para q solo tengan q ser calculados una vez :)
  43.        private int[] factoriales;
  44.        public Factorial(int rango)
  45.        {
  46.            factoriales = new int[rango];
  47.            for (int i = 0; i < rango; i++)
  48.            {
  49.                factoriales[i] = CalcularFactorial(i);
  50.            }
  51.        }
  52.        int CalcularFactorial(int n)
  53.        {
  54.            if (n <= 1)
  55.                return 1;
  56.            else
  57.                return n * CalcularFactorial(n - 1);
  58.        }
  59.        //Y de manera muy limpia obtenemos el factorial de un numero con el operador []
  60.        public int this[int i]
  61.        {
  62.            get
  63.            {
  64.                return factoriales[i];
  65.            }
  66.        }
  67.    }
  68. }
  69.  
  70.  



Reto 3:

El usuario proporcionara un numero de pruebas p, y un numero de intervalos n

El programa debera generar p numeros aleatorios entre 1 y q (tal que q sea el menor numero divisible por n, pero mayor o igual a 100), y elaborar un reporte sobre que porcentaje de los numeros cayo en cada intervalo.

Si por ejemplo el numero de intervalos n es 4, se consideraran los intervalos 1-25, 26-50, 51-75 y 75-100.


No se si me deje entender, si no lo hice avisenme...


Título: Re: Retos .Net
Publicado por: final_frontier en 9 Septiembre 2010, 11:15 am
No sé si será esto lo que pides pero te muestro la salida del programa:

Código:
Números aleatorios: 2
Número de intervalos: 7
53 26 <-- Números aleatorios
Intervalos:
(1,15) (16,30) (31,45) (46,60) (61,75) (76,90) (91,105)

Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Reto4_Net
  7. {
  8.    class Program
  9.    {
  10.        static void Main(string[] args)
  11.        {
  12.            //----------------------------------//
  13.  
  14.            Random obj = new Random();
  15.            int n, p, q = 100, i, j;
  16.            int[] intervalos;
  17.  
  18.            //----------------------------------//
  19.            Console.Write("Números aleatorios: ");
  20.            p = Convert.ToInt32(Console.ReadLine());
  21.  
  22.            Console.Write("Número de intervalos: ");
  23.            n = Convert.ToInt32(Console.ReadLine());
  24.  
  25.            intervalos = new int[p];
  26.  
  27.            while ((q % n) != 0)
  28.                q++;
  29.  
  30.            for (i = 0; i < p; i++)
  31.            {
  32.                intervalos[i] = obj.Next(q);
  33.                Console.Write(intervalos[i]+" ");
  34.            }
  35.            Console.Write("\nIntervalos: \n");
  36.            j = q / n;
  37.  
  38.            for (i = 0; i < n; i++)
  39.                Console.Write("("+((i*j)+1)+","+((i+1)*j)+") ");
  40.            Console.Read();
  41.        }
  42.    }
  43. }

Reto #5 (Corrección por amenaza de D4N93R :xD)

Tenemos un pequeño programa que almacena el registro de algunos alumnos que han hecho matrícula, con un máximo de 10 matriculados.

Crear dos tablas, una con los candidatos y otra con los admitidos, si la lista de admitidos esta llena, a la hora de insertar uno nuevo hay que comprobar la nota de corte (digamos un 5)

Ordenar de manera ascendente los usuarios por nota


Título: Re: Retos .Net
Publicado por: [D4N93R] en 11 Septiembre 2010, 16:56 pm
Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace Reto5
  6. {
  7.    public class Student
  8.    {
  9.        public byte Score { get; set; }
  10.        public string Name { get; set; }
  11.  
  12.        public Student(string input)
  13.        {
  14.            Score = Convert.ToByte(input.Substring(0, 2));
  15.            Name = input.Substring(3);
  16.        }
  17.        public override string ToString()
  18.        {
  19.            return string.Format("Score: {0:00}, Name = {1}", Score, Name);
  20.        }
  21.    }
  22.    static class Program
  23.    {
  24.        static int Main()
  25.        {
  26.            byte scoreLine = 5, capacity = 3;
  27.  
  28.            List<Student> students = new List<Student>();
  29.  
  30.            Console.WriteLine("Ingrese alumnos, formato: NN NOMBRE en donde NN es la nota.");
  31.            string input = string.Empty;
  32.  
  33.            while (!string.IsNullOrEmpty(input = Console.ReadLine()))
  34.            {
  35.                students.Add(new Student(input));
  36.            }
  37.  
  38.            if(students.Count <= capacity)
  39.                ShowList(students);
  40.            else
  41.            {
  42.                var query = (from s in students
  43.                            where s.Score > scoreLine
  44.                            orderby s.Score descending
  45.                            select s).Where((s, index) => index < capacity);
  46.                ShowList(query);
  47.            }
  48.            Console.ReadKey();
  49.            return 0;
  50.        }
  51.  
  52.        private static void ShowList(IEnumerable<Student> students)
  53.        {
  54.            foreach (var s in students)
  55.                Console.WriteLine(s.ToString());
  56.        }
  57.    }
  58. }

Reto #6

Una lista/array/vector/queue o lo que quieran, debe contener una cantidad de palabras. El reto consiste en comparar esas palabras para conseguir posibles anagramas.
Ejm: si tengo el array: "arroz", "zorra" la aplicación debe mostrar que esos dos son anagramas.

:P

EDIT: El array debe ser más o menos grande, o permitir la adición de elementos por parte del usuario, como quieran, pero no solamente arroz y zorra  :¬¬
EDIT2: No solo es palíndromo, sino que también en forma de anagrama, por ejemplo: ROMA - AMOR - OMAR - MORA - RAMO  :¬¬


Título: Re: Retos .Net
Publicado por: criskapunk en 13 Septiembre 2010, 16:01 pm
Como te odio [D4N93R] :¬¬ jaja

Reto #3

Código
  1. Option Explicit On
  2.  
  3. Module Module1
  4.  
  5.    Dim n1, n2, longitud, num, f, resultado As Integer
  6.    Dim strNum As String
  7.    Dim i, j, k As Integer
  8.  
  9.    Sub Main()
  10.  
  11.        Console.WriteLine("Ingrese el primer valor del intervalo: ")
  12.        n1 = Val(Console.ReadLine())
  13.        Console.WriteLine("Ingrese el segundo valor del intervalo: ")
  14.        n2 = Val(Console.ReadLine())
  15.        For i = n1 To n2
  16.            strNum = CStr(i)
  17.            longitud = strNum.Length
  18.            For j = 0 To (longitud - 1)
  19.                num = CInt(CStr(strNum(j)))
  20.                If (num = 0) Or (num = 1) Then
  21.                    f = 1
  22.                Else
  23.                    For k = 1 To num
  24.                        f *= k
  25.                    Next
  26.                End If
  27.                resultado += f
  28.                f = 1
  29.            Next
  30.            If i = resultado Then
  31.                Console.WriteLine(i)
  32.                Console.WriteLine("Es un numero curioso! :)")
  33.            End If
  34.            resultado = 0
  35.        Next
  36.        Console.ReadLine()
  37.    End Sub
  38.  
  39. End Module

No se si puedo poner algun reto :P

Un saludo


Título: Re: Retos .Net
Publicado por: [D4N93R] en 15 Septiembre 2010, 05:02 am
Bueno cómo nadie resolvió el reto, voy a poner la solución:
Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Reto6
  7. {
  8.    class Program
  9.    {
  10.        static void Main(string[] args)
  11.        {
  12.            string[] words = { "programador", "framework", "zorra", "mora", "amor", "roma", "arroz" };
  13.  
  14.            var wordsOrdered = words.GroupBy(w => w.Trim(), new AnagramComparer());
  15.  
  16.            foreach (var a in wordsOrdered)
  17.            {
  18.                Console.WriteLine("**********************");
  19.                foreach (var b in a)
  20.                {
  21.                    Console.WriteLine(b);
  22.                }
  23.            }
  24.            Console.WriteLine("**********************");
  25.        }
  26.    }
  27. }
  28.  
  29.  
  30. public class AnagramComparer : IEqualityComparer<string>
  31. {
  32.    public bool Equals(string x, string y)
  33.    {
  34.        return getLetters(x) == getLetters(y);
  35.    }
  36.  
  37.    public int GetHashCode(string obj)
  38.    {
  39.        return getLetters(obj).GetHashCode();
  40.    }
  41.  
  42.    private string getLetters(string word)
  43.    {
  44.        char[] chars = word.ToCharArray();
  45.        Array.Sort<char>(chars);
  46.        return new string(chars);
  47.    }
  48. }
  49.  

Reto #7
El número 197 es llamado primo circular porque todas las combinaciones de sus digitos son primos también.

Hay 13 primos por debajo de 100 que son circulares:  2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.

El reto consiste en saber cuantos primos circulares hay por debajo de un millón.

Reto #8
El que haga este proceso en menos tiempo.. Así que a postear soluciones que yo les mido el rendimiento del método.

 ;-)


Título: Re: Retos .Net
Publicado por: carlitos_jajajajaja en 20 Septiembre 2010, 15:46 pm
Cuanto tiempo mas o menos nos deberia tardar en calcular???


Título: Re: Retos .Net
Publicado por: [D4N93R] en 20 Septiembre 2010, 15:50 pm
Ni idea, calculo unos 1-2 minutos. Supongo. Puede que más.. Puede que menos x) Si ya lo terminaste, postealo, y cualquier cosa lo vamos optimizando.


Título: Re: Retos .Net
Publicado por: [L]ord [R]NA en 26 Septiembre 2010, 06:40 am
[D4N93R] creo que ambos cometimos un pequeño error... colocamos un reto que mato la idea de los ejercicios, que tal si cambias el ejercicio?


Título: Re: Retos .Net
Publicado por: [D4N93R] en 26 Septiembre 2010, 07:45 am
Si, voy a postear la respuesta y a poner otro ejercicio :) pero mañana, que ahora estoy revisando el regristro -.-


Título: Re: Retos .Net
Publicado por: [L]ord [R]NA en 26 Septiembre 2010, 17:35 pm
Cierto... tienes otra anecdota de aprendiendo a base de palos. ;D


Título: Re: Retos .Net
Publicado por: criskapunk en 28 Septiembre 2010, 18:43 pm
Con autorizacion de [D4N93R] posteo un nuevo reto :)

Reto #9
Dada una fraccion, simplificarla hasta llegar a su irreductible.

Un saludo ;)


Título: Re: Retos .Net
Publicado por: [L]ord [R]NA en 28 Septiembre 2010, 19:57 pm
Respuesta al Reto#9:
Código
  1. using System;
  2.  
  3. namespace fraccion
  4. {
  5. class MainClass
  6. {
  7. public static void factorizar (ref int a,ref int b)
  8. {
  9. for(int i=2;i<b+1;i++)if(a%i==0 && b%i==0)
  10. {
  11. a/=i;
  12. b/=i;
  13. i--;
  14. }
  15. }
  16.  
  17. public static void Main (string[] args)
  18. {
  19. string fraccion;
  20. string[] split;
  21. int[] valor = new int[2];
  22.  
  23. Console.WriteLine("Introduzca la fraccion en el formato a/b : ");
  24. fraccion = Console.ReadLine();
  25. split = fraccion.Split(char.Parse("/"));
  26. for(int i=0;i<2;i++) valor[i] = Int32.Parse(split[i]);
  27.  
  28. if(valor[0]>=valor[1])factorizar(ref valor[0],ref valor[1]);
  29. else factorizar(ref valor[1],ref valor[0]);
  30.  
  31. Console.WriteLine("{0}/{1}",valor[0],valor[1]);
  32. }
  33. }
  34. }


Título: Re: Retos .Net
Publicado por: [L]ord [R]NA en 29 Septiembre 2010, 07:08 am
Reto #10: Realizar una agenda telefonica.

Nota sobre el reto: Se debe crear una base de datos SQL desde el programa en la cual se guardara nombre. apellido, sexo, edad, telefono. El programa debe contar con las siguientes opciones...

1)Agregar nuevo contacto.
2)Eliminar contacto.
3)Buscar contacto.
4)Editar contacto.


Título: Re: Retos .Net
Publicado por: final_frontier en 6 Diciembre 2010, 03:26 am
@Lord R.N.A.

Cacho de ca**** yo no descansaba si no daba con la tecla :xD :xD :xD :xD

Mi solución propuesta

Antes que nada, la tabla que he utilizado

Código
  1. CREATE TABLE contacto(
  2.  
  3.  nombre  VARCHAR(50) NOT NULL,
  4.  sexo    CHAR(1),
  5.  edad    INT,
  6.  tlf     CHAR(9) NOT NULL,
  7.  
  8.  CONSTRAINT KeyAgenda PRIMARY KEY (nombre, tlf),
  9.  CONSTRAINT CaracterSexo CHECK sexo IN ('H', 'M')
  10. );

Y aquí el programa

Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. //Para conectar con base de datos
  6. using MySql.Data.MySqlClient;
  7.  
  8.  
  9. namespace Agenda
  10. {
  11.    class Program
  12.    {
  13.        private bool abierto = false;
  14.        private MySqlDataReader Reader;
  15.        private MySqlConnection connection;
  16.        private MySqlCommand command;
  17.        private int numContactos = 0;
  18.        private string MyConString;
  19.        private bool encontrar(string nom, string tel)
  20.        {
  21.            bool ret = false;
  22.  
  23.            if (numContactos != 0)
  24.            {
  25.                string comando = "SELECT * FROM contacto "
  26.                                 + "WHERE nombre = '" + nom + "' AND "
  27.                                 + "tlf = '" + tel + "';";
  28.                //Comando de selección para la búsqueda
  29.                command.CommandText = comando;
  30.                Reader = command.ExecuteReader();
  31.  
  32.                while ((Reader.Read()) && (ret == false))
  33.                    ret = true; //Si llega a entrar en el bucle es que por lo menos
  34.                //ha encontrado un dato. Al estar buscando por la
  35.                //clave primaria de la relación, sólo debería devolver
  36.                //un único valor, el buscado.
  37.                Reader.Dispose();
  38.            }
  39.  
  40.            return ret;
  41.        }
  42.  
  43.        public void agregarCon(string nom, char sex, int edad, string tlf)
  44.        {
  45.            if (!encontrar(nom, tlf))
  46.            {
  47.                string agrega = "INSERT INTO contacto VALUES('" + nom + "','" + sex + "','" + edad + "','" + tlf + "');";
  48.                command.CommandText = agrega;
  49.                command.ExecuteNonQuery();
  50.                numContactos++;
  51.            }
  52.            else
  53.            {
  54.                System.Console.WriteLine("Contacto previamente accesible en la tabla");
  55.            }
  56.        }
  57.        public void imprimeAgenda()
  58.        {
  59.            if (numContactos != 0)
  60.            {
  61.                command.CommandText = "SELECT * FROM contacto;";
  62.  
  63.                Reader = command.ExecuteReader();
  64.                while (Reader.Read())
  65.                {
  66.                    for (int i = 0; i < Reader.FieldCount; i++)
  67.                        System.Console.Write(Reader.GetValue(i).ToString() + " ");
  68.                    System.Console.Write("\n");
  69.                }
  70.  
  71.                Reader.Dispose();
  72.            }
  73.        }
  74.        public void editarContacto(string nom, string tel)
  75.        {
  76.            if (numContactos != 0)
  77.            {
  78.                //Variables para la edición
  79.                string nnom;
  80.                char nsex;
  81.                int nedad;
  82.                string ntel;
  83.  
  84.                System.Console.WriteLine("Nuevo nombre: ");
  85.                do
  86.                {
  87.                    nnom = System.Console.ReadLine();
  88.                    System.Console.WriteLine();
  89.                }while(nnom.Length>50);
  90.  
  91.                System.Console.WriteLine("Nuevo sexo: ");
  92.                do
  93.                {
  94.                    string aux = System.Console.ReadLine();
  95.                    nsex = aux[0];
  96.                    System.Console.WriteLine();
  97.                } while ((nsex != 'M') && (nsex != 'H'));
  98.  
  99.                System.Console.WriteLine("Nueva edad: ");
  100.                do
  101.                {
  102.                    try
  103.                    {
  104.                        nedad = Convert.ToInt32(System.Console.ReadLine());
  105.                    }
  106.                    catch (InvalidCastException)
  107.                    {
  108.                        nedad = -1;
  109.                    }
  110.                } while (nedad == -1);
  111.  
  112.                System.Console.WriteLine("Nuevo teléfono: ");
  113.                do
  114.                {
  115.                    ntel = System.Console.ReadLine();
  116.                    System.Console.WriteLine();
  117.                } while (ntel.Length > 9);
  118.  
  119.                eliminaContacto(nom, tel);
  120.                agregarCon(nnom, nsex, nedad, ntel);
  121.            }
  122.        }
  123.        public void eliminaContacto(string nom, string tel)
  124.        {
  125.            if (encontrar(nom, tel))
  126.            {
  127.                string comando = "DELETE FROM contacto "+
  128.                                 "WHERE nombre = '"+nom+"' AND tlf = '"+tel+"';";
  129.                command.CommandText = comando;
  130.                command.ExecuteNonQuery();
  131.                System.Console.WriteLine("Contacto modificado satisfactoriamente");
  132.            }
  133.            else
  134.            {
  135.                System.Console.WriteLine("Contacto no encontrado...");
  136.            }
  137.        }
  138.        public int getNumContactos()
  139.        {
  140.            return numContactos;
  141.        }
  142.  
  143.        ~Program()
  144.        {
  145.            if (abierto)
  146.            {
  147.                Reader.Close();
  148.                connection.Close();
  149.            }
  150.        }
  151.        Program()
  152.        {
  153.            MyConString = "SERVER=localhost;" +
  154.                "DATABASE=agenda;" +
  155.                "UID=usuario;" +
  156.                "PASSWORD=user;";
  157.            connection = new MySqlConnection(MyConString);
  158.            command = connection.CreateCommand();
  159.            connection.Open();
  160.            abierto = true;
  161.            command.CommandText = "SELECT * FROM contacto;";
  162.            Reader = command.ExecuteReader();
  163.            while (Reader.Read())
  164.                numContactos++;
  165.  
  166.            Reader.Dispose();
  167.        }
  168.  
  169.        public static void menu()
  170.        {
  171.            System.Console.WriteLine("---------MENU---------");
  172.            System.Console.WriteLine("1.- Agregar contacto");
  173.            System.Console.WriteLine("2.- Modificar contacto");
  174.            System.Console.WriteLine("3.- Eliminar contacto");
  175.            System.Console.WriteLine("4.- Ver Base actual");
  176.            System.Console.WriteLine("5.- Salir");
  177.            System.Console.Write("Elija una opción: ");
  178.        }
  179.  
  180.        static void Main(string[] args)
  181.        {
  182.            Program obj = new Program();
  183.            int opcion;
  184.            string nnom;
  185.            char nsex;
  186.            int nedad;
  187.            string ntel;
  188.            try
  189.            {
  190.                do
  191.                {
  192.                    Console.Clear();
  193.                    Program.menu();
  194.                    try
  195.                    {
  196.                        opcion = Convert.ToInt32(System.Console.ReadLine());
  197.                    }
  198.                    catch (InvalidCastException)
  199.                    {
  200.                        opcion = 0;
  201.                    }
  202.  
  203.                    System.Console.WriteLine();
  204.                    switch (opcion)
  205.                    {
  206.                        case 1:
  207.                            System.Console.WriteLine("Nombre: ");
  208.                            do
  209.                            {
  210.                                nnom = System.Console.ReadLine();
  211.                                System.Console.WriteLine();
  212.                            } while (nnom.Length > 50);
  213.  
  214.                            System.Console.WriteLine("Sexo: ");
  215.                            do
  216.                            {
  217.                                string aux = System.Console.ReadLine();
  218.                                nsex = aux[0];
  219.                                System.Console.WriteLine();
  220.                            } while ((nsex != 'M') && (nsex != 'H'));
  221.  
  222.                            System.Console.WriteLine("Edad: ");
  223.                            do
  224.                            {
  225.                                try
  226.                                {
  227.                                    nedad = Convert.ToInt32(System.Console.ReadLine());
  228.                                }
  229.                                catch (InvalidCastException)
  230.                                {
  231.                                    nedad = -1;
  232.                                }
  233.                            } while (nedad == -1);
  234.  
  235.                            System.Console.WriteLine("Teléfono: ");
  236.                            do
  237.                            {
  238.                                ntel = System.Console.ReadLine();
  239.                                System.Console.WriteLine();
  240.                            } while (ntel.Length > 50);
  241.  
  242.                            obj.agregarCon(nnom, nsex, nedad, ntel);
  243.                            System.Console.ReadLine();
  244.                            break;
  245.  
  246.                        case 2:
  247.                            System.Console.WriteLine("Nombre: ");
  248.                            do
  249.                            {
  250.                                nnom = System.Console.ReadLine();
  251.                                System.Console.WriteLine();
  252.                            } while (nnom.Length > 50);
  253.  
  254.                            System.Console.WriteLine("Teléfono: ");
  255.                            do
  256.                            {
  257.                                ntel = System.Console.ReadLine();
  258.                                System.Console.WriteLine();
  259.                            } while (ntel.Length > 50);
  260.  
  261.                            obj.editarContacto(nnom, ntel);
  262.  
  263.                            System.Console.ReadLine();
  264.                            break;
  265.                        case 3:
  266.                            System.Console.WriteLine("Nombre: ");
  267.                            do
  268.                            {
  269.                                nnom = System.Console.ReadLine();
  270.                                System.Console.WriteLine();
  271.                            } while (nnom.Length > 50);
  272.  
  273.                            System.Console.WriteLine("Teléfono: ");
  274.                            do
  275.                            {
  276.                                ntel = System.Console.ReadLine();
  277.                                System.Console.WriteLine();
  278.                            } while (ntel.Length > 50);
  279.  
  280.                            obj.eliminaContacto(nnom, ntel);
  281.                            System.Console.ReadLine();
  282.                            break;
  283.                        case 4:
  284.                            obj.imprimeAgenda();
  285.                            System.Console.ReadLine();
  286.                            break;
  287.                        case 5:
  288.                            break;
  289.  
  290.                        default:
  291.                            System.Console.WriteLine("Opción incorrecta");
  292.                            System.Console.ReadLine();
  293.                            break;
  294.                    }
  295.  
  296.                } while (opcion != 5);
  297.            }
  298.            catch (MySqlException e)
  299.            {
  300.                System.Console.WriteLine("Excepción: " + e.Message);
  301.            }
  302.            finally
  303.            {
  304.                System.Console.WriteLine("Presione una tecla para salir");
  305.                System.Console.ReadLine();
  306.            }
  307.        }
  308.    }
  309. }

Reto 11: A partir de una clase base llamada Polígono, generar las clases Esfera, Círculo, Rectángulo y Triángulo que permita en todos los casos obtener el área y perímetro de las figuras que representa cada clase.

Feliz navidad :B