Skip to content

Arrays #115

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 35 commits into from
Oct 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
234e6ba
js.uk: 4 arrays
Sep 21, 2020
1364709
fix errors
Sep 21, 2020
ccf80a6
fix
Sep 21, 2020
0f5a847
Address some possible issues in translation of 1.2.9
vsemozhetbyt Sep 18, 2020
39fd695
Address some possible issues in 1.2.11
vsemozhetbyt Sep 20, 2020
4d0ed20
Address review suggestions
vsemozhetbyt Oct 3, 2020
f3d5f49
Merge pull request #118 from vsemozhetbyt/1.2.10
tarasyyyk Oct 3, 2020
e63ed1c
Update 1-js/02-first-steps/09-comparison/article.md
tarasyyyk Oct 3, 2020
c4c0d10
Merge pull request #117 from vsemozhetbyt/1.2.9
tarasyyyk Oct 3, 2020
0ec4f1a
Merge pull request #119 from vsemozhetbyt/1.2.11
tarasyyyk Oct 4, 2020
469f8b7
Merge branch 'master' into master
ArtemZununov Oct 7, 2020
0c13849
Update 1-js/05-data-types/04-array/1-item-value/solution.md
ArtemZununov Oct 21, 2020
e144e4c
Update 1-js/05-data-types/04-array/1-item-value/task.md
ArtemZununov Oct 21, 2020
f625bfd
Update 1-js/05-data-types/04-array/10-maximal-subarray/solution.md
ArtemZununov Oct 21, 2020
b292336
Update 1-js/05-data-types/04-array/10-maximal-subarray/solution.md
ArtemZununov Oct 21, 2020
18aa57d
Update 1-js/05-data-types/04-array/10-maximal-subarray/solution.md
ArtemZununov Oct 21, 2020
346df19
Update 1-js/05-data-types/04-array/article.md
ArtemZununov Oct 21, 2020
553d1bf
Update 1-js/05-data-types/04-array/article.md
ArtemZununov Oct 21, 2020
5c53bb0
Update 1-js/05-data-types/04-array/10-maximal-subarray/task.md
ArtemZununov Oct 21, 2020
3428177
Update 1-js/05-data-types/04-array/10-maximal-subarray/task.md
ArtemZununov Oct 21, 2020
0a33c74
Update 1-js/05-data-types/04-array/2-create-array/task.md
ArtemZununov Oct 21, 2020
9dda948
Update 1-js/05-data-types/04-array/10-maximal-subarray/task.md
ArtemZununov Oct 21, 2020
2959f84
Update 1-js/05-data-types/04-array/5-array-input-sum/solution.md
ArtemZununov Oct 21, 2020
f4a3cad
Update 1-js/05-data-types/04-array/3-call-array-this/solution.md
ArtemZununov Oct 21, 2020
3f3fd8d
Update 1-js/05-data-types/04-array/3-call-array-this/solution.md
ArtemZununov Oct 21, 2020
fbad78f
Update 1-js/05-data-types/04-array/article.md
ArtemZununov Oct 21, 2020
e3b6dc3
Update 1-js/05-data-types/04-array/3-call-array-this/task.md
ArtemZununov Oct 21, 2020
37e4fec
Update 1-js/05-data-types/04-array/3-call-array-this/task.md
ArtemZununov Oct 21, 2020
c934ebf
Update 1-js/05-data-types/04-array/5-array-input-sum/solution.md
ArtemZununov Oct 21, 2020
eab4e7e
Update 1-js/05-data-types/04-array/5-array-input-sum/task.md
ArtemZununov Oct 21, 2020
3daeba3
Update 1-js/05-data-types/04-array/article.md
ArtemZununov Oct 21, 2020
6695273
Update 1-js/05-data-types/04-array/article.md
ArtemZununov Oct 21, 2020
9155264
Update 1-js/05-data-types/04-array/article.md
ArtemZununov Oct 21, 2020
6b611f0
Update 1-js/05-data-types/04-array/article.md
ArtemZununov Oct 21, 2020
6946dc3
Merge branch 'master' into master
tarasyyyk Oct 21, 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
5 changes: 2 additions & 3 deletions 1-js/05-data-types/04-array/1-item-value/solution.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The result is `4`:
Відповідь `4`:


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

That's because arrays are objects. So both `shoppingCart` and `fruits` are the references to the same array.

