Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Arrays#309

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
joaquinelio merged 28 commits intojavascript-tutorial:masterfromjoaquinelio:arr
Jul 22, 2020
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
28 commits
Select commitHold shift + click to select a range
042d43f
Arrays
joaquinelioJul 19, 2020
5314f8f
Update 1-js/05-data-types/04-array/10-maximal-subarray/solution.md
joaquinelioJul 21, 2020
b3a0cc0
Update 1-js/05-data-types/04-array/10-maximal-subarray/solution.md
joaquinelioJul 21, 2020
af2e2a0
Update 1-js/05-data-types/04-array/10-maximal-subarray/solution.md
joaquinelioJul 21, 2020
a373976
Update 1-js/05-data-types/04-array/5-array-input-sum/task.md
joaquinelioJul 21, 2020
baa16d7
Update 1-js/05-data-types/04-array/article.md
joaquinelioJul 21, 2020
71793c9
Update 1-js/05-data-types/04-array/article.md
joaquinelioJul 21, 2020
1a517fd
Update 1-js/05-data-types/04-array/article.md
joaquinelioJul 21, 2020
a73a204
Update 1-js/05-data-types/04-array/article.md
joaquinelioJul 21, 2020
e88e22a
Update 1-js/05-data-types/04-array/article.md
joaquinelioJul 21, 2020
fef7302
Update 1-js/05-data-types/04-array/5-array-input-sum/task.md
joaquinelioJul 21, 2020
93aedf5
Update 1-js/05-data-types/04-array/2-create-array/task.md
joaquinelioJul 21, 2020
cc3750c
Update 1-js/05-data-types/04-array/3-call-array-this/solution.md
joaquinelioJul 21, 2020
c2f4f67
Update 1-js/05-data-types/04-array/3-call-array-this/task.md
joaquinelioJul 21, 2020
05a0618
Update 1-js/05-data-types/04-array/article.md
joaquinelioJul 21, 2020
383249d
Update 1-js/05-data-types/04-array/5-array-input-sum/solution.md
joaquinelioJul 21, 2020
f122d1e
Update 1-js/05-data-types/04-array/article.md
joaquinelioJul 21, 2020
8fdb93a
Update 1-js/05-data-types/04-array/article.md
joaquinelioJul 21, 2020
726df56
Update 1-js/05-data-types/04-array/article.md
joaquinelioJul 21, 2020
b3e4585
Update 1-js/05-data-types/04-array/article.md
joaquinelioJul 21, 2020
2f951b1
Update 1-js/05-data-types/04-array/article.md
joaquinelioJul 21, 2020
785ff52
Update 1-js/05-data-types/04-array/article.md
joaquinelioJul 21, 2020
fe7c1bf
Update 1-js/05-data-types/04-array/article.md
joaquinelioJul 21, 2020
214685f
Update 1-js/05-data-types/04-array/article.md
joaquinelioJul 21, 2020
db4e7fb
Update 1-js/05-data-types/04-array/article.md
joaquinelioJul 21, 2020
778666a
Update article.md
joaquinelioJul 21, 2020
bcb2dc4
Update 1-js/05-data-types/04-array/article.md
joaquinelioJul 22, 2020
6a6b3f8
Update 1-js/05-data-types/04-array/10-maximal-subarray/solution.md
joaquinelioJul 22, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions1-js/05-data-types/04-array/1-item-value/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
The result is `4`:
El resultado es `4`:


```js run
Expand All@@ -13,5 +13,5 @@ alert( fruits.length ); // 4
*/!*
```

That's becausearraysare objects. So both `shoppingCart`and `fruits`are the references to the same array.
Esto es porque losarraysson objetos. Entonces ambos, `shoppingCart`y `fruits`son referencias al mismo array.

10 changes: 5 additions & 5 deletions1-js/05-data-types/04-array/1-item-value/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,18 +2,18 @@ importance: 3

---

#Is arraycopied?
#¿El arrayes copiado?

