Skip to content

Commit 482636e

Browse files
authored
Merge pull request mouredev#7371 from miguelex/main
mouredev#46 - php
2 parents e86eaef + f454261 commit 482636e

File tree

5 files changed

+450
-0
lines changed

5 files changed

+450
-0
lines changed
+197
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
<?php
2+
3+
class SocialNetwork {
4+
private $users = [];
5+
private $posts = [];
6+
private $follows = [];
7+
private $likes = [];
8+
9+
public function registerUser($userId, $username) {
10+
if (isset($this->users[$userId])) {
11+
echo "El usuario con ID $userId ya existe.\n";
12+
} else {
13+
$this->users[$userId] = $username;
14+
echo "Usuario $username registrado con éxito.\n";
15+
}
16+
}
17+
18+
public function followUser($followerId, $followeeId) {
19+
if (!isset($this->users[$followerId]) || !isset($this->users[$followeeId])) {
20+
echo "Uno de los usuarios no existe.\n";
21+
return;
22+
}
23+
$this->follows[$followerId][$followeeId] = true;
24+
echo "Usuario $followerId ahora sigue a $followeeId.\n";
25+
}
26+
27+
public function unfollowUser($followerId, $followeeId) {
28+
if (isset($this->follows[$followerId][$followeeId])) {
29+
unset($this->follows[$followerId][$followeeId]);
30+
echo "Usuario $followerId ha dejado de seguir a $followeeId.\n";
31+
} else {
32+
echo "El usuario $followerId no sigue a $followeeId.\n";
33+
}
34+
}
35+
36+
public function createPost($userId, $postId, $text) {
37+
if (!isset($this->users[$userId])) {
38+
echo "El usuario no existe.\n";
39+
return;
40+
}
41+
if (strlen($text) > 200) {
42+
echo "El texto del post excede los 200 caracteres.\n";
43+
return;
44+
}
45+
$this->posts[$postId] = [
46+
'userId' => $userId,
47+
'text' => $text,
48+
'createdAt' => date('Y-m-d H:i:s'),
49+
'likes' => 0
50+
];
51+
echo "Post creado con éxito.\n";
52+
}
53+
54+
public function deletePost($postId) {
55+
if (isset($this->posts[$postId])) {
56+
unset($this->posts[$postId]);
57+
echo "Post eliminado con éxito.\n";
58+
} else {
59+
echo "El post no existe.\n";
60+
}
61+
}
62+
63+
public function likePost($userId, $postId) {
64+
if (!isset($this->users[$userId])) {
65+
echo "El usuario no existe.\n";
66+
return;
67+
}
68+
if (!isset($this->posts[$postId])) {
69+
echo "El post no existe.\n";
70+
return;
71+
}
72+
$this->likes[$userId][$postId] = true;
73+
$this->posts[$postId]['likes']++;
74+
echo "Like añadido al post $postId.\n";
75+
}
76+
77+
public function unlikePost($userId, $postId) {
78+
if (isset($this->likes[$userId][$postId])) {
79+
unset($this->likes[$userId][$postId]);
80+
$this->posts[$postId]['likes']--;
81+
echo "Like eliminado del post $postId.\n";
82+
} else {
83+
echo "El usuario no ha hecho like en el post $postId.\n";
84+
}
85+
}
86+
87+
public function viewUserFeed($userId) {
88+
if (!isset($this->users[$userId])) {
89+
echo "El usuario no existe.\n";
90+
return;
91+
}
92+
$userPosts = array_filter($this->posts, function($post) use ($userId) {
93+
return $post['userId'] == $userId;
94+
});
95+
usort($userPosts, function($a, $b) {
96+
return strtotime($b['createdAt']) - strtotime($a['createdAt']);
97+
});
98+
$userPosts = array_slice($userPosts, 0, 10);
99+
foreach ($userPosts as $post) {
100+
echo "ID: {$post['userId']}, Usuario: {$this->users[$post['userId']]}, Texto: {$post['text']}, Fecha: {$post['createdAt']}, Likes: {$post['likes']}\n";
101+
}
102+
}
103+
104+
public function viewFollowedFeed($userId) {
105+
if (!isset($this->users[$userId])) {
106+
echo "El usuario no existe.\n";
107+
return;
108+
}
109+
$followedPosts = [];
110+
if (isset($this->follows[$userId])) {
111+
foreach ($this->follows[$userId] as $followeeId => $value) {
112+
foreach ($this->posts as $postId => $post) {
113+
if ($post['userId'] == $followeeId) {
114+
$followedPosts[] = $post;
115+
}
116+
}
117+
}
118+
}
119+
usort($followedPosts, function($a, $b) {
120+
return strtotime($b['createdAt']) - strtotime($a['createdAt']);
121+
});
122+
$followedPosts = array_slice($followedPosts, 0, 10);
123+
foreach ($followedPosts as $post) {
124+
echo "ID: {$post['userId']}, Usuario: {$this->users[$post['userId']]}, Texto: {$post['text']}, Fecha: {$post['createdAt']}, Likes: {$post['likes']}\n";
125+
}
126+
}
127+
}
128+
129+
// Menú interactivo
130+
$network = new SocialNetwork();
131+
132+
while (true) {
133+
echo "Seleccione una opción:\n";
134+
echo "1. Registrar usuario\n";
135+
echo "2. Seguir a un usuario\n";
136+
echo "3. Dejar de seguir a un usuario\n";
137+
echo "4. Crear post\n";
138+
echo "5. Eliminar post\n";
139+
echo "6. Hacer like en un post\n";
140+
echo "7. Eliminar like de un post\n";
141+
echo "8. Ver feed del usuario\n";
142+
echo "9. Ver feed de usuarios seguidos\n";
143+
echo "0. Salir\n";
144+
$option = readline("Opción: ");
145+
146+
switch ($option) {
147+
case 1:
148+
$userId = readline("ID de usuario: ");
149+
$username = readline("Nombre de usuario: ");
150+
$network->registerUser($userId, $username);
151+
break;
152+
case 2:
153+
$followerId = readline("ID del seguidor: ");
154+
$followeeId = readline("ID del seguido: ");
155+
$network->followUser($followerId, $followeeId);
156+
break;
157+
case 3:
158+
$followerId = readline("ID del seguidor: ");
159+
$followeeId = readline("ID del seguido: ");
160+
$network->unfollowUser($followerId, $followeeId);
161+
break;
162+
case 4:
163+
$userId = readline("ID de usuario: ");
164+
$postId = readline("ID del post: ");
165+
$text = readline("Texto del post: ");
166+
$network->createPost($userId, $postId, $text);
167+
break;
168+
case 5:
169+
$postId = readline("ID del post: ");
170+
$network->deletePost($postId);
171+
break;
172+
case 6:
173+
$userId = readline("ID de usuario: ");
174+
$postId = readline("ID del post: ");
175+
$network->likePost($userId, $postId);
176+
break;
177+
case 7:
178+
$userId = readline("ID de usuario: ");
179+
$postId = readline("ID del post: ");
180+
$network->unlikePost($userId, $postId);
181+
break;
182+
case 8:
183+
$userId = readline("ID de usuario: ");
184+
$network->viewUserFeed($userId);
185+
break;
186+
case 9:
187+
$userId = readline("ID de usuario: ");
188+
$network->viewFollowedFeed($userId);
189+
break;
190+
case 0:
191+
exit("¡Hasta luego!\n");
192+
default:
193+
echo "Opción no válida. Intente de nuevo.\n";
194+
break;
195+
}
196+
}
197+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import java.util.Scanner;
2+
3+
public class miguelex {
4+
5+
private static final int GRID_WIDTH = 4;
6+
private static final int GRID_HEIGHT = 3;
7+
private static final int DAYS = 24;
8+
private static boolean[] discovered = new boolean[DAYS];
9+
10+
public static void main(String[] args) {
11+
Scanner scanner = new Scanner(System.in);
12+
13+
while (true) {
14+
drawCalendar();
15+
16+
System.out.print("\nSeleccione un día (1-" + DAYS + ") para descubrir o escriba 0 para salir: ");
17+
String input = scanner.nextLine();
18+
19+
if (input.equals("0")) {
20+
System.out.println("¡Gracias por participar en el aDEViento!");
21+
break;
22+
}
23+
24+
try {
25+
int day = Integer.parseInt(input);
26+
if (day < 1 || day > DAYS) {
27+
System.out.println("Por favor, elija un número válido entre 1 y " + DAYS + ".");
28+
} else if (discovered[day - 1]) {
29+
System.out.println("El día " + day + " ya ha sido descubierto.");
30+
} else {
31+
discovered[day - 1] = true;
32+
System.out.println("¡Has descubierto el día " + day + "!");
33+
}
34+
} catch (NumberFormatException e) {
35+
System.out.println("Entrada inválida. Por favor, ingrese un número válido.");
36+
}
37+
}
38+
39+
scanner.close();
40+
}
41+
42+
private static void drawCalendar() {
43+
for (int row = 0; row < Math.ceil(DAYS / 6.0); row++) {
44+
for (int line = 0; line < GRID_HEIGHT; line++) {
45+
StringBuilder rowOutput = new StringBuilder();
46+
47+
for (int col = 0; col < 6; col++) {
48+
int day = row * 6 + col + 1;
49+
if (day > DAYS) break;
50+
51+
switch (line) {
52+
case 0, 2 -> rowOutput.append("**** ");
53+
case 1 -> {
54+
rowOutput.append("*");
55+
if (discovered[day - 1]) {
56+
rowOutput.append("**");
57+
} else {
58+
String dayStr = String.format("%02d", day);
59+
rowOutput.append(dayStr);
60+
}
61+
rowOutput.append("* ");
62+
}
63+
}
64+
}
65+
System.out.println(rowOutput);
66+
}
67+
}
68+
}
69+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
const GRID_WIDTH = 4;
2+
const GRID_HEIGHT = 3;
3+
const DAYS = 24;
4+
5+
const discovered = Array(DAYS).fill(false);
6+
7+
function drawCalendar(discovered) {
8+
for (let row = 0; row < Math.ceil(DAYS / 6); row++) {
9+
for (let line = 0; line < GRID_HEIGHT; line++) {
10+
let rowOutput = "";
11+
for (let col = 0; col < 6; col++) {
12+
const day = row * 6 + col + 1;
13+
if (day > DAYS) break;
14+
15+
switch (line) {
16+
case 0:
17+
case 2:
18+
rowOutput += "*".repeat(GRID_WIDTH) + " ";
19+
break;
20+
case 1:
21+
rowOutput += "*";
22+
rowOutput += discovered[day - 1]
23+
? "*".repeat(GRID_WIDTH - 2)
24+
: day.toString().padStart(2, "0").padEnd(GRID_WIDTH - 2, " ");
25+
rowOutput += "* ";
26+
break;
27+
}
28+
}
29+
console.log(rowOutput);
30+
}
31+
}
32+
}
33+
34+
const readline = require("readline");
35+
const rl = readline.createInterface({
36+
input: process.stdin,
37+
output: process.stdout
38+
});
39+
40+
function promptUser() {
41+
drawCalendar(discovered);
42+
43+
rl.question(`\nSeleccione un día (1-${DAYS}) para descubrir o escriba 0 para salir: `, (input) => {
44+
const day = parseInt(input, 10);
45+
46+
if (day === 0) {
47+
console.log("¡Gracias por participar en el aDEViento!");
48+
rl.close();
49+
return;
50+
}
51+
52+
if (isNaN(day) || day < 1 || day > DAYS) {
53+
console.log(`Por favor, elija un número válido entre 1 y ${DAYS}.`);
54+
} else if (discovered[day - 1]) {
55+
console.log(`El día ${day} ya ha sido descubierto.`);
56+
} else {
57+
discovered[day - 1] = true;
58+
console.log(`¡Has descubierto el día ${day}!`);
59+
}
60+
61+
promptUser();
62+
});
63+
}
64+
65+
promptUser();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import math
2+
3+
GRID_WIDTH = 4
4+
GRID_HEIGHT = 3
5+
DAYS = 24
6+
7+
discovered = [False] * DAYS
8+
9+
def draw_calendar():
10+
for row in range(math.ceil(DAYS / 6)):
11+
for line in range(GRID_HEIGHT):
12+
row_output = ""
13+
for col in range(6):
14+
day = row * 6 + col + 1
15+
if day > DAYS:
16+
break
17+
18+
if line == 0 or line == 2:
19+
row_output += "**** "
20+
elif line == 1:
21+
row_output += "*"
22+
if discovered[day - 1]:
23+
row_output += "**"
24+
else:
25+
day_str = str(day).zfill(2)
26+
row_output += day_str
27+
row_output += "* "
28+
print(row_output)
29+
30+
def main():
31+
while True:
32+
draw_calendar()
33+
try:
34+
user_input = input(f"\nSeleccione un día (1-{DAYS}) para descubrir o escriba 0 para salir: ")
35+
day = int(user_input)
36+
37+
if day == 0:
38+
print("¡Gracias por participar en el aDEViento!")
39+
break
40+
41+
if day < 1 or day > DAYS:
42+
print(f"Por favor, elija un número válido entre 1 y {DAYS}.")
43+
elif discovered[day - 1]:
44+
print(f"El día {day} ya ha sido descubierto.")
45+
else:
46+
discovered[day - 1] = True
47+
print(f"¡Has descubierto el día {day}!")
48+
except ValueError:
49+
print("Entrada inválida. Por favor, ingrese un número válido.")
50+
51+
if __name__ == "__main__":
52+
main()

0 commit comments

Comments
 (0)