Це відбувається тому, що масиви — це об’єкти. Отже, `shoppingCart` та `fruits` посилаються на один і той самий об’єкт.
9 changes: 4 additions & 5 deletions 1-js/05-data-types/04-array/1-item-value/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,17 @@ importance: 3

---

# Is array copied?
# Чи скопійовано масив?

What is this code going to show?
Що продемонструє наступний код?

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

// push a new value into the "copy"
// додаємо нове значення в "копію"
let shoppingCart = fruits;
shoppingCart.push("Banana");

// what's in fruits?
// Що в fruits?
alert( fruits.length ); // ?
```

36 changes: 18 additions & 18 deletions 1-js/05-data-types/04-array/10-maximal-subarray/solution.md
Original file line number Diff line number Diff line change
@@ -1,43 +1,43 @@
# Slow solution
# Повільне рішення

We can calculate all possible subsums.
Ми можемо порахувати всі можливі підсуми.

The simplest way is to take every element and calculate sums of all subarrays starting from it.
Найпростіший шлях - це порахувати суми всіх підмасивів, починаючи з кожного елемента.

For instance, for `[-1, 2, 3, -9, 11]`:
Наприклад, для `[-1, 2, 3, -9, 11]`:

```js no-beautify
// Starting from -1:
// Починаємо з -1:
-1
-1 + 2
-1 + 2 + 3
-1 + 2 + 3 + (-9)
-1 + 2 + 3 + (-9) + 11

// Starting from 2:
// Починаємо з 2:
2
2 + 3
2 + 3 + (-9)
2 + 3 + (-9) + 11

// Starting from 3:
// Починаємо з 3:
3
3 + (-9)
3 + (-9) + 11

// Starting from -9
// Починаємо з -9
-9
-9 + 11

// Starting from 11
// Починаємо з 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.
Вирішення потребує використання циклів: зовнішний цикл проходить по елементах масиву, а внутрішній рахує підсуму починаючи з поточного елементу.

