Compare commits

...

52 Commits

Author SHA1 Message Date
8671a962b4 gtk hello3 button 2023-07-05 11:28:28 +02:00
695a1defaf gtk4 hello1 hello2 2023-07-04 12:53:21 +02:00
000f8f72a2 organizado en carpetas 2023-07-04 12:18:40 +02:00
d9f4748095 reto15 iniciado 2023-07-03 18:02:50 +02:00
40ceace587 copy trait 2023-07-03 17:43:20 +02:00
fd3dd1845e reto14 terminado 2023-07-03 10:47:14 +02:00
608531751c reto14 empezado 2023-07-02 17:53:08 +02:00
e442e0e89f prop ownership 2023-07-02 17:04:33 +02:00
4507728150 reto13 terminado 2023-07-02 12:25:06 +02:00
ce61363ec0 reto13 iniciando loop 2023-07-01 18:33:05 +02:00
851f81a443 reto13 2023-06-30 16:14:07 +02:00
df7aa7d898 reto13 while intentos>0 2023-06-30 13:18:52 +02:00
e64671f6a1 reto13 caracteres a ocultar 2023-06-29 16:29:25 +02:00
9c563d915c reto13 obtenida palabra 2023-06-28 23:53:42 +02:00
8c5c1c32a8 reto13 empezado 2023-06-28 17:37:22 +02:00
f4800c58e8 reto12 terminado 2023-06-26 12:15:35 +02:00
f311fc4dd1 iflet 2023-06-26 11:46:57 +02:00
0116149495 reto11 finalizado 2023-06-25 12:19:59 +02:00
117cc87783 reto10 terminado 2023-06-23 17:31:56 +02:00
643fda700c enums 2023-06-23 17:00:46 +02:00
e5271ed247 reto08 terminado 2023-06-23 11:06:07 +02:00
05a39284f9 reto08 fix, ahora puede dar cero 2023-06-23 07:37:06 +02:00
b9e4b1f385 reto08 terminado 2023-06-22 17:56:51 +02:00
7d9450217c tuple struct 2023-06-22 14:46:17 +02:00
ce7dd49028 reto07 terminado 2023-06-22 14:35:36 +02:00
de1be634a3 reto07 todas las preguntas 2023-06-21 16:55:07 +02:00
bc4795416a reto07 segunda pregunta 2023-06-21 10:49:09 +02:00
a8445c6415 reto07 while no fallo 2023-06-21 08:30:37 +02:00
6ecf1e0e24 reto07 empezado 2023-06-19 16:23:05 +02:00
eec80bdf24 struct en multiples archivos 2023-06-19 11:46:38 +02:00
d60fd485e8 reto06 piedra papel tijera lagarto spook 2023-06-19 11:04:13 +02:00
db0cb83b84 primeros pasos reto06 2023-06-17 11:30:59 +02:00
10ed6c0c03 enunciado reto06 2023-06-16 15:50:41 +02:00
cafb564382 reto05 2023-06-15 17:15:33 +02:00
a73b6dc300 reto04 2023-06-15 13:24:38 +02:00
468e90ac55 reto03 finish 2023-06-15 10:45:23 +02:00
ad298b5e75 reto03 14062023 17:48 2023-06-14 17:48:33 +02:00
3ef50a1bac corrección números de los retos & reto03 2023-06-14 16:30:26 +02:00
618c949452 reto03 2023-06-14 14:07:53 +02:00
fbf3cad39a reto01 añadido el espacio 2023-06-13 16:35:02 +02:00
0cb757c9e4 reto01 2023-06-13 16:27:12 +02:00
119e10c2a0 reto00 2023-06-13 15:15:19 +02:00
140359f02d memorias y struct 2023-06-10 13:18:21 +02:00
321e92f717 punto y coma 2023-06-09 18:08:58 +02:00
4af7058ed7 funciones recursivas 2023-06-09 14:31:12 +02:00
61e19478bd while 2023-06-09 12:54:08 +02:00
6e1cd4e0fc nombre y arreglos2 2023-06-08 18:43:55 +02:00
07d62f050e iteradores y _ 2023-06-06 13:44:20 +02:00
d9437e766d cierre 2023-06-06 11:40:05 +02:00
7fe484d94e match, struct e impl 2023-06-04 12:51:58 +02:00
327e1279fc funciones y metodos - struct e impl 2023-06-04 12:50:23 +02:00
a077149208 math 2023-06-04 12:50:00 +02:00
117 changed files with 1751 additions and 54 deletions

View File

@@ -1,17 +0,0 @@
https://tinchicus.com/2022/09/26/rust-listado-del-curso-inicial/
- https://tinchicus.com/2022/06/01/rust-usando-a-cargo/ (hola_mundo)
- https://tinchicus.com/2022/06/03/rust-strings/ (cadenas)
- https://tinchicus.com/2022/06/06/rust-arrays/ (arreglos)
- https://tinchicus.com/2022/06/07/rust-vector/ (vectores)
- https://tinchicus.com/2022/06/08/rust-tuple/ (tupla)
- https://tinchicus.com/2022/06/09/rust-hash-map/ (mapeo)
- https://tinchicus.com/2022/06/10/rust-slice/ (slices)
- https://tinchicus.com/2022/06/13/rust-pasando-valores/ (porvalor y porreferencia)
- https://tinchicus.com/2022/06/14/rust-la-libreria-std/
- https://tinchicus.com/2022/06/15/rust-println/ (println)
- https://tinchicus.com/2022/06/16/rust-format/ (format)
- https://tinchicus.com/2022/06/17/rust-read_line/ (entrada)
- https://tinchicus.com/2022/06/20/rust-argumentos/ (argumento)
- https://tinchicus.com/2022/06/21/rust-for/ (bucles)
- https://tinchicus.com/2022/06/22/rust-if/ (condicion)