What is this code going to show?
¿Qué va a mostrar este código?

```js
let fruits = ["Apples", "Pear", "Orange"];

//push a new value into the "copy"
//introduce un valor nuevo dentro de una copia
let shoppingCart = fruits;
shoppingCart.push("Banana");

//what's infruits?
alert( fruits.length ); // ?
//¿Qué hay en "fruits"?
alert( fruits.length ); //¿?
```

44 changes: 22 additions & 22 deletions1-js/05-data-types/04-array/10-maximal-subarray/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,43 @@
#Slow solution
#Solución lenta

We can calculate all possible subsums.
Podemos calcular todas las subsumas.

The simplest way is to take every element and calculate sums of allsubarraysstarting from it.
La forma más simple es tomar cada elemento y calcular las sumas de todos lossubarraysque comienzan con él.

For instance, for `[-1, 2, 3, -9, 11]`:
Por ejemplo, para `[-1, 2, 3, -9, 11]`:

```js no-beautify
//Starting from -1:
//Comenzando desde -1:
-1
-1 + 2
-1 + 2 + 3
-1 + 2 + 3 + (-9)
-1 + 2 + 3 + (-9) + 11

//Starting from 2:
//Comenzando desde 2:
2
2 + 3
2 + 3 + (-9)
2 + 3 + (-9) + 11

//Starting from 3:
//Comenzando desde 3:
3
3 + (-9)
3 + (-9) + 11

//Starting from -9
//Comenzando desde -9
-9
-9 + 11

//Starting from 11
//Comenzando desde 11
11
```

The code is actually a nested loop: the external loop over array elements, and the internal counts subsums starting with the current element.
El código es un bucle anidado. El bucle externo itera sobre los elementos del array, y el interno cuenta subsumas comenzando con cada uno de ellos.

```js run
function getMaxSubSum(arr) {
let maxSum = 0; //if we takenoelements, zero will be returned
let maxSum = 0; //sinoobtenemos elementos, devolverá cero

for (let i = 0; i < arr.length; i++) {
let sumFixedStart = 0;
Expand All@@ -57,25 +57,25 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6
alert( getMaxSubSum([100, -9, 2, -3, 5]) ); // 100
```