```js run
function getMaxSubSum(arr) {
let maxSum = 0; // if we take no elements, zero will be returned
let maxSum = 0; // якщо елементи відсутні - повертаємо 0

for (let i = 0; i < arr.length; i++) {
let sumFixedStart = 0;
Expand All @@ -57,15 +57,15 @@ 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 the array size 2 times, the algorithm will work 4 times longer.
Таке рішення має оцінку часу виконання [O(n<sup>2</sup>)](https://uk.wikipedia.org/wiki/Нотація_Ландау). Інакше кажучи, якщо ми збільшимо розмір масиву вдвічі, алгоритм буде виконуватися в 4 рази довше.

For big arrays (1000, 10000 or more items) such algorithms can lead to a serious sluggishness.
Для великих масивів (1000, 10000 або більше елементів) подібні алгоритми можуть призводити до серйозних "пригальмувань" роботі.

# Fast solution
# Швидке рішення

Let's walk the array and keep the current partial sum of elements in the variable `s`. If `s` becomes negative at some point, then assign `s=0`. The maximum of all such `s` will be the answer.
Пройдемося по масиву і в процесі будемо накопичувати проміжну суму елементів в змінній `s`. Якщо в певний момент `s` стане меншою за 0, присвоїмо `s=0`. Максимальне значення з усіх `s` і буде відповіддю.

If the description is too vague, please see the code, it's short enough:
Якщо пояснення не дуже зрозуміле, подивіться, будь ласка, на код - він досить лаконічний:

```js run demo
function getMaxSubSum(arr) {
Expand All @@ -89,6 +89,6 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6
alert( getMaxSubSum([-1, -2, -3]) ); // 0
Copy link
Collaborator

Choose a reason for hiding this comment

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

Будь ласка, перекладіть також коментарі в коді вище.

```

The algorithm requires exactly 1 array pass, so the time complexity is O(n).
Цей алгоритм потребує рівно один прохід по масиву, його оціночний час виконання - 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.
Ви можете дізнатися більше про цей алгоритм тут: [Maximum subarray problem](http://en.wikipedia.org/wiki/Maximum_subarray_problem). Якщо досі не цілком зрозуміло, як це працює, будь ласка, подивіться алгоритм у прикладах вище, це буде краще за будь-які слова.
14 changes: 7 additions & 7 deletions 1-js/05-data-types/04-array/10-maximal-subarray/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ importance: 2

---

# A maximal subarray
# Максимальний підмасив

The input is an array of numbers, e.g. `arr = [1, -2, 3, 4, -9, 6]`.
На вході масив чисел, наприклад `arr = [1, -2, 3, 4, -9, 6]`.

The task is: find the contiguous subarray of `arr` with the maximal sum of items.
Завдання: знайти неперервний підмасив `arr` з максимальною сумою елементів.

Write the function `getMaxSubSum(arr)` that will return that sum.
Написати функцію `getMaxSubSum(arr)` яка повертає таку суму.

For instance:
Наприклад:

```js
getMaxSubSum([-1, *!*2, 3*/!*, -9]) == 5 (the sum of highlighted items)
Expand All @@ -21,10 +21,10 @@ getMaxSubSum([*!*100*/!*, -9, 2, -3, 5]) == 100
getMaxSubSum([*!*1, 2, 3*/!*]) == 6 (take all)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Будь ласка, перекладіть коментарі в коді вище.

```

If all items are negative, it means that we take none (the subarray is empty), so the sum is zero:
Якщо всі елементи менші нуля, нічого не беремо, це означає, що підмасив пустий, а сума рівна нулю:

```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.
Будь ласка, подумайте над швидким рішенням: [O(n<sup>2</sup>)](https://uk.wikipedia.org/wiki/Нотація_Ландау) або навіть над рішенням O(n), якщо зможете.
17 changes: 8 additions & 9 deletions 1-js/05-data-types/04-array/2-create-array/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ importance: 5

---

# Array operations.
# Операції з масивами.

Let's try 5 array operations.
Давайте спробуємо 5 операцій з масивом.

1. Create an array `styles` with items "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 the array and show it.
5. Prepend `Rap` and `Reggae` to the array.
1. Створіть масив `styles` з елементами "Jazz" та "Blues".
2. Додайте "Rock-n-Roll" в кінець масиву.
3. Замініть значення в середині масиву на "Classics". Ваш код повинен шукати медіанний елемент у масивах будь-якої довжини.
4. Видаліть перший елемент масиву та покажіть його.
5. Вставте `Rap` та `Reggae` на початок масиву.

The array in the process:
Вигляд масиву по ходу виконання операцій:

```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 deletions 1-js/05-data-types/04-array/3-call-array-this/solution.md
Original file line number Diff line number Diff 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`.
Виклик `arr[2]()` це - синтаксично старий-добрий `obj[method]()`, в ролі `obj` ми маємо `arr`, а в ролі `method` ми маємо `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:
Ми маємо виклик функції `arr[2]` як методу об’єкту. Відповідно, він отримає в якості `this` об’єкт `arr` та виведе масив:

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

The array has 3 values: initially it had two, plus the function.
Масив має 3 елемента, спочатку їх було 2, плюс функція.
5 changes: 2 additions & 3 deletions 1-js/05-data-types/04-array/3-call-array-this/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 5

---

# Calling in an array context
# Виклик в контексті масиву

What is the result? Why?
Яким буде результат? Чому?

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

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

7 changes: 3 additions & 4 deletions 1-js/05-data-types/04-array/5-array-input-sum/solution.md
Original file line number Diff line number Diff 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.
Зверніть увагу на одну важливу річ у вирішенні цієї задачі. Ми не конвертуємо `value` в число одразу після `prompt`, тому що одразу після операції `value = +value` ми не зможемо відрізнити порожній рядок (зупинення роботи функції) від нуля (дійсне число). Тому ми робимо це пізніше.


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

while (true) {

let value = prompt("A number please?", 0);
let value = prompt("Введіть, будь ласка, номер", 0);

// should we cancel?
// Обриваємо введення даних?
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 deletions 1-js/05-data-types/04-array/5-array-input-sum/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ importance: 4

---

# Sum input numbers
# Сума введених чисел

Write the function `sumInput()` that:
Напишіть функцію `sumInput()` яка:

- 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.
- Просить користувача ввести дані за допомогою `prompt` та зберігає їх в масив.
- Закінчує робити запити в користувача після того, як введено не числове значення, порожня строка або натиснуто "відмінити".
- Підраховує та повертає суму елементів масиву.

P.S. A zero `0` is a valid number, please don't stop the input on zero.
P.S. Нуль `0` це - валідне число, будь ласка, не зупиняйте функцію при введені `0`.

[demo]
Loading