Skip to content

Loops tasks #190

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 5 commits into from
Aug 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
14 changes: 7 additions & 7 deletions 1-js/02-first-steps/13-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`.
Відповідь: `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`.
Кожна ітерація циклу зменшує `i` на `1`. Перевірка `while (i)` зупинить цикл, коли `i = 0`.

Hence, the steps of the loop form the following sequence ("loop unrolled"):
Відповідно, ось так буде виконуватися цикл («розгорнемо» цикл):

```js
let i = 3;

alert(i--); // shows 3, decreases i to 2
alert(i--); // покаже 3, потім зменшить i до 2

alert(i--) // shows 2, decreases i to 1
alert(i--) // покаже 2, потім зменшить i до 1

alert(i--) // shows 1, decreases i to 0
alert(i--) // покаже 1, потім зменшить i до 0

// done, while(i) check stops the loop
// все, перевірка while (i) зупинить цикл
```
22 changes: 11 additions & 11 deletions 1-js/02-first-steps/13-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.
Завдання демонструє, як префіксна/постфіксна форми можуть призвести до різних результатів при їх порівнянні.

1. **From 1 to 4**
1. Перший цикл виведе числа **від 1 до 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`.
Перше значення `i = 1`, тому що операція `++i` спочатку збільшує `i`, і після цього повертає *нове* значення. Відповідно, перше порівняння буде `1 < 5` і `alert` виведе `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.
Далі йдуть `2, 3, 4…` -- значення показуються одне за одним. Порівняння завжди відбувається зі збільшеним значенням, тому що `++` стоїть перед змінною.

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**
Наприкінці, коли `i = 4` збільшується до `5`, умова `while(5 < 5)` не справджується, і в результаті цикл зупиняється. Отже, `5` не покажеться.
2. Другий цикл виведе числа **від 1 до 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`).
Перше значення знову `i = 1`. Постфіксна форма `i++` збільшує `i` до `1` і повертає *старе* значення, тому порівняння `i++ < 5` буде виконуватися з `i = 0` (на противагу `++i < 5`).

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`.
Далі йде виклик `alert`. Однак, це вже інший вираз, який виконується після збільшення `i` та порівняння. Тому він отримає поточне значення `i = 1`.

Then follow `2, 3, 4…`
Далі слідують `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`.
Зупинимося на `i = 4`. Префіксна форма `++i` збільшила б `i` до `5` і використала це значення в порівнянні. Проте ми маємо постфіксну форму `i++`. Отже, вона збільшить `i` до `5`, але поверне старе значення. Таким чином порівняння буде `while(4 < 5)` -- що вірно, а тому відбудеться виклик `alert`.

The value `i = 5` is the last one, because on the next step `while(5 < 5)` is false.
Значення `i = 5` буде останнім, тому що наступний крок вже буде `while(5 < 5)` -- що не вірно.
10 changes: 5 additions & 5 deletions 1-js/02-first-steps/13-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?
# Яке значення виведе цикл "while"?

For every loop iteration, write down which value it outputs and then compare it with the solution.
Запишіть для кожного циклу значення, які він виведе. Потім порівняйте з відповіддю.

Both loops `alert` the same values, or not?
Чи виводять обидва цикли однакові значення?

1. The prefix form `++i`:
1. Префіксна форма `++i`:

```js
let i = 0;
while (++i < 5) alert( i );
```
2. The postfix form `i++`
2. Постфіксна форма `i++`

```js
let i = 0;
Expand Down
14 changes: 7 additions & 7 deletions 1-js/02-first-steps/13-while-for/3-which-value-for/solution.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
**The answer: from `0` to `4` in both cases.**
**Відповідь: обидва цикли виведуть від `0` до `4`.**

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

for (let i = 0; i < 5; i++) alert( i );
```

That can be easily deducted from the algorithm of `for`:
Такий результат обумовлений алгоритмом роботи `for`:

1. Execute once `i = 0` before everything (begin).
2. Check the condition `i < 5`
3. If `true` -- execute the loop body `alert(i)`, and then `i++`
1. Перед виконанням циклу, присвоїти `i = 0` (початок).
2. Перевірити умову `i < 5`.
3. Якщо `true` -- виконати тіло циклу: викликати `alert(i)`, а потім `i++`.

The increment `i++` is separated from the condition check (2). That's just another statement.
Збільшення `i++` виконується окремо від перевірки умови (2 крок). Це інша інструкція.

The value returned by the increment is not used here, so there's no difference between `i++` and `++i`.
Значення `i` після збільшення тут не використовується, тому немає різниці між `i++` та `++i`.
10 changes: 5 additions & 5 deletions 1-js/02-first-steps/13-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?
# Яке значення виведе цикл "for"?

For each loop write down which values it is going to show. Then compare with the answer.
Для кожного циклу запишіть, які значення він виведе. Потім порівняйте з відповіддю.

Both loops `alert` same values or not?
Обидва цикли виведуть одинакові числа чи ні?

1. The postfix form:
1. Постфіксна форма:

```js
for (let i = 0; i < 5; i++) alert( i );
```
2. The prefix form:
2. Префіксна форма:

```js
for (let i = 0; i < 5; ++i) alert( i );
Expand Down
2 changes: 1 addition & 1 deletion 1-js/02-first-steps/13-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.
Для того, щоб перевіряти числа на парність, ми використовуємо оператор остачі від ділення `%`.
4 changes: 2 additions & 2 deletions 1-js/02-first-steps/13-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
# Виведіть парні числа