The solution has a time complexety of[O(n<sup>2</sup>)](https://en.wikipedia.org/wiki/Big_O_notation). In other words, if we increase thearraysize 2 times, the algorithm will work 4 times longer.
La solución tiene una complejidad 2 en notación Landau[O(n<sup>2</sup>)](https://es.wikipedia.org/wiki/Notaci%C3%B3n_de_Landau) (coste respecto al tiempo). Es decir, si multiplicamos el tamaño delarraypor 2, el tiempo del algoritmo se multiplicará por 4.

For bigarrays (1000, 10000or more items)such algorithms can lead to a serious sluggishness.
Paraarraysmuy grandes(1000, 10000o más items)tales algoritmos llevarán a una severa lentitud.

#Fast solution
#Solución rápida

Let's walk thearrayand keep the current partial sum of elements in thevariable `s`.If `s`becomes negative at some point, then assign `s=0`.The maximum of all such`s`will be the answer.
Recorramos elarrayy registremos la suma parcial actual de los elementos en lavariable `s`.Si `s`se vuelve cero en algún punto, le asignamos `s=0`.El máximo entre todas las sumas parciales`s`será la respuesta.

If the description is too vague, please see the code, it's short enough:
Si la descripción te resulta demasiado vaga, por favor mira el código. Es bastante corto:

```js run demo
function getMaxSubSum(arr) {
let maxSum = 0;
let partialSum = 0;

for (let item of arr) { //for each itemof arr
partialSum += item; //add it to partialSum
maxSum = Math.max(maxSum, partialSum); //remember the maximum
if (partialSum < 0) partialSum = 0; //zero if negative
for (let item of arr) { //por cada itemde arr
partialSum += item; //se lo suma a partialSum
maxSum = Math.max(maxSum, partialSum); //registra el máximo
if (partialSum < 0) partialSum = 0; //cero si se vuelve negativo
}

return maxSum;
Expand All@@ -89,6 +89,6 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6
alert( getMaxSubSum([-1, -2, -3]) ); // 0
```

The algorithm requires exactly 1 array pass, so the time complexity is O(n).
El algoritmo requiere exactamente una pasada, entonces la complejidad es O(n).

You can find more detail information about the algorithm here: [Maximum subarray problem](http://en.wikipedia.org/wiki/Maximum_subarray_problem).If it's still not obvious why that works, then please trace the algorithm on the examples above, see how it works, that's better than any words.
Puedes encontrar información detallada acerca del algoritmo: [Subvector de suma máxima](https://es.wikibooks.org/wiki/Algoritmia/Divide_y_vencer%C3%A1s#Subvector_de_suma_m%C3%A1xima).Si aún no es obvio cómo funciona, traza el algoritmo en los ejemplos de arriba y observa cómo trabaja, es mejor que cualquier explicación.
18 changes: 9 additions & 9 deletions1-js/05-data-types/04-array/10-maximal-subarray/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,29 +2,29 @@ importance: 2

---

#A maximal subarray
#Subarray máximo

The input is an arrayof numbers, e.g. `arr = [1, -2, 3, 4, -9, 6]`.
La entrada es un arrayde números, por ejemplo `arr = [1, -2, 3, 4, -9, 6]`.

The task is: find the contiguoussubarrayof`arr`with the maximal sum of items.
La tarea es: encuentra elsubarraycontiguo de items de`arr`con la suma máxima.

Write the function `getMaxSubSum(arr)`that will return that sum.
Escribe la función `getMaxSubSum(arr)`que devuelva tal sumo.

For instance:
Por ejemplo:

```js
getMaxSubSum([-1, *!*2, 3*/!*, -9]) == 5 (the sum of highlighteditems)
getMaxSubSum([-1, *!*2, 3*/!*, -9]) == 5 (la suma deitems resaltados)
getMaxSubSum([*!*2, -1, 2, 3*/!*, -9]) == 6
getMaxSubSum([-1, 2, 3, -9, *!*11*/!*]) == 11
getMaxSubSum([-2, -1, *!*1, 2*/!*]) == 3
getMaxSubSum([*!*100*/!*, -9, 2, -3, 5]) == 100
getMaxSubSum([*!*1, 2, 3*/!*]) == 6 (take all)
getMaxSubSum([*!*1, 2, 3*/!*]) == 6 (toma todo)
```

If all items are negative, it means that we take none (the subarrayis empty),so the sum is zero:
Si todos los elementos son negativos, significa que que no tomamos ninguno (el subarrayestá vacío),entonces la suma es cero:

```js
getMaxSubSum([-1, -2, -3]) = 0
```

Please try to think of a fast solution: [O(n<sup>2</sup>)](https://en.wikipedia.org/wiki/Big_O_notation) or even O(n)if you can.
Trata de pensar un solución rápida: [O(n<sup>2</sup>)](https://es.wikipedia.org/wiki/Notaci%C3%B3n_de_Landau) o incluso O(n)si puedes.
17 changes: 8 additions & 9 deletions1-js/05-data-types/04-array/2-create-array/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,17 +2,17 @@ importance: 5

---

#Array operations.
#Operaciones en arrays.

Let's try 5 array operations.
Tratemos 5 operaciones de array.

1.Create an array `styles`withitems "Jazz"and "Blues".
2.Append "Rock-n-Roll"to the end.
3.Replace the value in the middle by "Classics".Your code for finding the middle value should work for any arrays with odd length.
4.Strip off the first value of thearrayand show it.
5.Prepend `Rap`and `Reggae`to the array.
1.Crear un array `styles`con lositems "Jazz"y "Blues".
2.Agregar "Rock-n-Roll"al final.
3.Reemplazar el valor en el medio por "Classics".Tu código para encontrar el valor medio debe funcionar con cualquier array de longitud impar.
4.Quitar el primer valor delarrayy mostrarlo.
5.Anteponer `Rap`y `Reggae`al array.

The arrayin the process:
El arraydurante el proceso:

```js no-beautify
Jazz, Blues
Expand All@@ -21,4 +21,3 @@ Jazz, Classics, Rock-n-Roll
Classics, Rock-n-Roll
Rap, Reggae, Classics, Rock-n-Roll
```

6 changes: 3 additions & 3 deletions1-js/05-data-types/04-array/3-call-array-this/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
The call`arr[2]()`is syntactically the good old`obj[method]()`,in the role of `obj`we have`arr`,and in the role of `method`we have `2`.
El llamado a`arr[2]()`es sintácticamente el buen y viejo`obj[method]()`,en el rol de `obj`tenemos`arr`,y en el rol de `method`tenemos `2`.

So we have a call of the function`arr[2]`as an object method. Naturally, it receives`this`referencing the object `arr`and outputs the array:
Entonces tenemos una llamada a función`arr[2]`como un método de objeto. Naturalmente, recibe`this`referenciando el objeto `arr`y su salida es el array:

```js run
let arr = ["a", "b"];
Expand All@@ -12,4 +12,4 @@ arr.push(function() {
arr[2](); // a,b,function(){...}
```

The arrayhas 3values: initially it had two, plus the function.
El arraytiene 3valores: Iniciamente tenía 2 y se agregó la función.
5 changes: 2 additions & 3 deletions1-js/05-data-types/04-array/3-call-array-this/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,9 @@ importance: 5

---

#Calling in an array context
#LLamados en un contexto de array

What is the result? Why?
¿Cuál es el resultado y por qué?

```js
let arr = ["a", "b"];
Expand All@@ -15,4 +15,3 @@ arr.push(function() {

arr[2](); // ?
```

7 changes: 3 additions & 4 deletions1-js/05-data-types/04-array/5-array-input-sum/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
Please note the subtle, but important detail of the solution. We don't convert`value`to number instantly after`prompt`,because after`value = +value`we would not be able to tell an empty string (stop sign) from the zero (valid number).We do it later instead.
Toma nota del sutil pero importante detalle de la solución. No convertimos`value`a número instantáneamente después de`prompt`,porque después de`value = +value`no seríamos capaces de diferenciar una cadena vacía (señal de detención) de un cero (un número válido).Lo hacemos más adelante.


```js run demo
Expand All@@ -8,9 +8,9 @@ function sumInput() {

while (true) {

let value = prompt("A number please?", 0);
let value = prompt("Un número, por favor...", 0);

//should we cancel?
//¿Debemos cancelar?
if (value === "" || value === null || !isFinite(value)) break;

numbers.push(+value);
Expand All@@ -25,4 +25,3 @@ function sumInput() {

alert( sumInput() );
```

12 changes: 6 additions & 6 deletions1-js/05-data-types/04-array/5-array-input-sum/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,14 @@ importance: 4

---

#Sum input numbers
#Suma de números ingresados

Write the function `sumInput()`that:
Escribe una función `sumInput()`que:

-Asks the user for values using`prompt`and stores the values in the array.
-Finishes asking when the user enters a non-numeric value, an empty string, or presses "Cancel".
-Calculates and returns the sum of array items.
-Pida al usuario valores usando`prompt`y los almacene en el array.
-Termine de pedirlos cuando el usuario ingrese un valor no numérico, una cadena vacía, o presione "Escape".
-Calcule y devuelva la suma de los items del array.

P.S. A zero `0`is a valid number, please don't stop the input on zero.
P.D. Un cero `0`es un número válido, por favor no detengas los ingresos con el cero.

[demo]
Loading

[8]ページ先頭

©2009-2025 Movatter.jp