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 #1Si 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 1000Suerte!
Solucion #Reto 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Reto1_NET
{
class Program
{
static void Main(string[] args)
{
const int numero = 1000;
int suma = 0;
Console.WriteLine("======================================================== ");
Console.WriteLine(" RETO #1 ");
Console.WriteLine("Suma de todos los multiplos de 3 y 5 por debajo de 1000 ");
Console.WriteLine("======================================================== ");
for (int i = 0; i < numero; i++)
if ((i % 3 == 0) || (i % 5 == 0))
{
Console.WriteLine(i);
suma = suma + i;
}
Console.WriteLine("La suma de los multiplos es : ");
Console.WriteLine(suma);
Console.ReadLine();
}
}
}
De momento no se me ocurre ningún reto, si alguien quiere poner algo : Que lo ponga xD
Estaba esperando un post asi por aca ;D
Aca lo dejo en vb.net:
Module Module1
Dim i, acu As Integer
Sub Main()
For i = 1 To 1000
If (i Mod 3 = 0) Or (i Mod 5 = 0) Then
acu += i
End If
Next
Console.WriteLine("La suma de los numeros es: ")
Console.WriteLine(acu)
Console.ReadLine()
End Sub
End Module
Un saludo ;)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Reto1_Net
{
class Program
{
static void Main(string[] args)
{
int suma = 0, i;
for (i = 1; i < 1000; i++)
{
if (((i % 3) == 0) || ((i % 5) == 0))
{
suma += i;
//Console.Write(i+" ");
//Por si queréis ver los números
}
}
Console.WriteLine("El total de las sumas es: "+suma);
Console.Read();
//El resultado es 233168
}
}
}
Reto2: Teniendo los extremos de un intervalo, mostrar todos los números primos comprendidos entre ellos incluyendo dichos extremos
Acá esta mi solución en F# para el Reto #2:
let isPrime (n:int) =
let bound = int (System.Math.Sqrt(float n))
seq {2 .. bound} |> Seq.exists (fun x -> n % x = 0) |> not
let primes m n =
seq {m .. n}
primes 53 1042
|> Seq.iter(fun x -> if isPrime x then printfn "%d" x)
System.Console.ReadKey();
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.
Quiero que sepas que te odio por estos ejercicios raros :xD
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Reto3_Net
{
class Program
{
static void Main(string[] args)
{
curious obj = new curious();
int a, b, aux;
try
{
Console.Write("Número 1: ");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("Número 2: ");
b = Convert.ToInt32(Console.ReadLine());
if (a > b)
{
aux = a;
a = b;
b = aux;
}
for (aux = a; aux <= b; aux++)
if (obj.curioso(aux))
Console.Write(aux + " ");
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
Console.Read();
}
}
class curious
{
private int num(char a)
{
int b = 0;
switch (a)
{
case '0': b = 0;
break;
case '1': b = 1;
break;
case '2': b = 2;
break;
case '3': b = 3;
break;
case '4': b = 4;
break;
case '5': b = 5;
break;
case '6': b = 6;
break;
case '7': b = 7;
break;
case '8': b = 8;
break;
case '9': b = 9;
break;
}
return b;
}
public bool curioso(int a)
{
int aux = 0;
String cad = a.ToString();
for (int i = 0; i < cad.Length; i++)
aux += factorial(num(cad[i]));
if (aux == a)
return true;
else
return false;
}
public int factorial(int a)
{
if (a <= 1)
return 1;
else
return a * factorial(a - 1);
}
}
}
Si al comprobarlo ves que no es un FAIL, me mandas un mp y pongo el cuarto reto :B
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
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#:
using System;
namespace Problema2Mejorado
{
class Program
{
static Factorial fact = new Factorial(10);
static void Main(string[] args)
{
int inicio, final;
Console.WriteLine("Introduzca el primer numero del intervalo");
inicio = int.Parse(Console.ReadLine());
Console.WriteLine("Introduzca el ultimo numero del intervalo");
final = int.Parse(Console.ReadLine());
for (int probar = inicio; probar <= final; probar++)
{
if (EsCurioso(probar))
Console.WriteLine("{0}, ", probar);
}
Console.ReadKey();
}
//Para omitir conversiones inutiles recibo el numero como string ya q necesito analizar sus digitos
static bool EsCurioso(int Numero)
{
string Num = Numero.ToString();
int sumador = 0;
foreach (char digito in Num)
{
//Con esto me ahorro todo el switch case del otro codigo :p
int ValorDigito = int.Parse(digito.ToString());
sumador += fact[ValorDigito];
}
if (sumador == int.Parse(Num))
return true;
else
return false;
}
}
class Factorial
{
//En este arreglo guardaremos los factoriales de 0 hasta 9, para q solo tengan q ser calculados una vez :)
private int[] factoriales;
public Factorial(int rango)
{
factoriales = new int[rango];
for (int i = 0; i < rango; i++)
{
factoriales[i] = CalcularFactorial(i);
}
}
int CalcularFactorial(int n)
{
if (n <= 1)
return 1;
else
return n * CalcularFactorial(n - 1);
}
//Y de manera muy limpia obtenemos el factorial de un numero con el operador []
public int this[int i]
{
get
{
return factoriales[i];
}
}
}
}
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...
No sé si será esto lo que pides pero te muestro la salida del programa:
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)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Reto4_Net
{
class Program
{
static void Main(string[] args)
{
//----------------------------------//
Random obj = new Random();
int n, p, q = 100, i, j;
int[] intervalos;
//----------------------------------//
Console.Write("Números aleatorios: ");
p = Convert.ToInt32(Console.ReadLine());
Console.Write("Número de intervalos: ");
n = Convert.ToInt32(Console.ReadLine());
intervalos = new int[p];
while ((q % n) != 0)
q++;
for (i = 0; i < p; i++)
{
intervalos[i] = obj.Next(q);
Console.Write(intervalos[i]+" ");
}
Console.Write("\nIntervalos: \n");
j = q / n;
for (i = 0; i < n; i++)
Console.Write("("+((i*j)+1)+","+((i+1)*j)+") ");
Console.Read();
}
}
}
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
using System;
using System.Collections.Generic;
using System.Linq;
namespace Reto5
{
public class Student
{
public byte Score { get; set; }
public string Name { get; set; }
public Student(string input)
{
Score = Convert.ToByte(input.Substring(0, 2));
Name = input.Substring(3);
}
public override string ToString()
{
return string.Format("Score: {0:00}, Name = {1}", Score, Name);
}
}
static class Program
{
static int Main()
{
byte scoreLine = 5, capacity = 3;
List<Student> students = new List<Student>();
Console.WriteLine("Ingrese alumnos, formato: NN NOMBRE en donde NN es la nota.");
string input = string.Empty;
while (!string.IsNullOrEmpty(input = Console.ReadLine()))
{
students.Add(new Student(input));
}
if(students.Count <= capacity)
ShowList(students);
else
{
var query = (from s in students
where s.Score > scoreLine
orderby s.Score descending
select s).Where((s, index) => index < capacity);
ShowList(query);
}
Console.ReadKey();
return 0;
}
private static void ShowList(IEnumerable<Student> students)
{
foreach (var s in students)
Console.WriteLine(s.ToString());
}
}
}
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 :¬¬
Como te odio [D4N93R] :¬¬ jaja
Reto #3
Option Explicit On
Module Module1
Dim n1, n2, longitud, num, f, resultado As Integer
Dim strNum As String
Dim i, j, k As Integer
Sub Main()
Console.WriteLine("Ingrese el primer valor del intervalo: ")
n1 = Val(Console.ReadLine())
Console.WriteLine("Ingrese el segundo valor del intervalo: ")
n2 = Val(Console.ReadLine())
For i = n1 To n2
strNum = CStr(i)
longitud = strNum.Length
For j = 0 To (longitud - 1)
num = CInt(CStr(strNum(j)))
If (num = 0) Or (num = 1) Then
f = 1
Else
For k = 1 To num
f *= k
Next
End If
resultado += f
f = 1
Next
If i = resultado Then
Console.WriteLine(i)
Console.WriteLine("Es un numero curioso! :)")
End If
resultado = 0
Next
Console.ReadLine()
End Sub
End Module
No se si puedo poner algun reto :P
Un saludo
Bueno cómo nadie resolvió el reto, voy a poner la solución:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Reto6
{
class Program
{
static void Main(string[] args)
{
string[] words = { "programador", "framework", "zorra", "mora", "amor", "roma", "arroz" };
var wordsOrdered = words.GroupBy(w => w.Trim(), new AnagramComparer());
foreach (var a in wordsOrdered)
{
Console.WriteLine("**********************");
foreach (var b in a)
{
Console.WriteLine(b);
}
}
Console.WriteLine("**********************");
}
}
}
public class AnagramComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return getLetters(x) == getLetters(y);
}
public int GetHashCode(string obj)
{
return getLetters(obj).GetHashCode();
}
private string getLetters(string word)
{
char[] chars = word.ToCharArray();
Array.Sort<char>(chars);
return new string(chars);
}
}
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.
;-)
Cuanto tiempo mas o menos nos deberia tardar en calcular???
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.
[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?
Si, voy a postear la respuesta y a poner otro ejercicio :) pero mañana, que ahora estoy revisando el regristro -.-
Cierto... tienes otra anecdota de aprendiendo a base de palos. ;D
Con autorizacion de [D4N93R] posteo un nuevo reto :)
Reto #9
Dada una fraccion, simplificarla hasta llegar a su irreductible.
Un saludo ;)
Respuesta al Reto#9:
using System;
namespace fraccion
{
class MainClass
{
public static void factorizar (ref int a,ref int b)
{
for(int i=2;i<b+1;i++)if(a%i==0 && b%i==0)
{
a/=i;
b/=i;
i--;
}
}
public static void Main (string[] args)
{
string fraccion;
string[] split;
int[] valor = new int[2];
Console.WriteLine("Introduzca la fraccion en el formato a/b : ");
fraccion = Console.ReadLine();
split = fraccion.Split(char.Parse("/"));
for(int i=0;i<2;i++) valor[i] = Int32.Parse(split[i]);
if(valor[0]>=valor[1])factorizar(ref valor[0],ref valor[1]);
else factorizar(ref valor[1],ref valor[0]);
Console.WriteLine("{0}/{1}",valor[0],valor[1]);
}
}
}
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.
@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
CREATE TABLE contacto(
nombre VARCHAR(50) NOT NULL,
sexo CHAR(1),
edad INT,
tlf CHAR(9) NOT NULL,
CONSTRAINT KeyAgenda PRIMARY KEY (nombre, tlf),
CONSTRAINT CaracterSexo CHECK sexo IN ('H', 'M')
);
Y aquí el programa
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//Para conectar con base de datos
using MySql.Data.MySqlClient;
namespace Agenda
{
class Program
{
private bool abierto = false;
private MySqlDataReader Reader;
private MySqlConnection connection;
private MySqlCommand command;
private int numContactos = 0;
private string MyConString;
private bool encontrar(string nom, string tel)
{
bool ret = false;
if (numContactos != 0)
{
string comando = "SELECT * FROM contacto "
+ "WHERE nombre = '" + nom + "' AND "
+ "tlf = '" + tel + "';";
//Comando de selección para la búsqueda
command.CommandText = comando;
Reader = command.ExecuteReader();
while ((Reader.Read()) && (ret == false))
ret = true; //Si llega a entrar en el bucle es que por lo menos
//ha encontrado un dato. Al estar buscando por la
//clave primaria de la relación, sólo debería devolver
//un único valor, el buscado.
Reader.Dispose();
}
return ret;
}
public void agregarCon(string nom, char sex, int edad, string tlf)
{
if (!encontrar(nom, tlf))
{
string agrega = "INSERT INTO contacto VALUES('" + nom + "','" + sex + "','" + edad + "','" + tlf + "');";
command.CommandText = agrega;
command.ExecuteNonQuery();
numContactos++;
}
else
{
System.Console.WriteLine("Contacto previamente accesible en la tabla");
}
}
public void imprimeAgenda()
{
if (numContactos != 0)
{
command.CommandText = "SELECT * FROM contacto;";
Reader = command.ExecuteReader();
while (Reader.Read())
{
for (int i = 0; i < Reader.FieldCount; i++)
System.Console.Write(Reader.GetValue(i).ToString() + " ");
System.Console.Write("\n");
}
Reader.Dispose();
}
}
public void editarContacto(string nom, string tel)
{
if (numContactos != 0)
{
//Variables para la edición
string nnom;
char nsex;
int nedad;
string ntel;
System.Console.WriteLine("Nuevo nombre: ");
do
{
nnom = System.Console.ReadLine();
System.Console.WriteLine();
}while(nnom.Length>50);
System.Console.WriteLine("Nuevo sexo: ");
do
{
string aux = System.Console.ReadLine();
nsex = aux[0];
System.Console.WriteLine();
} while ((nsex != 'M') && (nsex != 'H'));
System.Console.WriteLine("Nueva edad: ");
do
{
try
{
nedad = Convert.ToInt32(System.Console.ReadLine());
}
catch (InvalidCastException)
{
nedad = -1;
}
} while (nedad == -1);
System.Console.WriteLine("Nuevo teléfono: ");
do
{
ntel = System.Console.ReadLine();
System.Console.WriteLine();
} while (ntel.Length > 9);
eliminaContacto(nom, tel);
agregarCon(nnom, nsex, nedad, ntel);
}
}
public void eliminaContacto(string nom, string tel)
{
if (encontrar(nom, tel))
{
string comando = "DELETE FROM contacto "+
"WHERE nombre = '"+nom+"' AND tlf = '"+tel+"';";
command.CommandText = comando;
command.ExecuteNonQuery();
System.Console.WriteLine("Contacto modificado satisfactoriamente");
}
else
{
System.Console.WriteLine("Contacto no encontrado...");
}
}
public int getNumContactos()
{
return numContactos;
}
~Program()
{
if (abierto)
{
Reader.Close();
connection.Close();
}
}
Program()
{
MyConString = "SERVER=localhost;" +
"DATABASE=agenda;" +
"UID=usuario;" +
"PASSWORD=user;";
connection = new MySqlConnection(MyConString);
command = connection.CreateCommand();
connection.Open();
abierto = true;
command.CommandText = "SELECT * FROM contacto;";
Reader = command.ExecuteReader();
while (Reader.Read())
numContactos++;
Reader.Dispose();
}
public static void menu()
{
System.Console.WriteLine("---------MENU---------");
System.Console.WriteLine("1.- Agregar contacto");
System.Console.WriteLine("2.- Modificar contacto");
System.Console.WriteLine("3.- Eliminar contacto");
System.Console.WriteLine("4.- Ver Base actual");
System.Console.WriteLine("5.- Salir");
System.Console.Write("Elija una opción: ");
}
static void Main(string[] args)
{
Program obj = new Program();
int opcion;
string nnom;
char nsex;
int nedad;
string ntel;
try
{
do
{
Console.Clear();
Program.menu();
try
{
opcion = Convert.ToInt32(System.Console.ReadLine());
}
catch (InvalidCastException)
{
opcion = 0;
}
System.Console.WriteLine();
switch (opcion)
{
case 1:
System.Console.WriteLine("Nombre: ");
do
{
nnom = System.Console.ReadLine();
System.Console.WriteLine();
} while (nnom.Length > 50);
System.Console.WriteLine("Sexo: ");
do
{
string aux = System.Console.ReadLine();
nsex = aux[0];
System.Console.WriteLine();
} while ((nsex != 'M') && (nsex != 'H'));
System.Console.WriteLine("Edad: ");
do
{
try
{
nedad = Convert.ToInt32(System.Console.ReadLine());
}
catch (InvalidCastException)
{
nedad = -1;
}
} while (nedad == -1);
System.Console.WriteLine("Teléfono: ");
do
{
ntel = System.Console.ReadLine();
System.Console.WriteLine();
} while (ntel.Length > 50);
obj.agregarCon(nnom, nsex, nedad, ntel);
System.Console.ReadLine();
break;
case 2:
System.Console.WriteLine("Nombre: ");
do
{
nnom = System.Console.ReadLine();
System.Console.WriteLine();
} while (nnom.Length > 50);
System.Console.WriteLine("Teléfono: ");
do
{
ntel = System.Console.ReadLine();
System.Console.WriteLine();
} while (ntel.Length > 50);
obj.editarContacto(nnom, ntel);
System.Console.ReadLine();
break;
case 3:
System.Console.WriteLine("Nombre: ");
do
{
nnom = System.Console.ReadLine();
System.Console.WriteLine();
} while (nnom.Length > 50);
System.Console.WriteLine("Teléfono: ");
do
{
ntel = System.Console.ReadLine();
System.Console.WriteLine();
} while (ntel.Length > 50);
obj.eliminaContacto(nnom, ntel);
System.Console.ReadLine();
break;
case 4:
obj.imprimeAgenda();
System.Console.ReadLine();
break;
case 5:
break;
default:
System.Console.WriteLine("Opción incorrecta");
System.Console.ReadLine();
break;
}
} while (opcion != 5);
}
catch (MySqlException e)
{
System.Console.WriteLine("Excepción: " + e.Message);
}
finally
{
System.Console.WriteLine("Presione una tecla para salir");
System.Console.ReadLine();
}
}
}
}
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