Skip to content

Commit 2238be5

Browse files
committed
Merge js branch into main in a single commit
2 parents 3c15fbf + b1696af commit 2238be5

File tree

20 files changed

+923
-0
lines changed

20 files changed

+923
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Challenge Description and Solution
2+
3+
## English Version
4+
5+
### Challenge Description
6+
Given a string, create a function that reverses it without using built-in reverse methods. This will help you practice loops and index handling.
7+
8+
### Code Explanation
9+
The `reverseString` function iterates over the input string from the end to the beginning, concatenating characters to build the reversed string.
10+
11+
### Relevant Code Snippet
12+
13+
```javascript
14+
function reverseString(s) {
15+
let reversedStr = "";
16+
for (let i = s.length - 1; i >= 0; i--) {
17+
reversedStr += s[i];
18+
}
19+
return reversedStr;
20+
}
21+
```
22+
23+
### Example Usage
24+
25+
```javascript
26+
const testString = "hello";
27+
console.log("Original string:", testString);
28+
console.log("Reversed string:", reverseString(testString));
29+
```
30+
31+
---
32+
33+
## Versión en Español
34+
35+
### Descripción del Reto
36+
Dada una cadena, crea una función que la invierta sin usar métodos integrados de inversión. Esto te ayudará a practicar bucles y manejo de índices.
37+
38+
### Explicación del Código
39+
La función `reverseString` itera sobre la cadena de entrada desde el final hasta el principio, concatenando caracteres para construir la cadena invertida.
40+
41+
### Fragmento de Código Relevante
42+
43+
```javascript
44+
function reverseString(s) {
45+
let reversedStr = "";
46+
for (let i = s.length - 1; i >= 0; i--) {
47+
reversedStr += s[i];
48+
}
49+
return reversedStr;
50+
}
51+
```
52+
53+
### Ejemplo de Uso
54+
55+
```javascript
56+
const testString = "hello";
57+
console.log("Original string:", testString);
58+
console.log("Reversed string:", reverseString(testString));
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Challenge: Given a string, create a function that reverses it without using built-in reverse methods.
2+
// This will help you practice loops and index handling.
3+
4+
function reverseString(s) {
5+
let reversedStr = "";
6+
for (let i = s.length - 1; i >= 0; i--) {
7+
reversedStr += s[i];
8+
}
9+
return reversedStr;
10+
}
11+
12+
// Example usage
13+
const testString = "hello";
14+
console.log("Original string:", testString);
15+
console.log("Reversed string:", reverseString(testString));
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Challenge Description and Solution
2+
3+
## English Version
4+
5+
### Challenge Description
6+
Write a function that determines if a number is even or odd. Test with different types of inputs (positive numbers, negative numbers, and zero) to ensure robustness.
7+
8+
### Code Explanation
9+
The `isEven` function uses the modulo operator `%` to determine if a number is even. If the remainder of the division of the number by 2 is zero, the number is even; otherwise, it is odd.
10+
11+
### Relevant Code Snippet
12+
13+
```javascript
14+
function isEven(n) {
15+
return n % 2 === 0;
16+
}
17+
```
18+
19+
### Example Usage
20+
21+
```javascript
22+
const testValues = [0, 1, -1, 2, -2, 15, -15];
23+
testValues.forEach(val => {
24+
const result = isEven(val) ? "even" : "odd";
25+
console.log(`${val} is ${result}`);
26+
});
27+
```
28+
29+
---
30+
31+
## Versión en Español
32+
33+
### Descripción del Reto
34+
Escribe una función que determine si un número es par o impar. Prueba con diferentes tipos de entradas (números positivos, negativos y cero) para asegurar la robustez.
35+
36+
### Explicación del Código
37+
La función `isEven` utiliza el operador módulo `%` para determinar si un número es par. Si el residuo de la división entre el número y 2 es cero, el número es par; de lo contrario, es impar.
38+
39+
### Fragmento de Código Relevante
40+
41+
```javascript
42+
function isEven(n) {
43+
return n % 2 === 0;
44+
}
45+
```
46+
47+
### Ejemplo de Uso
48+
49+
```javascript
50+
const testValues = [0, 1, -1, 2, -2, 15, -15];
51+
testValues.forEach(val => {
52+
const result = isEven(val) ? "even" : "odd";
53+
console.log(`${val} is ${result}`);
54+
});
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// Challenge: Write a function that determines if a number is even or odd. Test with different types of inputs (positive numbers, negative numbers, and zero) to ensure robustness.
2+
3+
function isEven(n) {
4+
return n % 2 === 0;
5+
}
6+
7+
// Example usage
8+
const testValues = [0, 1, -1, 2, -2, 15, -15];
9+
testValues.forEach(val => {
10+
const result = isEven(val) ? "even" : "odd";
11+
console.log(`${val} is ${result}`);
12+
});
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# Challenge Description and Solution
2+
3+
## English Version
4+
5+
### Challenge Description
6+
Implement a function that determines if a number is prime. Pay attention to edge cases such as negative values and the number 1.
7+
8+
### Code Explanation
9+
The `isPrime` function checks if a number `n` is prime. It first excludes numbers less than or equal to 1, which are not prime. Then, it considers 2 and 3 as prime numbers. Next, it eliminates multiples of 2 and 3. Finally, it uses a loop that checks divisors starting from 5, skipping multiples of 6, to optimize the search. If a divisor is found, it returns `false`; otherwise, it returns `true`.
10+
11+
### Relevant Code Snippet
12+
13+
```javascript
14+
function isPrime(n) {
15+
if (n <= 1) {
16+
return false;
17+
}
18+
if (n <= 3) {
19+
return true;
20+
}
21+
if (n % 2 === 0 || n % 3 === 0) {
22+
return false;
23+
}
24+
let i = 5;
25+
while (i * i <= n) {
26+
if (n % i === 0 || n % (i + 2) === 0) {
27+
return false;
28+
}
29+
i += 6;
30+
}
31+
return true;
32+
}
33+
```
34+
35+
### Example Usage
36+
37+
```javascript
38+
const testNumbers = [-1, 0, 1, 2, 3, 4, 5, 29, 35];
39+
testNumbers.forEach(num => {
40+
console.log(`${num} is prime: ${isPrime(num)}`);
41+
});
42+
```
43+
44+
---
45+
46+
## Versión en Español
47+
48+
### Descripción del Reto
49+
Implementa una función que determine si un número es primo. Presta atención a casos especiales como valores negativos y el número 1.
50+
51+
### Explicación del Código
52+
La función `isPrime` verifica si un número `n` es primo. Primero descarta números menores o iguales a 1, que no son primos. Luego, considera los números 2 y 3 como primos. Después, elimina múltiplos de 2 y 3. Finalmente, utiliza un bucle que verifica divisores desde 5 en adelante, saltando múltiplos de 6, para optimizar la búsqueda. Si encuentra un divisor, retorna `false`; si no, retorna `true`.
53+
54+
### Fragmento de Código Relevante
55+
56+
```javascript
57+
function isPrime(n) {
58+
if (n <= 1) {
59+
return false;
60+
}
61+
if (n <= 3) {
62+
return true;
63+
}
64+
if (n % 2 === 0 || n % 3 === 0) {
65+
return false;
66+
}
67+
let i = 5;
68+
while (i * i <= n) {
69+
if (n % i === 0 || n % (i + 2) === 0) {
70+
return false;
71+
}
72+
i += 6;
73+
}
74+
return true;
75+
}
76+
```
77+
78+
### Ejemplo de Uso
79+
80+
```javascript
81+
const testNumbers = [-1, 0, 1, 2, 3, 4, 5, 29, 35];
82+
testNumbers.forEach(num => {
83+
console.log(`${num} es primo: ${isPrime(num)}`);
84+
});
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Challenge: Implement a function that determines if a number is prime.
2+
// Pay attention to edge cases such as negative values and the number 1.
3+
4+
function isPrime(n) {
5+
if (n <= 1) {
6+
return false;
7+
}
8+
if (n <= 3) {
9+
return true;
10+
}
11+
if (n % 2 === 0 || n % 3 === 0) {
12+
return false;
13+
}
14+
let i = 5;
15+
while (i * i <= n) {
16+
if (n % i === 0 || n % (i + 2) === 0) {
17+
return false;
18+
}
19+
i += 6;
20+
}
21+
return true;
22+
}
23+
24+
// Example usage
25+
const testNumbers = [-1, 0, 1, 2, 3, 4, 5, 29, 35];
26+
testNumbers.forEach(num => {
27+
console.log(`${num} is prime: ${isPrime(num)}`);
28+
});
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# Challenge Description and Solution
2+
3+
## English Version
4+
5+
### Challenge Description
6+
Create a generator that returns the Fibonacci sequence up to n terms. You can explore iterative and recursive approaches to solve the problem.
7+
8+
### Code Explanation
9+
The code presents two generator functions for the Fibonacci sequence:
10+
11+
- `fibonacciIterative(n)`: Uses a `for` loop to generate the first n terms of the Fibonacci sequence iteratively. It initializes two variables `a` and `b` with 0 and 1 respectively, and in each iteration yields the current value of `a` and updates `a` and `b`.
12+
13+
- `fibonacciRecursive(n, a=0, b=1)`: Generates the Fibonacci sequence recursively. If `n` is 0, it ends the recursion. Otherwise, it yields the current value `a` and recursively calls itself with `n-1`, `b`, and `a+b`.
14+
15+
### Relevant Code Snippet
16+
17+
```javascript
18+
function* fibonacciIterative(n) {
19+
let a = 0, b = 1;
20+
for (let i = 0; i < n; i++) {
21+
yield a;
22+
[a, b] = [b, a + b];
23+
}
24+
}
25+
26+
function* fibonacciRecursive(n, a = 0, b = 1) {
27+
if (n === 0) return;
28+
yield a;
29+
yield* fibonacciRecursive(n - 1, b, a + b);
30+
}
31+
```
32+
33+
### Example Usage
34+
35+
```javascript
36+
const n = 10;
37+
console.log("Iterative Fibonacci sequence:");
38+
for (const num of fibonacciIterative(n)) {
39+
process.stdout.write(num + " ");
40+
}
41+
console.log("\nRecursive Fibonacci sequence:");
42+
for (const num of fibonacciRecursive(n)) {
43+
process.stdout.write(num + " ");
44+
}
45+
console.log();
46+
```
47+
48+
---
49+
50+
## Versión en Español
51+
52+
### Descripción del Reto
53+
Crea un generador que devuelva la secuencia de Fibonacci hasta n términos. Puedes explorar enfoques iterativos y recursivos para resolver el problema.
54+
55+
### Explicación del Código
56+
El código presenta dos funciones generadoras para la secuencia de Fibonacci:
57+
58+
- `fibonacciIterative(n)`: Utiliza un bucle `for` para generar los primeros n términos de la secuencia de Fibonacci de manera iterativa. Inicializa dos variables `a` y `b` con 0 y 1 respectivamente, y en cada iteración produce el valor actual de `a` y actualiza `a` y `b`.
59+
60+
- `fibonacciRecursive(n, a=0, b=1)`: Genera la secuencia de Fibonacci de forma recursiva. Si `n` es 0, termina la recursión. De lo contrario, produce el valor actual `a` y llama recursivamente a sí misma con `n-1`, `b` y `a+b`.
61+
62+
### Fragmento de Código Relevante
63+
64+
```javascript
65+
function* fibonacciIterative(n) {
66+
let a = 0, b = 1;
67+
for (let i = 0; i < n; i++) {
68+
yield a;
69+
[a, b] = [b, a + b];
70+
}
71+
}
72+
73+
function* fibonacciRecursive(n, a = 0, b = 1) {
74+
if (n === 0) return;
75+
yield a;
76+
yield* fibonacciRecursive(n - 1, b, a + b);
77+
}
78+
```
79+
80+
### Ejemplo de Uso
81+
82+
```javascript
83+
const n = 10;
84+
console.log("Secuencia de Fibonacci iterativa:");
85+
for (const num of fibonacciIterative(n)) {
86+
process.stdout.write(num + " ");
87+
}
88+
console.log("\nSecuencia de Fibonacci recursiva:");
89+
for (const num of fibonacciRecursive(n)) {
90+
process.stdout.write(num + " ");
91+
}
92+
console.log();
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Challenge: Create a generator that returns the Fibonacci sequence up to n terms.
2+
// You can explore iterative and recursive approaches to solve the problem.
3+
4+
// Iterative generator function
5+
function* fibonacciIterative(n) {
6+
let a = 0, b = 1;
7+
for (let i = 0; i < n; i++) {
8+
yield a;
9+
[a, b] = [b, a + b];
10+
}
11+
}
12+
13+
// Recursive generator function
14+
function* fibonacciRecursive(n, a = 0, b = 1) {
15+
if (n === 0) return;
16+
yield a;
17+
yield* fibonacciRecursive(n - 1, b, a + b);
18+
}
19+
20+
// Example usage
21+
const n = 10;
22+
console.log("Iterative Fibonacci sequence:");
23+
for (const num of fibonacciIterative(n)) {
24+
process.stdout.write(num + " ");
25+
}
26+
console.log("\nRecursive Fibonacci sequence:");
27+
for (const num of fibonacciRecursive(n)) {
28+
process.stdout.write(num + " ");
29+
}
30+
console.log();

0 commit comments

Comments
 (0)