|
| 1 | +# Challenge Description and Solution |
| 2 | + |
| 3 | +## English Version |
| 4 | + |
| 5 | +### Challenge Description |
| 6 | +Given an array of numbers, write a function that finds and returns the maximum value without using predefined sorting functions. |
| 7 | + |
| 8 | +### Code Explanation |
| 9 | +The `findMax` function first checks if the array is empty and throws an error in that case. It then initializes `maxVal` with the first element of the array and iterates over the rest of the elements comparing each with `maxVal`. If it finds a greater value, it updates `maxVal`. Finally, it returns the maximum value found. |
| 10 | + |
| 11 | +### Relevant Code Snippet |
| 12 | + |
| 13 | +```javascript |
| 14 | +function findMax(arr) { |
| 15 | + if (arr.length === 0) { |
| 16 | + throw new Error("Array is empty"); |
| 17 | + } |
| 18 | + let maxVal = arr[0]; |
| 19 | + for (let i = 1; i < arr.length; i++) { |
| 20 | + if (arr[i] > maxVal) { |
| 21 | + maxVal = arr[i]; |
| 22 | + } |
| 23 | + } |
| 24 | + return maxVal; |
| 25 | +} |
| 26 | +``` |
| 27 | + |
| 28 | +### Example Usage |
| 29 | + |
| 30 | +```javascript |
| 31 | +const testArray = [3, 5, 1, 8, 2, 9, 4]; |
| 32 | +console.log("Array:", testArray); |
| 33 | +console.log("Maximum value:", findMax(testArray)); |
| 34 | +``` |
| 35 | + |
| 36 | +--- |
| 37 | + |
| 38 | +## Versión en Español |
| 39 | + |
| 40 | +### Descripción del Reto |
| 41 | +Dado un arreglo de números, escribe una función que encuentre y retorne el valor máximo sin usar funciones de ordenamiento predefinidas. |
| 42 | + |
| 43 | +### Explicación del Código |
| 44 | +La función `findMax` primero verifica si el arreglo está vacío y lanza un error en ese caso. Luego inicializa `maxVal` con el primer elemento del arreglo y recorre el resto de los elementos comparando cada uno con `maxVal`. Si encuentra un valor mayor, actualiza `maxVal`. Finalmente, retorna el valor máximo encontrado. |
| 45 | + |
| 46 | +### Fragmento de Código Relevante |
| 47 | + |
| 48 | +```javascript |
| 49 | +function findMax(arr) { |
| 50 | + if (arr.length === 0) { |
| 51 | + throw new Error("Array is empty"); |
| 52 | + } |
| 53 | + let maxVal = arr[0]; |
| 54 | + for (let i = 1; i < arr.length; i++) { |
| 55 | + if (arr[i] > maxVal) { |
| 56 | + maxVal = arr[i]; |
| 57 | + } |
| 58 | + } |
| 59 | + return maxVal; |
| 60 | +} |
| 61 | +``` |
| 62 | + |
| 63 | +### Ejemplo de Uso |
| 64 | + |
| 65 | +```javascript |
| 66 | +const testArray = [3, 5, 1, 8, 2, 9, 4]; |
| 67 | +console.log("Arreglo:", testArray); |
| 68 | +console.log("Valor máximo:", findMax(testArray)); |
0 commit comments