Skip to content

Loops: while and for #50

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Sep 9, 2019
14 changes: 7 additions & 7 deletions 1-js/02-first-steps/12-while-for/1-loop-last-value/solution.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The answer: `1`.
La respuesta: `1`.

```js run
let i = 3;
Expand All @@ -8,18 +8,18 @@ while (i) {
}
```

Every loop iteration decreases `i` by `1`. The check `while(i)` stops the loop when `i = 0`.
Cada iteración del bucle disminuye `i` por `1`. La comprobación `while(i)` detiene el bucle cuando `i = 0`.

Hence, the steps of the loop form the following sequence ("loop unrolled"):
Por consiguiente, los pasos del bucle forman la siguiente secuencia ("bucle desenrollado").

```js
let i = 3;

alert(i--); // shows 3, decreases i to 2
alert(i--); // muestra 3, disminuye i a 2

alert(i--) // shows 2, decreases i to 1
alert(i--) // muestra 2, disminuye i a 1

alert(i--) // shows 1, decreases i to 0
alert(i--) // muestra 1, disminuye i a 0

// done, while(i) check stops the loop
// listo, while(i) comprueba y detiene el bucle
```
4 changes: 2 additions & 2 deletions 1-js/02-first-steps/12-while-for/1-loop-last-value/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 3

---

# Last loop value
# Ultimo valor del bucle
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Falta tilde en la U


What is the last value alerted by this code? Why?
¿Qué es alertado por el último valor de este código? ¿Por qué?

```js
let i = 3;
Expand Down
22 changes: 11 additions & 11 deletions 1-js/02-first-steps/12-while-for/2-which-value-while/solution.md
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
The task demonstrates how postfix/prefix forms can lead to different results when used in comparisons.
La tarea demuestra como las formas de sufjio y prefijo pueden llevar a diferentes resultado cuando son usadas en comparaciones.
Copy link
Collaborator

@tscandalitta tscandalitta May 27, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

como -> cómo
La palabra sufijo está mal escrita
resultadoS


1. **From 1 to 4**
1. **Del 1 al 4**

```js run
let i = 0;
while (++i < 5) alert( i );
```

The first value is `i = 1`, because `++i` first increments `i` and then returns the new value. So the first comparison is `1 < 5` and the `alert` shows `1`.
El primer valor es `i = 1`, porque primero `++i` incrementa `i` y entonces retorna el valor nuevo. Asi que la primera comparación es `1 < 5` y el `alert` muestra `1`.

Then follow `2, 3, 4…` -- the values show up one after another. The comparison always uses the incremented value, because `++` is before the variable.
Entonces siguen `2, 3, 4…` -- los valores son mostrados uno tras de otro. La comparación siempre usa el valor incrementado, porque `++` esta antes de la variable.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sugiero: "...mostrados uno tras otro. La comparación siempre usa el valor incrementado porque ++ está antes de la variable."


Finally, `i = 4` is incremented to `5`, the comparison `while(5 < 5)` fails, and the loop stops. So `5` is not shown.
2. **From 1 to 5**
Finalmente, `i = 4` es incrementada a `5`, la comparación `while(5 < 5)` falla, y el bucle se detiene. Asi que `5` no es mostrado.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Asi -> Así

2. **Del 1 al 5**

```js run
let i = 0;
while (i++ < 5) alert( i );
```

The first value is again `i = 1`. The postfix form of `i++` increments `i` and then returns the *old* value, so the comparison `i++ < 5` will use `i = 0` (contrary to `++i < 5`).
El primer valor es de nuevo `i = 1`. La forma del sufijo de `i++` incrementa `i` y entonce retorna el valor *viejo*, asi que la comparación `i++ < 5` usara `i = 0` (contrario a `++i < 5`).
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

asi -> así
entonces -> luego
usara -> usará


But the `alert` call is separate. It's another statement which executes after the increment and the comparison. So it gets the current `i = 1`.
Pero la llamada a `alert` esta separda. Es otra declaración la cual se ejecuta luego del increment y la comparación. Asi que obtiene el `i = 1` actual.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

esta->está
increment->incremento
Asi->Así


Then follow `2, 3, 4…`
Luego siguen `2, 3, 4…`

Let's stop on `i = 4`. The prefix form `++i` would increment it and use `5` in the comparison. But here we have the postfix form `i++`. So it increments `i` to `5`, but returns the old value. Hence the comparison is actually `while(4 < 5)` -- true, and the control goes on to `alert`.
Vamos a parar en `i = 4`. La forma del prefijo `++i` lo incrementaria y usaria `5` en la comparación. Pero aqui tenemos la forma del sufijo `i++`. Asi que incrementa `i` a `5`, pero retorna el valor viejo. Por lo tanto, la comparación es en realidad `while(4 < 5)` -- verdadero, y el control sigue a `alert`.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Me parece que quedaría mejor "Detengámonos en i = 4." o "Paremos en i = 4."
Faltan varios tildes en incrementaría, usaría, aquí, así.


The value `i = 5` is the last one, because on the next step `while(5 < 5)` is false.
El valor `i = 5` es el último, porque el siguiente paso `while(5 < 5)` es falso.
10 changes: 5 additions & 5 deletions 1-js/02-first-steps/12-while-for/2-which-value-while/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@ importance: 4

---

# Which values does the while loop show?
# ¿Cuál valor es mostrado por el bucle while?

For every loop iteration, write down which value it outputs and then compare it with the solution.
Para cada iteración del bucle, escribe cual valor sera impreso y entonces comparalo con la solución.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quedaría mejor "Para cada iteración del bucle, escribe qué valor será mostrado y luego compáralo con la solución."


Both loops `alert` the same values, or not?
¿Para cada bucle se alertan los mismos valores o no?
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Me parece que quedaría mejor "Ambos bucles ¿alertan los mismos valores?"


1. The prefix form `++i`:
1. La forma de prefijo `++i`:

```js
let i = 0;
while (++i < 5) alert( i );
```
2. The postfix form `i++`
2. La forma de sufijo `i++`

```js
let i = 0;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
**The answer: from `0` to `4` in both cases.**
**La respuesta: de `0 `a `4` en ambaos casos.**