7
arreglos/Cargo.lock generated
View File

@@ -1,7 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "arreglos"
version = "0.1.0"

7
cadenas/Cargo.lock generated
View File

@@ -1,7 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "cadenas"
version = "0.1.0"

View File

@@ -0,0 +1,35 @@
## https://tinchicus.com/2022/09/26/rust-listado-del-curso-inicial/
- https://tinchicus.com/2022/06/01/rust-usando-a-cargo/ (hola_mundo)
- https://tinchicus.com/2022/06/03/rust-strings/ (cadenas)
- https://tinchicus.com/2022/06/06/rust-arrays/ (arreglos)
- https://tinchicus.com/2022/06/07/rust-vector/ (vectores)
- https://tinchicus.com/2022/06/08/rust-tuple/ (tupla)
- https://tinchicus.com/2022/06/09/rust-hash-map/ (mapeo)
- https://tinchicus.com/2022/06/10/rust-slice/ (slices)
- https://tinchicus.com/2022/06/13/rust-pasando-valores/ (porvalor y porreferencia)
- https://tinchicus.com/2022/06/14/rust-la-libreria-std/
- https://tinchicus.com/2022/06/15/rust-println/ (println)
- https://tinchicus.com/2022/06/16/rust-format/ (format)
- https://tinchicus.com/2022/06/17/rust-read_line/ (entrada)
- https://tinchicus.com/2022/06/20/rust-argumentos/ (argumento)
- https://tinchicus.com/2022/06/21/rust-for/ (bucles)
- https://tinchicus.com/2022/06/22/rust-if/ (condicion)
- https://tinchicus.com/2022/06/23/rust-match/ (coincidir)
- https://tinchicus.com/2022/06/24/rust-funciones-y-metodos/ (ejemplo01)
- https://tinchicus.com/2022/06/27/rust-closures/ (cierre)
- https://tinchicus.com/2022/06/28/rust-iteradores/ (iter)
- https://tinchicus.com/2022/06/29/rust-el-parametro-_/ (bucles2)
- https://tinchicus.com/2022/06/30/rust-loop-27/ (arreglos2)
- https://tinchicus.com/2022/07/01/rust-loop-labels/ (nombre)
- https://tinchicus.com/2022/07/04/rust-while/ (while)
- https://tinchicus.com/2022/07/05/rust-funciones-recursivas/ (recursiva)
- https://tinchicus.com/2022/07/06/rust-punto-y-coma/ (ejemplo02)
- https://tinchicus.com/2022/07/12/rust-memoria-estatica/ (ejemplo03)
- https://tinchicus.com/2022/07/13/rust-struct/ (estructura)
- https://tinchicus.com/2022/07/14/rust-struct-en-multiples-archivos/ (estructura2)
- https://tinchicus.com/2022/07/15/rust-tuple-struct/ (nuevotipo)
- https://tinchicus.com/2022/07/18/rust-enum/ (enums)
- https://tinchicus.com/2022/07/19/rust-patrones-y-coincidencias/ (iflet)
- https://tinchicus.com/2022/07/20/rust-ownership/ (prop)
- https://tinchicus.com/2022/07/21/rust-copy-trait/ (copiari32, copiar)

View File

@@ -0,0 +1,8 @@
[package]
name = "arreglos2"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,12 @@
fn main() {
let mi_arreglo = ["Lovecraft", "Poe", "Barker", "King"];
let mut i = 0;
loop {
if i >= mi_arreglo.len() {
break;
}
println!("{}", mi_arreglo[i]);
i = i + 1;
}
}

View File

@@ -0,0 +1,8 @@
[package]
name = "bucles2"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,8 @@
fn main() {
let mi_arreglo = ["Lovecraft", "Poe", "Barker", "King"];
// Evita avisos en el compilador y sirve para almacenar datos que no son necesarios
for (_, apellido) in mi_arreglo.iter().enumerate() {
println!("{}", apellido);
}
}

View File

@@ -0,0 +1,8 @@
[package]
name = "cierre"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,39 @@
use std::thread;
use std::time::Duration;
fn rutina_ejercicio(i: u32, a: u32) {
let cierre = |num| {
println!("Recalculando...");
thread::sleep(Duration::from_secs(2));
num
};
if i < 25 {
println!("Hoy haz {} sentadillas", cierre(i));
println!("Despues haz {} sentadillas", cierre(i));
} else {
if a == 3 {
println!("Descansa un poco y recuerda hidratarte");
} else {
println!("Hoy corre por {} minutos", cierre(i));
}
}
}
fn main() {
let valor_especificado = 27;
let numero_al_azar = 5;
rutina_ejercicio(valor_especificado, numero_al_azar);
// ejemplo creado por mi
let imprime_algo = |texto| {
println!("WTF!!!!!");
texto
};
println!(
"Vamos a imprimir el texto....{}",
imprime_algo("Mis cojones mangas 3")
)
}

View File