Use the `for` loop to output even numbers from `2` to `10`.
Виведіть парні числа від `2` до `10`, використовуючи цикл `for`.

[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( `число ${i}!` );
i++;
}
```
Expand Down
6 changes: 3 additions & 3 deletions 1-js/02-first-steps/13-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"
# Замініть цикл "for" на "while"

Rewrite the code changing the `for` loop to `while` without altering its behavior (the output should stay same).
Замініть цикл `for` на `while` так, щоб поведінка не змінилася (щоб вивід залишився той самий).

```js run
for (let i = 0; i < 3; i++) {
alert( `number ${i}!` );
alert( `число ${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("Введене число, більше за 100?", 0);
} while (num <= 100 && num);
```

The loop `do..while` repeats while both checks are truthy:
Цикл `do..while` повторятиметься доки справджуються дві перевірки:

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 an empty string. Then the `while` loop stops too.
1. Перевірка `num <= 100` -- тобто, що введе число досі менше за `100`.
2. Перевірка `&& num` рахуватиметься `false`, коли `num` матиме значення `null` або порожній рядок `''`. В цьому випадку цикл `while` теж потрібно буде зупинити.

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.
Друга перевірка додається тому що, якщо `num` буде `null`, тоді перевірка `num <= 100` верне `true`. Отже, без другої перевірки цикл не зупиниться, якщо користувач натисне Скасувати. Необхідні обидві перевірки.
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ importance: 5

---

# Repeat until the input is correct
# Повторяти цикл, доки ввід невірний

Write a loop which prompts for a number greater than `100`. If the visitor enters another number -- ask them to input again.
Напишіть цикл, який пропонує `prompt` ввести число більше за `100`. Якщо відвідувач введе інше число -- попросити ввести ще раз, і так далі.

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.
Цикл повинен запитувати число доти, доки відвідувач не введе число, більше за `100`, або не скасує ввід/введе порожній рядок.

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.
Ми припускаємо, що відвідувач вводитиме лише числа. В цьому завданні не обов’язково реалізовувати оброблення не-числового введення.

[demo]
24 changes: 12 additions & 12 deletions 1-js/02-first-steps/13-while-for/7-list-primes/solution.md
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
There are many algorithms for this task.
Є багато способів для вирішення цієї задачі.

Let's use a nested loop:
Скористаймося вкладеними циклами:

```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
Для кожного `i` в інтервалі (від 2 до n) {
перевірити, чи число `i` має дільник з діапазону 2..i
якщо так => значення не просте
якщо ні => значення просте, показати його
}
```

The code using a label:
Код з використанням мітки:

```js run
let n = 10;

nextPrime:
for (let i = 2; i <= n; i++) { // for each i...
for (let i = 2; i <= n; i++) { // для кожного 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++) { // шукаємо дільник..
if (i % j == 0) continue nextPrime; // не просте, беремо наступне i
}

alert( i ); // a prime
alert( i ); // просте число
}
```

There's a lot of space to optimize 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.
Звичайно, цей код можна оптимізувати з точки зору продуктивності. Наприклад, ми могли б перевіряти всі `j` від `2` до квадратного кореня з `i`. Але все ж таки, якби потрібно було перебирати справді великі числа, нам прийшлося б використовувати просунуту математику і складні алгоритми на кшталт [квадратичного решета](https://uk.wikipedia.org/wiki/Квадратичне_решето) чи [методу решета числового поля](https://uk.wikipedia.org/wiki/Метод_решета_числового_поля).
14 changes: 7 additions & 7 deletions 1-js/02-first-steps/13-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
# Вивести прості числа

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.
[Просте число](https://uk.wikipedia.org/wiki/Просте_число) -- це натуральне число, яке має два дільники (`1` і саме число).

In other words, `n > 1` is a prime if it can't be evenly divided by anything except `1` and `n`.
Інакше кажучи, `n > 1` -- просте, якщо воно більше за `1` і ділиться без остачі на `1` та `n`.

For example, `5` is a prime, because it cannot be divided without a remainder by `2`, `3` and `4`.
Наприклад, число `5` -- просте, тому що воно не ділиться без остачі на `2`, `3` і `4`. Воно ділиться без остачі лише на `1` і на `5`.

**Write the code which outputs prime numbers in the interval from `2` to `n`.**
**Напишіть код, який виводить всі прості числа в діапазоні від `2` до `n`.**

For `n = 10` the result will be `2,3,5,7`.
Для `n = 10` результат повинен бути `2,3,5,7`.

P.S. The code should work for any `n`, not be hard-tuned for any fixed value.
P.S. Код також повинен легко модифікуватися для будь-якого числа `n`.