```js run
for (let i = 0; i < 5; ++i) alert( i );
Expand Down
10 changes: 5 additions & 5 deletions 1-js/02-first-steps/12-while-for/3-which-value-for/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ importance: 4

---

# Which values get shown by the "for" loop?
# ¿Qué valores seran mostrados por el bucle "for"?
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seran->serán


For each loop write down which values it is going to show. Then compare with the answer.
Para cada bucle anota que valores va a mostrar. Entonces compara con la respuesta.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No hace falta una traducción textual, quedaría mejor:
"Para cada bucle anota qué valores mostrará y luego compara con la respuesta."


Both loops `alert` same values or not?
¿Ambos bucles alertan los mismos valores o no?
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Me parece que quedaría mejor "Ambos bucles ¿alertan los mismos valores?"


1. The postfix form:
1. La forma del sufijo:

```js
for (let i = 0; i < 5; i++) alert( i );
```
2. The prefix form:
2. La forma del prefijo:

```js
for (let i = 0; i < 5; ++i) alert( i );
Expand Down
2 changes: 1 addition & 1 deletion 1-js/02-first-steps/12-while-for/4-for-even/solution.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ for (let i = 2; i <= 10; i++) {
}
```

We use the "modulo" operator `%` to get the remainder and check for the evenness here.
Usamos el operador modulo `%` para conseguir el residuo y que los valores son pares.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Usamos el operador "módulo" % para conseguir el residuo y chequear la paridad.

4 changes: 2 additions & 2 deletions 1-js/02-first-steps/12-while-for/4-for-even/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ importance: 5

---

# Output even numbers in the loop
# Produce números pares en el bucle
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Produce->Muestra


Use the `for` loop to output even numbers from `2` to `10`.
Usa el bucle `for` para producir números pares del `2` al `10`.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"...para mostrar..."


[demo]
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
```js run
let i = 0;
while (i < 3) {
alert( `number ${i}!` );
alert( `número ${i}!` );
i++;
}
```
Expand Down
6 changes: 3 additions & 3 deletions 1-js/02-first-steps/12-while-for/5-replace-for-while/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ importance: 5

---

# Replace "for" with "while"
# Reemplaza "for" por "while"

Rewrite the code changing the `for` loop to `while` without altering its behavior (the output should stay same).
Reescribe el código cambiando el bucle `for` a `while` sin alterar su comportamient (la salida deberia ser la misma).
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

comportamientO
deberia->debería


```js run
for (let i = 0; i < 3; i++) {
alert( `number ${i}!` );
alert( `número ${i}!` );
}
```

Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
let num;

do {
num = prompt("Enter a number greater than 100?", 0);
num = prompt("Ingresa un número mayor a 100", 0);
} while (num <= 100 && num);
```