@@ -0,0 +1,8 @@
[package]
name = "coincidir"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,46 @@
fn main() {
let booleano = false;
let binario;
match booleano {
false => binario = 0,
true => binario = 1,
}
println!("{} -> {}", booleano, binario);
let booleano = !booleano;
let binario = match booleano {
false => 0,
true => 1,
};
println!("{} -> {}", booleano, binario);
let x = 1;
match x {
1 | 2 | 3 => println!("Works"),
_ => println!("Noooo"),
}
match x {
1..=10 => println!("Works to"),
_ => println!("Noooo"),
}
let y = 'G';
match y {
'A'..='Z' => println!("Works to"),
_ => println!("Noooo"),
}
match y {
p @ 'A'..='Z' => println!("{}", p),
_ => println!("Noo"),
}
match y {
p @ 'A'..='F' | p @ 'G'..='Z' => println!("{}", p),
_ => println!("Noo"),
}
}

View File

@@ -0,0 +1,8 @@
[package]
name = "copiar"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,12 @@
fn sumar(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) {
let sum = v1.iter().fold(0i32, |a, &b| a + b);
let prod = v2.iter().fold(1i32, |a, &b| a * b);
return (v1, v2, sum + prod);
}
fn main() {
let vecuno = vec![2, 3, 5];
let vecdos = vec![3, 5];
let (vecuno, vecdos, rta) = sumar(vecuno, vecdos);
println!("{} + {} = {}", vecuno[0], vecdos[0], rta);
}

View File

@@ -0,0 +1,8 @@
[package]
name = "copiari32"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,9 @@
fn incrementar(n: i32) -> i32 {
n + 32
}
fn main() {
let num = 10i32;
let num2 = incrementar(num);
println!("num: {}, num2: {}", num, num2);
}

View File

@@ -0,0 +1,8 @@
[package]
name = "ejemplo01"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,14 @@
struct Perro {
peso: i32,
edad: i32,
}
impl Perro {
fn nuevo(a: i32, b: i32) -> Perro {
Perro { peso: a, edad: b }
}
}
fn main() {
let perro = Perro::nuevo(98, 87);
println!("{} {}", perro.edad, perro.peso);
}

View File

@@ -0,0 +1,8 @@
[package]
name = "ejemplo02"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,22 @@
fn main() {
let x = 5u32;
let y = {
let x_cuadrado = x * x;
let x_cubo = x_cuadrado * x;
x_cubo + x_cuadrado + x
};
// La variable z no tiene ningún valor, no es devuelto por el punto y coma
let z = {
2 * x;
};
// la variable h tiene el valor de 2*x por que es devuelta al no tener punto y coma.
let h = { 2 * x };
println!("x es {:?}", x);
println!("y es {:?}", y);
println!("z es {:?}", z);
println!("h es {:?}", h);
}

View File

@@ -0,0 +1,8 @@
[package]
name = "ejemplo03"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,16 @@
fn main() {
let x = 5u32;
let y: &u32;
{
let x_cuadrado = x * x;
let x_cubo = x_cuadrado * x;
// da un error por que la memoria es eliminada
// cuando es eliminado el scope
y = &(x_cubo + x_cuadrado + x);
};
let z = { 2 * x };
println!("x={}, y={}, z={}", z, y, z)
}

View File

@@ -0,0 +1,8 @@
[package]
name = "enums"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,32 @@
enum Numerado1 {
TipoTuple(f32, i32, String),
TipoStruct { var1: i32, var2: f32 },
StructTuple(i32),
Variable,
}
enum Numerado2 {
TipoTuple(f32, i32, String),
TipoStruct { var1: i32, var2: f32 },
StructTuple(i32),
}
fn main() {
let mut texto1 = "".to_owned();
let mut texto2 = "".to_owned();
let mut num1 = 0f32;
let valor = Numerado1::TipoTuple(3.14, 1, "Hola".to_owned());
let valor2 = Numerado2::TipoTuple(3.14, 0, "Mundo".to_owned());
if let Numerado1::TipoTuple(f, i, s) = valor {
texto1 = s;
num1 = f;
}
if let Numerado2::TipoTuple(f, i, s) = valor2 {
texto2 = s;
}
println!("{}, {}! del hombre {}", texto1, texto2, num1)
}

View File

@@ -0,0 +1,8 @@
[package]
name = "estructura"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,65 @@
struct Persona {
nombre: String,
edad: i32,
apellido: String,
}
struct Area {
oficina: String,
puesto: String,
}
struct Persona2 {
nombre: String,
edad: i32,
apellido: String,
area: Area,
}
fn main() {
// usuario1
let usuario = Persona {
nombre: String::from("Martín"),
apellido: String::from("Miranda"),
edad: 33,
};
println!(
"{} {}, {} años",
usuario.nombre, usuario.apellido, usuario.edad
);
// usuario2
let mut usuario2 = Persona {
nombre: String::from("Federico"),
apellido: String::from("Caco"),
edad: 12,
};
// se puede cambiar por que usuario2 es mutable
usuario2.edad = 22;
println!(
"{} {}, {} años",
usuario2.nombre, usuario2.apellido, usuario2.edad
);
// struct dentro de un struct
// usuario3
let mut usuario3 = Persona2 {
nombre: String::from("Lucas"),
apellido: String::from("Pelotas"),
edad: 76,
area: Area {
oficina: String::from("IT"),
puesto: String::from("Tecnico"),
},
};
usuario3.edad = 45;
println!("Nombre: {}", usuario3.nombre);
println!("Apellido: {}", usuario3.apellido);
println!("Edad: {}", usuario3.edad);
println!("Oficina: {}", usuario3.area.oficina);
println!("Puesto: {}", usuario3.area.puesto);
}

