Skip to content

Commit a6ccc43

Browse files
Merge branch 'main' of github.com:mouredev/roadmap-retos-programacion into JesusAEE
2 parents b1444a1 + c32693a commit a6ccc43

File tree

8 files changed

+713
-0
lines changed

8 files changed

+713
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,5 @@
66
!stats.json
77
.DS_Store
88
.idea/
9+
pubspec.yaml
10+
pubspec.lock
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
2+
import 'package:intl/intl.dart';
3+
4+
/*
5+
* EJERCICIO:
6+
* Crea dos variables utilizando los objetos fecha (date, o semejante) de tu lenguaje:
7+
* - Una primera que represente la fecha (día, mes, año, hora, minuto, segundo) actual.
8+
* - Una segunda que represente tu fecha de nacimiento (te puedes inventar la hora).
9+
* Calcula cuántos años han transcurrido entre ambas fechas.
10+
*
11+
* DIFICULTAD EXTRA (opcional):
12+
* Utilizando la fecha de tu cumpleaños, formatéala y muestra su resultado de
13+
* 10 maneras diferentes. Por ejemplo:
14+
* - Día, mes y año.
15+
* - Hora, minuto y segundo.
16+
* - Día de año.
17+
* - Día de la semana.
18+
* - Nombre del mes.
19+
* (lo que se te ocurra...)
20+
*/
21+
22+
23+
void main()
24+
{
25+
DateTime date = DateTime.now();
26+
DateTime birthDay = DateTime(1991, 9, 14, 1, 0, 0);
27+
DateFormat dateFormatter = DateFormat('dd/MM/yyyy hh:mm');
28+
Duration dateDifference = date.difference(birthDay);
29+
30+
print('Fecha actual: ' + dateFormatter.format(date));
31+
print('Cumple : ' + dateFormatter.format(birthDay));
32+
print('Transcurrido: ${(dateDifference.inDays / 365).floor().toString()} años');
33+
34+
//Dificultad extra
35+
36+
DateFormat dateFormatter_ddMMyyyy = DateFormat('dd/MM/yyyy');
37+
DateFormat dateFormatter_hhmmss = DateFormat('hh:mm:ss');
38+
DateFormat dateFormatter_Completa = DateFormat('EEEE, dd MMMM, yyyy');
39+
DateFormat dateFormatter_diaSemana = DateFormat('EEEE');
40+
DateFormat dateFormatter_Mes = DateFormat('MMMM');
41+
42+
print('Cumple : ' + dateFormatter_ddMMyyyy.format(birthDay));
43+
print('Cumple : ' + dateFormatter_hhmmss.format(birthDay));
44+
print('Cumple : ' + dateFormatter_Completa.format(birthDay));
45+
print('Cumple : ' + dateFormatter_diaSemana.format(birthDay));
46+
print('Cumple : ' + dateFormatter_Mes.format(birthDay));
47+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
* EJERCICIO:
3+
* Utilizando tu lenguaje, crea un programa capaz de ejecutar de manera
4+
* asíncrona una función que tardará en finalizar un número concreto de
5+
* segundos parametrizables. También debes poder asignarle un nombre.
6+
* La función imprime su nombre, cuándo empieza, el tiempo que durará
7+
* su ejecución y cuando finaliza.
8+
*
9+
* DIFICULTAD EXTRA (opcional):
10+
* Utilizando el concepto de asincronía y la función anterior, crea
11+
* el siguiente programa que ejecuta en este orden:
12+
* - Una función C que dura 3 segundos.
13+
* - Una función B que dura 2 segundos.
14+
* - Una función A que dura 1 segundo.
15+
* - Una función D que dura 1 segundo.
16+
* - Las funciones C, B y A se ejecutan en paralelo.
17+
* - La función D comienza su ejecución cuando las 3 anteriores han
18+
* finalizado.
19+
*/
20+
21+
import 'dart:async';
22+
23+
void main() async
24+
{
25+
26+
//Ejecución en paralelo
27+
List<Future<void>> functions = [
28+
29+
showName('Función C', 3),
30+
showName('Función B', 2),
31+
showName('Función A', 1)
32+
];
33+
34+
await Future.wait(functions);
35+
36+
await showName('Función D', 1);
37+
}
38+
39+
Future<void> showName(String name, int duration) async
40+
{
41+
await Future.delayed(Duration(seconds: duration));
42+
print('Soy $name');
43+
}

Roadmap/25 - LOGS/c#/kenysdev.cs

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
#pragma warning disable CA1050 // for namespace Name
2+
/*
3+
╔══════════════════════════════════════╗
4+
║ Autor: Kenys Alvarado ║
5+
║ GitHub: https://github.com/Kenysdev ║
6+
║ 2024 - C# ║
7+
╚══════════════════════════════════════╝
8+
------------------------------------------
9+
* LOGS
10+
------------------------------------------
11+
Mas info: https://nlog-project.org/
12+
13+
*/
14+
using NLog;
15+
16+
// __________________________________
17+
class Program {
18+
19+
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
20+
static void Main() {
21+
/*
22+
* EJERCICIO #1:
23+
* Explora el concepto de "logging" en tu lenguaje. Configúralo y muestra
24+
* un ejemplo con cada nivel de "severidad" disponible.
25+
*/
26+
logger.Trace("Trace");
27+
logger.Debug("Debug");
28+
logger.Info("Info");
29+
logger.Warn("Warnin");
30+
logger.Error("Error");
31+
logger.Fatal("Fatal");
32+
33+
//__________________________________
34+
Console.WriteLine("\nEJERCICIO #2");
35+
ProgramTask tasks = new();
36+
37+
tasks.Add("a", "1");
38+
tasks.Add("b", "2");
39+
tasks.Add("c", "3");
40+
41+
tasks.Delete("b");
42+
tasks.ShowList();
43+
}
44+
}
45+
46+
/*
47+
__________________________________
48+
* EJERCICIO #2:
49+
* Crea un programa ficticio de gestión de tareas que permita añadir, eliminar
50+
* y listar dichas tareas.
51+
* - Añadir: recibe nombre y descripción.
52+
* - Eliminar: por nombre de la tarea.
53+
* Implementa diferentes mensajes de log que muestren información según la
54+
* tarea ejecutada (a tu elección).
55+
* Utiliza el log para visualizar el tiempo de ejecución de cada tarea.
56+
*/
57+
class ProgramTask {
58+
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
59+
private readonly Dictionary<string, string> tasks;
60+
61+
public ProgramTask() {
62+
tasks = [];
63+
logger.Debug("Se inició instancia de la clase ProgramTask.");
64+
}
65+
66+
public void Add(string name, string description) {
67+
tasks[name] = description;
68+
logger.Info("Se agregó una tarea.");
69+
}
70+
71+
public void Delete(string name) {
72+
if (tasks.Remove(name)) {
73+
logger.Info($"Tarea '{name}' eliminada.");
74+
} else {
75+
Console.WriteLine();
76+
logger.Warn($"No se encontró la tarea '{name}'.");
77+
}
78+
}
79+
80+
public void ShowList() {
81+
logger.Info("Lista de tareas");
82+
foreach (var task in tasks) {
83+
Console.WriteLine($"{task.Key} -- {task.Value}");
84+
}
85+
}
86+
}

Roadmap/25 - LOGS/go/hozlucas28.go

Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
package main
2+
3+
import (
4+
"bufio"
5+
"errors"
6+
"fmt"
7+
"log"
8+
"os"
9+
"strings"
10+
"time"
11+
)
12+
13+
/* -------------------------------------------------------------------------- */
14+
/* CLASSES */
15+
/* -------------------------------------------------------------------------- */
16+
17+
/* ------------------------------ Task Manager ------------------------------ */
18+
19+
type Task struct {
20+
description string
21+
title string
22+
}
23+
24+
type TaskManager struct {
25+
tasks []Task
26+
shouldPrintLogs bool
27+
}
28+
29+
func (taskManager *TaskManager) addTask(newTask Task) error {
30+
var startTime time.Time = time.Now()
31+
32+
if taskManager.shouldPrintLogs {
33+
fmt.Println()
34+
log.Println("addTask (method) start execution...")
35+
}
36+
37+
taskManager.tasks = append(taskManager.tasks, newTask)
38+
39+
if taskManager.shouldPrintLogs {
40+
log.Println("addTask (method) ends execution!")
41+
log.Printf("addTask: %v\n", time.Since(startTime))
42+
}
43+
44+
return nil
45+
}
46+
47+
func (taskManager *TaskManager) deleteTaskByTitle(title string) error {
48+
var startTime time.Time = time.Now()
49+
50+
if taskManager.shouldPrintLogs {
51+
fmt.Println()
52+
log.Println("deleteTaskByTitle (method) start execution...")
53+
}
54+
55+
var uppercasedTitle string = strings.ToUpper(title)
56+
57+
var sanitizedTasks []Task
58+
59+
for _, task := range taskManager.tasks {
60+
var uppercasedTaskTitle string = strings.ToUpper(task.title)
61+
62+
if uppercasedTaskTitle != uppercasedTitle {
63+
sanitizedTasks = append(sanitizedTasks, task)
64+
65+
}
66+
}
67+
68+
if len(taskManager.tasks) == len(sanitizedTasks) {
69+
return errors.New("The task title was not found!")
70+
}
71+
72+
taskManager.tasks = sanitizedTasks
73+
74+
if taskManager.shouldPrintLogs {
75+
log.Printf("deleteTaskByTitle (method) ends execution!\n")
76+
log.Printf("deleteTaskByTitle: %v\n", time.Since(startTime))
77+
}
78+
79+
return nil
80+
}
81+
82+
func (taskManager *TaskManager) printTasks() {
83+
var startTime time.Time = time.Now()
84+
85+
if taskManager.shouldPrintLogs {
86+
log.Printf("printTasks (method) start execution...\n\n")
87+
}
88+
89+
for _, task := range taskManager.tasks {
90+
fmt.Printf("%+v\n", task)
91+
}
92+
93+
if taskManager.shouldPrintLogs {
94+
fmt.Println()
95+
log.Printf("printTasks (method) ends execution!\n")
96+
log.Printf("printTasks: %v", time.Since(startTime))
97+
}
98+
}
99+
100+
/* -------------------------------------------------------------------------- */
101+
/* MAIN */
102+
/* -------------------------------------------------------------------------- */
103+
104+
func main() {
105+
/*
106+
Logging...
107+
*/
108+
109+
fmt.Println("Logging...")
110+
111+
fmt.Printf("\nlog.Print(<MESSAGE>)...\n\n")
112+
113+
log.Print("logger message!")
114+
115+
fmt.Printf("\nlog.Printf(<MESSAGE>)...\n\n")
116+
117+
log.Printf("Formatted logger message!")
118+
119+
fmt.Printf("\nlog.Println(<MESSAGE>)...\n\n")
120+
121+
log.Println("Logger message with line break at the end!")
122+
123+
fmt.Println("\n# ---------------------------------------------------------------------------------- #")
124+
125+
/*
126+
Additional challenge...
127+
*/
128+
129+
fmt.Printf("\nAdditional challenge...\n")
130+
131+
var taskManager TaskManager = TaskManager{shouldPrintLogs: true}
132+
133+
var exit bool = false
134+
var reader *bufio.Reader = bufio.NewReader(os.Stdin)
135+
136+
for !exit {
137+
fmt.Print("\nWrite an operation ('Add task', 'Delete task by title', 'Print tasks', or 'Exit'): ")
138+
operation, readerErr := reader.ReadString('\n')
139+
if readerErr != nil {
140+
continue
141+
}
142+
143+
operation = strings.TrimSpace(operation)
144+
operation = strings.ToUpper(operation)
145+
146+
operationActions:
147+
switch operation {
148+
case "ADD TASK":
149+
fmt.Print("\nTask title: ")
150+
taskTitle, readerErr := reader.ReadString('\n')
151+
if readerErr != nil {
152+
break operationActions
153+
}
154+
155+
fmt.Print("Task description: ")
156+
taskDescription, readerErr := reader.ReadString('\n')
157+
if readerErr != nil {
158+
break operationActions
159+
}
160+
161+
taskManager.addTask(Task{
162+
description: strings.TrimSpace(taskDescription),
163+
title: strings.TrimSpace(taskTitle),
164+
})
165+
166+
case "DELETE TASK BY TITLE":
167+
fmt.Print("\nTask title: ")
168+
taskTitle, readerErr := reader.ReadString('\n')
169+
if readerErr != nil {
170+
break operationActions
171+
}
172+
173+
taskManager.deleteTaskByTitle(taskTitle)
174+
175+
case "PRINT TASKS":
176+
fmt.Println()
177+
taskManager.printTasks()
178+
179+
case "EXIT":
180+
exit = true
181+
fmt.Print("\nApplication closed!")
182+
183+
default:
184+
fmt.Print("\nInvalid operation! Try again...\n")
185+
}
186+
}
187+
}

0 commit comments

Comments
 (0)