The loop `do..while` repeats while both checks are truthy:
El bucle `do..while` se repite mientras ambas comprobaciones sean valores verdaderos:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Podría quedar mejor "mientras ambas condiciones sean verdaderas:" o no?


1. The check for `num <= 100` -- that is, the entered value is still not greater than `100`.
2. The check `&& num` is false when `num` is `null` or a empty string. Then the `while` loop stops too.
1. La comprobación para `num <= 100` -- eso es, el valor ingresado aún no es mayor que `100`.
2. La comprobación `&& num` es falsa cuando `num` es `null` o una cadena de texto vacia. Entonces el bucle `while` se detiene tambien.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"La condición num <= 100 ..."
"La condición && num ..."
tambien->también


P.S. If `num` is `null` then `num <= 100` is `true`, so without the 2nd check the loop wouldn't stop if the user clicks CANCEL. Both checks are required.
PD. Si `num` es `null` entonces `num <= 100` es `true`, asi que sin la segunda comprabación el bucle no se detendria si el usuario hace click en CANCELAR. Ambas comprobaciones son requreridas.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

asi->así
detendria->detendría
Si arriba cambiaste comprobación por condición, acá deberías también para que haya más consistencia.

Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ importance: 5

---

# Repeat until the input is correct
# Repite hasta que la entrada sea correcta

Write a loop which prompts for a number greater than `100`. If the visitor enters another number -- ask them to input again.
Escribe un bucle que solicita un número mayor que `100`. Si el visitante ingresa otro número -- pideles que ingresen un valor de nuevo.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

solicita->solicite
"pídele que ingrese un valor nuevamente." visitante singular
Podrías cambiar visitante por usuario ya que en otros artículos se tradujo visitor por usuario


The loop must ask for a number until either the visitor enters a number greater than `100` or cancels the input/enters an empty line.
El bucle debe pedir por un número hasta que o el visitante ingrese un número mayor que `100` o cancele la entrada/ingresa un la linea vacía.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"El bucle debe pedir por un número hasta que el visitante ingrese un número mayor que 100 o bien cancele la entrada/ingrese un la linea vacía."


Here we can assume that the visitor only inputs numbers. There's no need to implement a special handling for a non-numeric input in this task.
Aquí podemos asumir que el visitante solo ingresara números. No hay necesidad de implementar un manejo especial para entradas no numéricas en esta tarea.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ingresara->ingresará


[demo]
25 changes: 12 additions & 13 deletions 1-js/02-first-steps/12-while-for/7-list-primes/solution.md
Original file line number Diff line number Diff line change
@@ -1,29 +1,28 @@
There are many algorithms for this task.
Hay muchos algoritmos para esta tarea.

Let's use a nested loop:
Vamos a usar un bucle anidado.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Utilicemos un ..
Usemos un ..