View File

@@ -0,0 +1,8 @@
[package]
name = "estructura2"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,47 @@
mod persona;
use persona::*;
fn main() {
let usuario = Persona {
nombre: String::from("Martin"),
apellido: String::from("Miranda"),
edad: 45,
area: Area {
oficina: String::from("IT"),
puesto: String::from("Desarrollador"),
},
nomina: Nomina {
bruto: 100000,
neto: 50000,
},
};
println!("Nombre: {}", usuario.nombre);
println!("Apellido: {}", usuario.apellido);
println!("Edad: {}", usuario.edad);
println!("Oficina: {}", usuario.area.oficina);
println!("Puesto: {}", usuario.area.puesto);
println!("Bruto: {}", usuario.nomina.bruto);
println!("Neto: {}", usuario.nomina.neto);
let usuario2 = Persona {
nombre: String::from("Enzo"),
apellido: String::from("Tortore"),
edad: 33,
area: Area {
oficina: String::from("DB"),
puesto: String::from("Administrador"),
},
nomina: Nomina {
bruto: usuario.nomina.bruto,
neto: usuario.nomina.neto,
},
};
println!("Nombre: {}", usuario2.nombre);
println!("Apellido: {}", usuario2.apellido);
println!("Edad: {}", usuario2.edad);
println!("Oficina: {}", usuario2.area.oficina);
println!("Puesto: {}", usuario2.area.puesto);
println!("Bruto: {}", usuario2.nomina.bruto);
println!("Neto: {}", usuario2.nomina.neto);
}

View File

@@ -0,0 +1,4 @@
pub struct Area {
pub oficina: String,
pub puesto: String,
}

View File

@@ -0,0 +1,12 @@
pub mod area;
pub use area::*;
pub mod nomina;
pub use nomina::*;
pub struct Persona {
pub nombre: String,
pub edad: i32,
pub apellido: String,
pub area: Area,
pub nomina: Nomina,
}

View File

@@ -0,0 +1,4 @@
pub struct Nomina {
pub bruto: i32,
pub neto: i32,
}

View File

@@ -0,0 +1,8 @@
[package]
name = "iflet"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,14 @@
fn main() {
let x = 1;
match x {
1 => println!("uno"),
_ => println!("no encontrado"),
}
if let 1 = x {
println!("uno")
} else {
println!("no encontrado")
}
}

View File

@@ -0,0 +1,8 @@
[package]
name = "iter"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,17 @@
fn main() {
let v1 = vec![1, 2, 3];
let v1_iter = v1.iter();
for val in v1_iter {
println!("{}", val);
}
let v2 = vec![50, 100, 200];
let v2_iter = v2.iter();
v2_iter.for_each(|e| print!("{}, ", e));
let mut v3 = vec![50, 100, 200];
v3.iter_mut().for_each(|e| *e += 23);
println!("{:?}", v3)
}

View File

@@ -0,0 +1,8 @@
[package]
name = "nombre"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,13 @@
fn main() {
'bucle_externo: for x in 0..10 {
'bucle_interno: for y in 0..10 {
if x % 2 == 0 {
continue 'bucle_externo;
}
if y % 2 != 0 {
continue 'bucle_interno;
}
println!("X: {}, Y: {}", x, y);
}
}
}

View File

@@ -0,0 +1,8 @@
[package]
name = "nuevotipo"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,11 @@
// tuple-struct;
struct MiPi(f32);
fn main() {
// creamos objeto del tipo MiPi
let mi_pi = MiPi(22f32 / 7f32);
println!("mi_pi = {:?}", mi_pi.0);
// asignación de patrón de tipo nuevo
let MiPi(pi) = mi_pi;
println!("pi = {}", pi);
}

View File

@@ -0,0 +1,8 @@
[package]
name = "prop"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,9 @@
fn vec_transfer(v: Vec<i32>) {
println!("v[0] en la función = {}", v[0]);
}
fn main() {
let mivec = vec![1i32,2i32,3i32];
vec vec_transfer(mivec);
println!("mivec[0] es = {}", mivec[0]);
}

View File

@@ -0,0 +1,8 @@
[package]
name = "recursiva"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,19 @@
fn recursivo(n: i32) {
let mut _v: i32 = 0;
if n % 2 == 0 {
_v = n / 2;
} else {
_v = 3 * n + 1;
}
println!("{}", _v);
if _v != 1 {
recursivo(_v)
}
}
fn main() {
recursivo(12)
}

View File

@@ -0,0 +1,16 @@
fn primera_palabra(s: &String) -> usize {
let b = s.as_bytes();
for (i, &item) in b.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
fn main() {
let s = String::from("Hola Mundo Cruel");
let pos = primera_palabra(&s);
let palabra = &s[0..pos];
println!("{}", palabra);
}

View File

@@ -0,0 +1,8 @@
[package]
name = "whileloop"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,9 @@
fn main() {
let mi_arreglo = ["Lovecraft", "Poe", "Barker", "King"];
let mut i = 0;
while i < mi_arreglo.len() {
println!("{}", mi_arreglo[i]);
i = i + 1;
}
}

3
ejercicios/README.md Normal file
View File

@@ -0,0 +1,3 @@
# Ejercicios de:
### https://github.com/mouredev/retos-programacion-2023

View File

@@ -0,0 +1,8 @@
[package]
name = "reto00"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,22 @@
/*
* Escribe un programa que muestre por consola (con un print) los
* números de 1 a 100 (ambos incluidos y con un salto de línea entre
* cada impresión), sustituyendo los siguientes:
* - Múltiplos de 3 por la palabra "fizz".
* - Múltiplos de 5 por la palabra "buzz".
* - Múltiplos de 3 y de 5 a la vez por la palabra "fizzbuzz".
*/
fn main() {
for num in 1..101 {
let mut texto = num.to_string();
if num % 3 == 0 && num % 5 == 0 {
texto = String::from("fizzbuzz")
} else if num % 3 == 0 {
texto = String::from("fizz")
} else if num % 5 == 0 {
texto = String::from("buzz")
}
println!("{}", texto)
}
}

View File

@@ -0,0 +1,8 @@
[package]
name = "reto01"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,60 @@
/*
* Escribe un programa que reciba un texto y transforme lenguaje natural a
* "lenguaje hacker" (conocido realmente como "leet" o "1337"). Este lenguaje
* se caracteriza por sustituir caracteres alfanuméricos.
* - Utiliza esta tabla (https://www.gamehouse.com/blog/leet-speak-cheat-sheet/)
* con el alfabeto y los números en "leet".
* (Usa la primera opción de cada transformación. Por ejemplo "4" para la "a")
*/
fn main() {
let alphabet = String::from_utf8((b'A'..=b'Z').chain(b'0'..=b'9').collect()).unwrap();
println!("{}", alphabet);
let respuesta = [
"4",
"l3",
"[",
")",
"3",
"|=",
"&",
"#",
"1",
",_|",
">|",
"1",
"^^",
"^",
"0",
"|*",
"(_,)",
"l2",
"hu",
"gg",
"pesadooooooooo",
"0",
"yy",
"2",
"3",
"4",
];
let vecalphabet: Vec<_> = alphabet.split("").collect();
let texto = String::from("wtf hijo de puta hay que decirlo mas").to_uppercase();
let vectexto: Vec<_> = texto.split("").collect();
let mut textfinal = "".to_string();
for item in vectexto {
if alphabet.contains(item) {
let index = vecalphabet
.iter()
.position(|&r| r == item.to_string())
.unwrap();
if index != 0 {
//println!("es->{}", respuesta[index]);
textfinal += &respuesta[index].to_string();
}
} else if item == " ".to_string() {
textfinal += &" ".to_string()
}
}
println!("{}", textfinal)
}

View File

@@ -0,0 +1,8 @@
[package]
name = "reto03"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,57 @@
/*
* Escribe un programa que muestre cómo transcurre un juego de tenis y quién lo ha ganado.
* El programa recibirá una secuencia formada por "P1" (Player 1) o "P2" (Player 2), según quien
* gane cada punto del juego.
*
* - Las puntuaciones de un juego son "Love" (cero), 15, 30, 40, "Deuce" (empate), ventaja.
* - Ante la secuencia [P1, P1, P2, P2, P1, P2, P1, P1], el programa mostraría lo siguiente:
* 15 - Love
* 30 - Love
* 30 - 15
* 30 - 30
* 40 - 30
* Deuce
* Ventaja P1
* Ha ganado el P1
* - Si quieres, puedes controlar errores en la entrada de datos.
* - Consulta las reglas del juego si tienes dudas sobre el sistema de puntos.
*/
fn main() {
let secuencia = vec!["P1", "P1", "P2", "P2", "P1", "P2", "P1", "P1"];
let puntos = vec!["Love", "15", "30", "40"];
let mut jugador1 = 0;
let mut jugador2 = 0;
let mut puntos1;
let mut puntos2;
for ele in secuencia {
if ele == "P1" {
jugador1 += 1;
} else if ele == "P2" {
jugador2 += 1;
}
if jugador1 < puntos.len() {
puntos1 = puntos[jugador1].to_string();
} else {
puntos1 = "+".to_string();
}
puntos2 = if jugador2 < puntos.len() {
puntos[jugador2].to_string()
} else {
"+".to_string()
};
if jugador1 > 2 && jugador2 > 2 && jugador1 == jugador2 {
println!("Deuce");
} else if jugador1 > 2 && jugador2 > 2 && jugador1 + 1 == jugador2 {
println!("Ventaja P2");
} else if jugador1 > 2 && jugador2 > 2 && jugador2 + 1 == jugador1 {
println!("Ventaja P1");
} else if jugador1 > 3 && jugador1 > jugador2 {
println!("Ha ganado el P1");
} else if jugador1 > 3 && jugador2 > jugador1 {
println!("Ha ganado el P2");
} else {
println!("{} - {}", puntos1, puntos2);
}
}
}

View File

@@ -0,0 +1,9 @@
[package]
name = "reto04"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8"

View File

@@ -0,0 +1,59 @@
/*
* Escribe un programa que sea capaz de generar contraseñas de forma aleatoria.
* Podrás configurar generar contraseñas con los siguientes parámetros:
* - Longitud: Entre 8 y 16.
* - Con o sin letras mayúsculas.
* - Con o sin números.
* - Con o sin símbolos.
* (Pudiendo combinar todos estos parámetros entre ellos)
*/
use rand::Rng;
fn main() {
// configurar:
let veces = 13;
let mayusculas = true;
let numeros = true;
let simbolos = true;
let mut caracteres = String::from_utf8((b'a'..=b'z').collect()).unwrap();
if mayusculas {
let string_mayusculas = String::from_utf8((b'A'..=b'Z').collect()).unwrap();
caracteres += string_mayusculas.to_string().as_str();
}
if numeros {
let string_numeros = String::from_utf8((b'0'..=b'9').collect()).unwrap();
caracteres += string_numeros.to_string().as_str();
}
if simbolos {
for num in 33..48 {
let u8 = num as u8;
let caracter = u8 as char;
caracteres += caracter.to_string().as_str();
}
for num in 58..65 {
let u8 = num as u8;
let caracter = u8 as char;
caracteres += caracter.to_string().as_str();
}
for num in 91..97 {
let u8 = num as u8;
let caracter = u8 as char;
caracteres += caracter.to_string().as_str();
}
for num in 123..127 {
let u8 = num as u8;
let caracter = u8 as char;
caracteres += caracter.to_string().as_str();
}
}
println!("Caracteres: {}", caracteres);
let mut texto: String = String::new();
for _ in 0..veces {
let num = rand::thread_rng().gen_range(0..caracteres.len());
let caracter = caracteres.chars().nth(num).unwrap();
texto += caracter.to_string().as_str();
}
println!("{}", texto.to_string());
}

View File

@@ -0,0 +1,8 @@
[package]
name = "reto04"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,65 @@
/*
* Escribe un programa que, dado un número, compruebe y muestre si es primo, fibonacci y par.
* Ejemplos:
* - Con el número 2, nos dirá: "2 es primo, fibonacci y es par"
* - Con el número 7, nos dirá: "7 es primo, no es fibonacci y es impar"
*/
fn esprimo(numero: i32) -> bool {
if numero == 0 || numero == 1 {
return false;
} else {
for i in 2..numero {
if numero % i == 0 {
return false;
}
}
return true;
}
}
fn esfibonacci(numero: i32) -> bool {
let mut vector_numeros = vec![0, 1];
let mut suma = vector_numeros[0] + vector_numeros[1];
while suma < numero {
vector_numeros.push(suma);
vector_numeros.drain(0..1);
suma = vector_numeros[0] + vector_numeros[1];
if suma > numero {
return false;
}
if suma == numero {
return true;
}
}
return false;
}
fn espar(numero: i32) -> bool {
if numero % 2 == 0 {
return true;
} else {
return false;
}
}
fn main() {
let num = 200;
let mut texto = String::new();
texto += &num.to_string();
if esprimo(num) {
texto += " es primo";
} else {
texto += " no es primo";
}
if esfibonacci(num) {
texto += ", fibonacci";
} else {
texto += ", no es fibonacci";
}
if espar(num) {
texto += " y es par";
} else {
texto += " y es impar";
}
println!("{}", texto);
}

View File

@@ -0,0 +1,8 @@
[package]
name = "reto05"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,11 @@
/*
* Escribe un !Hola Mundo! en todos los lenguajes de programación que puedas.
* Seguro que hay algún lenguaje que te llama la atención y nunca has utilizado,
* o quizás quieres dar tus primeros pasos... ¡Pues este es el momento!
*
* A ver quién se atreve con uno de esos lenguajes que no solemos ver por ahí...
*/
fn main() {
println!("Hello, world!");
}

View File

@@ -0,0 +1,9 @@
[package]
name = "reto06"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8"

View File

@@ -0,0 +1,52 @@
/*
* Crea un programa que calcule quien gana más partidas al piedra,
* papel, tijera, lagarto, spock.
* - El resultado puede ser: "Player 1", "Player 2", "Tie" (empate)
* - La función recibe un listado que contiene pares, representando cada jugada.
* - El par puede contener combinaciones de "🗿" (piedra), "📄" (papel),
* "✂️" (tijera), "🦎" (lagarto) o "🖖" (spock).
* - Ejemplo. Entrada: [("🗿","✂️"), ("✂️","🗿"), ("📄","✂️")]. Resultado: "Player 2".
* - Debes buscar información sobre cómo se juega con estas 5 posibilidades.
Reglas del juego piedra papel tijera lagarto Spock.
Tijera corta a papel.
Papel envuelve a piedra.
Piedra aplasta a lagarto.
Lagarto envenena a Spock.
Spock rompe a tijera.
Tijera decapita a lagarto.
Lagarto devora a papel.
Papel desautoriza a Spock.
Spock vaporiza a piedra.
Piedra aplasta a tijera.
*/
use rand::Rng;
fn main() {
let simbolos: Vec<&str> = vec!["piedra", "lagarto", "spook", "tijera", "papel"];
// random jugadas
let num1 = rand::thread_rng().gen_range(0..simbolos.len());
let num2 = rand::thread_rng().gen_range(0..simbolos.len());
let jugada: Vec<&str> = vec![simbolos[num1], simbolos[num2]];
println!("{} {}", jugada[0], jugada[1]);
if jugada[0] != jugada[1] {
let mut ordenado: Vec<&str> = Vec::new();
let mut index = simbolos.iter().position(|&r| r == jugada[0]).unwrap();
// println!("{} {}", index, jugada[0]);
for _ in 0..5 {
if index == simbolos.len() {
index = 0
}
ordenado.push(simbolos[index]);
index = index + 1;
}
if ordenado[1] == jugada[1] || ordenado[3] == jugada[1] {
println!("Player 1");
} else {
println!("Player 2");
}
} else {
println!("Empate");
}
}

View File

@@ -0,0 +1,8 @@
[package]
name = "reto07"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,169 @@
/*
* Crea un programa que simule el comportamiento del sombrero selccionador del
* universo mágico de Harry Potter.
* - De ser posible realizará 5 preguntas (como mínimo) a través de la terminal.
* - Cada pregunta tendrá 4 respuestas posibles (también a selecciona una a través de terminal).
* - En función de las respuestas a las 5 preguntas deberás diseñar un algoritmo que
* coloque al alumno en una de las 4 casas de Hogwarts (Gryffindor, Slytherin , Hufflepuff y Ravenclaw)
* - Ten en cuenta los rasgos de cada casa para hacer las preguntas y crear el algoritmo seleccionador.
* Por ejemplo, en Slytherin se premia la ambición y la astucia.
*/
use std::io;
fn main() {
let mut entrada: String = String::new();
while entrada.trim().parse::<i32>().is_err()
|| entrada.trim().parse::<i32>().unwrap() < 1
|| entrada.trim().parse::<i32>().unwrap() > 4
{
entrada.clear();
println!("Cuál es tu color preferido?");
println!("1. Azul");
println!("2. Rojo");
println!("3. Verde");
println!("4. Negro");
io::stdin().read_line(&mut entrada).unwrap();
}
let mut numero = entrada.trim().parse::<i32>().unwrap();
let mut gryffindor = 0;
let mut slytherin = 0;
let mut hufflepuff = 0;
let mut ravenclaw = 0;
match numero {
1 => gryffindor += 1,
2 => slytherin += 1,
3 => hufflepuff += 1,
4 => ravenclaw += 1,
_ => (),
}
entrada.clear();
while entrada.trim().parse::<i32>().is_err()
|| entrada.trim().parse::<i32>().unwrap() < 1
|| entrada.trim().parse::<i32>().unwrap() > 4
{
entrada.clear();
println!("A que velocidad vuela una paloma?");
println!("1. 130km/h");
println!("2. 340km/h");
println!("3. 500km/h");
println!("4. La europea o la asiática?");
io::stdin().read_line(&mut entrada).unwrap();
}
numero = entrada.trim().parse::<i32>().unwrap();
match numero {
2 => gryffindor += 1,
3 => slytherin += 1,
4 => hufflepuff += 1,
1 => ravenclaw += 1,
_ => (),
}
entrada.clear();
while entrada.trim().parse::<i32>().is_err()
|| entrada.trim().parse::<i32>().unwrap() < 1
|| entrada.trim().parse::<i32>().unwrap() > 4
{
entrada.clear();
println!("Los pelos del culo abrigan?");
println!("1. Si, digan lo que digan");
println!("2. demasiado calor");
println!("3. No, digan lo que digan");
println!("4. Que es un culo?");
io::stdin().read_line(&mut entrada).unwrap();
}
numero = entrada.trim().parse::<i32>().unwrap();
match numero {
3 => gryffindor += 1,
4 => slytherin += 1,
1 => hufflepuff += 1,
2 => ravenclaw += 1,
_ => (),
}
entrada.clear();
while entrada.trim().parse::<i32>().is_err()
|| entrada.trim().parse::<i32>().unwrap() < 1
|| entrada.trim().parse::<i32>().unwrap() > 4
{
entrada.clear();
println!("Desde Santurce a Bilbao");
println!("1. Voy con toa la cuadrilla");
println!("2. En coches de policia");
println!("3. Vengo deprisa y corriendo");
println!("4. Que me quiere ver el Juez?");
io::stdin().read_line(&mut entrada).unwrap();
}
numero = entrada.trim().parse::<i32>().unwrap();
match numero {
4 => gryffindor += 1,
1 => slytherin += 1,
2 => hufflepuff += 1,
3 => ravenclaw += 1,
_ => (),
}
entrada.clear();
while entrada.trim().parse::<i32>().is_err()
|| entrada.trim().parse::<i32>().unwrap() < 1
|| entrada.trim().parse::<i32>().unwrap() > 4
{
entrada.clear();
println!("Tipos de monederos");
println!("1. piel de pingüino");
println!("2. casco de bombero");
println!("3. escroto de jubilao");
println!("4. Que es un escroto?");
io::stdin().read_line(&mut entrada).unwrap();
}
numero = entrada.trim().parse::<i32>().unwrap();
match numero {
1 => gryffindor += 1,
2 => slytherin += 1,
3 => hufflepuff += 1,
4 => ravenclaw += 1,
_ => (),
}
let mut vec = vec![gryffindor, slytherin, hufflepuff, ravenclaw];
println!(
"Griffindor: {}, Slytherin: {}, Hufflepuff: {}, Ravenclaw: {}",
gryffindor, slytherin, hufflepuff, ravenclaw
);
vec.sort();
// Aquí decidimos el ganador
if vec[vec.len() - 1] == vec[vec.len() - 2] {
let mut ganador1 = String::from("");
let mut ganador2 = String::from("");
if gryffindor == vec[vec.len() - 1] {
ganador1 = String::from("Gryffindor");
}
if slytherin == vec[vec.len() - 1] {
if ganador1 == String::from("") {
ganador1 = String::from("Slytherin");
} else {
ganador2 = String::from("Slytherin");
}
}
if hufflepuff == vec[vec.len() - 1] {
if ganador1 == String::from("") {
ganador1 = String::from("Hufflepuff");
} else {
ganador2 = String::from("Hufflepuff");
}
}
if ravenclaw == vec[vec.len() - 1] {
ganador2 = String::from("Ravenclaw");
}
println!("Los ganadores son: {} y {}", ganador1, ganador2);
} else {
let mut ganador = String::from("");
if gryffindor == vec[vec.len() - 1] {
ganador = String::from("Gryffindor");
} else if slytherin == vec[vec.len() - 1] {
ganador = String::from("Slytherin");
} else if hufflepuff == vec[vec.len() - 1] {
ganador = String::from("Hufflepuff");
} else if ravenclaw == vec[vec.len() - 1] {
ganador = String::from("Ravenclaw");
}
println!("El ganador es: {}", ganador);
}
}

View File

@@ -0,0 +1,8 @@
[package]
name = "reto08"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,34 @@
/*
* Crea un generador de números pseudoaleatorios entre 0 y 100.
* - No puedes usar ninguna función "random" (o semejante) del lenguaje de programación seleccionado.
*
* Es más complicado de lo que parece...
*/
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
fn seudorandom() -> u32 {
let mut now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
.to_string()
.chars()
.collect::<String>()
.split("")
.collect::<Vec<&str>>()[10..13]
.join("")
.parse::<u32>()
.unwrap() as u32;
while now > 100 {
println!("{}", now);
now = now - 101;
}
now
}
fn main() {
let numero = seudorandom();
println!("El número es: {}", numero);
}

View File

@@ -0,0 +1,8 @@
[package]
name = "reto09"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,78 @@
/*
* Crea 3 funciones, cada una encargada de detectar si una cadena de
* texto es un heterograma, un isograma o un pangrama.
* - Debes buscar la definición de cada uno de estos términos.
* Heterograma: un conjunto de caracteres que no se repiten.
* Isograma: palabra sin letras repetidas (como ambidiestramente ) o, más ampliamente, una palabra en la que las letras aparecen el mismo número de veces.
* Pangrama: texto que contiene todas las letras del abecedario. Tengo un libro de papiroflexia sobre las hazañas y aventuras de Don Quijote de la Mancha en Kuwait.
*/
fn esheterograma(cadena: &str) -> bool {
let vectorcadena: Vec<char> = cadena.chars().collect();
let mut vectorvacio: Vec<char> = vec![];
for letra in vectorcadena.iter() {
if vectorvacio.contains(letra) {
return false;
} else {
vectorvacio.push(*letra);
}
}
return true;
}
fn esisograma(cadena: &str) -> bool {
let vectorcadena: Vec<char> = cadena.chars().collect();
let mut vectorcadenasinrepetir: Vec<char> = vec![];
let mut vectorvacio: Vec<i32> = vec![];
for letra in vectorcadena.iter() {
if !vectorcadenasinrepetir.contains(letra) {
// si no está se le añade un 1 al vector de numeros
vectorcadenasinrepetir.push(*letra);
vectorvacio.push(1);
} else {
// si está hay que buscarla y sumarle un 1 al vector de numeros
let index = vectorcadenasinrepetir
.iter()
.enumerate()
.find(|&r| r.1.to_string() == letra.to_string())
.unwrap()
.0;
vectorvacio[index] += 1;
}
}
for i in vectorvacio.iter() {
if i != &vectorvacio[0] {
return false;
}
}
return true;
}
fn espangrama(cadena: &str) -> bool {
let vectorcadena: Vec<char> = cadena.chars().collect();
let mut vectorabecedario: Vec<char> = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'ñ', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
]
.to_vec();
for letra in vectorcadena.iter() {
if !vectorabecedario.contains(letra) {
return false;
} else {
let index = vectorabecedario
.iter()
.enumerate()
.find(|&r| r.1.to_string() == letra.to_string())
.unwrap()
.0;
vectorabecedario.remove(index);
}
}
return true;
}
fn main() {
println!("{}", esheterograma("mis coj"));
println!("{}", esisograma("aabbccdgged"));
println!("{}", espangrama("abcdefghijklmnñopqrstuwxyza"));
}

View File

@@ -0,0 +1,10 @@
[package]
name = "reto10"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
reqwest = "0.11.12"
tokio = {version = "1", features = ["full"]}

View File

@@ -0,0 +1,23 @@
/*
* Llamar a una API es una de las tareas más comunes en programación.
*
* Implementa una llamada HTTP a una API (la que tú quieras) y muestra su
* resultado a través de la terminal. Por ejemplo: Pokémon, Marvel...
*
* Aquí tienes un listado de posibles APIs:
* https://github.com/public-apis/public-apis
*/
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let html: String = reqwest::get("https://bible-api.com/john%203:16") // Se pasa el url o endpoint con el cual se interacturara
.await? // Hace que reqwest espere por la respuesta del servidor
.text() //Convierte el resultado en un String
.await?;
// println!("{:?}", html);
let texto = html.as_str();
let vector: Vec<&str> = texto.split(":").collect();
println!("{}", vector[8]);
Ok(())
}

View File

@@ -0,0 +1,8 @@
[package]
name = "reto11"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

Some files were not shown because too many files have changed in this diff Show More