```js
For each i in the interval {
check if i has a divisor from 1..i
if yes => the value is not a prime
if no => the value is a prime, show it
Por cada i en el intervalo {
comprobar si i tiene un divisor en 1..i
si sí => el valor no es un primo
si no => el valor es un primo, enséñalo
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Podria cambiarse "si sí" por "si tiene" para que sea más claro.
enséñalo-> mostrarlo

}
```

The code using a label:
El codigo usando una etiqueta:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

codigo->código


```js run
let n = 10;

nextPrime:
for (let i = 2; i <= n; i++) { // for each i...
for (let i = 2; i <= n; i++) { // por cada i...

for (let j = 2; j < i; j++) { // look for a divisor..
if (i % j == 0) continue nextPrime; // not a prime, go next i
for (let j = 2; j < i; j++) { // buscar por un divisor..
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"buscar un divisor.."

if (i % j == 0) continue nextPrime; // no es un primo, ir al proximo i
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Podría eliminarse el "un"
proximo->próximo

}

alert( i ); // a prime
alert( i ); // un primo
}
```

There's a lot of space to opimize it. For instance, we could look for the divisors from `2` to square root of `i`. But anyway, if we want to be really efficient for large intervals, we need to change the approach and rely on advanced maths and complex algorithms like [Quadratic sieve](https://en.wikipedia.org/wiki/Quadratic_sieve), [General number field sieve](https://en.wikipedia.org/wiki/General_number_field_sieve) etc.
Hay un monton de espacio para optimizarlo. Por ejemplo, podriamos buscar por divisores desde `2` hasta la raíz cuadrada de `i`. Pero de todas formas, si queremos ser realmente eficientes para intervalos grandes, tenemos que cambiar el enfoque y confiar en matemáticas avanzadas y algoritmos complejos como [Criba cuadrática](https://es.wikipedia.org/wiki/Criba_cuadr%C3%A1tica), [Criba general del cuerpo de números](https://es.wikipedia.org/wiki/Criba_general_del_cuerpo_de_n%C3%BAmeros) etc.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Hay mucho lugar para la mejora. Por ejemplo..."
podriamos->podríamos
tenemos que-> necesitamos

14 changes: 7 additions & 7 deletions 1-js/02-first-steps/12-while-for/7-list-primes/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ importance: 3

---

# Output prime numbers
# Muestra números primos

An integer number greater than `1` is called a [prime](https://en.wikipedia.org/wiki/Prime_number) if it cannot be divided without a remainder by anything except `1` and itself.
Un número entero mayor que `1` es llamado [primo](https://es.wikipedia.org/wiki/N%C3%BAmero_primo) si no puede ser divido sin un residuo por cualquier número excepto `1` y el mismo.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

divido->dividido
cualquier->ningún
el-> él


In other words, `n > 1` is a prime if it can't be evenly divided by anything except `1` and `n`.
En otras palabras, `n > 1` es un primo si no puede ser divido parejamente por cualquier número except `1` y `n`.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

divido parejamente -> dividido exactamente
exceptO

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cualquier->ningún


For example, `5` is a prime, because it cannot be divided without a remainder by `2`, `3` and `4`.
Por ejemplo, `5` es un primo, porque no puede ser divido sin un residuo por `2`, `3` y `4`.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"..porque no puede ser divido exactamente por 2, 3 y 4." me parece que queda más claro


**Write the code which outputs prime numbers in the interval from `2` to `n`.**
**Escribe el código que muestra números primos en el intervalo de `2` a `n`.**
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

muestra->muestre


For `n = 10` the result will be `2,3,5,7`.
Para `n = 10` el resultado sera `2, 3, 5, 7`.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sera->será


P.S. The code should work for any `n`, not be hard-tuned for any fixed value.
PD. El código deberia funcionar para cualquier `n`, no debe estar programado para valores fijos.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

deberia ->debería

Loading