Skip to content

Commit 756ef1b

Browse files
Translation 'Arrays' (#115)
* Translation 'Array' Co-authored-by: Taras <[email protected]>
1 parent 1c80c01 commit 756ef1b

File tree

10 files changed

+214
-219
lines changed

10 files changed

+214
-219
lines changed

1-js/05-data-types/04-array/1-item-value/solution.md

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
The result is `4`:
1+
Відповідь `4`:
22

33

44
```js run
@@ -13,5 +13,4 @@ alert( fruits.length ); // 4
1313
*/!*
1414
```
1515

16-
That's because arrays are objects. So both `shoppingCart` and `fruits` are the references to the same array.
17-
16+
Це відбувається тому, що масиви — це об’єкти. Отже, `shoppingCart` та `fruits` посилаються на один і той самий об’єкт.

1-js/05-data-types/04-array/1-item-value/task.md

+4-5
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,17 @@ importance: 3
22

33
---
44

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

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

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

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

16-
// what's in fruits?
16+
// Що в fruits?
1717
alert( fruits.length ); // ?
1818
```
19-

1-js/05-data-types/04-array/10-maximal-subarray/solution.md

+18-18
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,43 @@
1-
# Slow solution
1+
# Повільне рішення
22

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

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

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

99
```js no-beautify
10-
// Starting from -1:
10+
// Починаємо з -1:
1111
-1
1212
-1 + 2
1313
-1 + 2 + 3
1414
-1 + 2 + 3 + (-9)
1515
-1 + 2 + 3 + (-9) + 11
1616

17-
// Starting from 2:
17+
// Починаємо з 2:
1818
2
1919
2 + 3
2020
2 + 3 + (-9)
2121
2 + 3 + (-9) + 11
2222

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

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

32-
// Starting from 11
32+
// Починаємо з 11
3333
11
3434
```
3535

36-
The code is actually a nested loop: the external loop over array elements, and the internal counts subsums starting with the current element.
36+
Вирішення потребує використання циклів: зовнішний цикл проходить по елементах масиву, а внутрішній рахує підсуму починаючи з поточного елементу.
3737

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

4242
for (let i = 0; i < arr.length; i++) {
4343
let sumFixedStart = 0;
@@ -57,15 +57,15 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6
5757
alert( getMaxSubSum([100, -9, 2, -3, 5]) ); // 100
5858
```
5959

60-
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.
60+
Таке рішення має оцінку часу виконання [O(n<sup>2</sup>)](https://uk.wikipedia.org/wiki/Нотація_Ландау). Інакше кажучи, якщо ми збільшимо розмір масиву вдвічі, алгоритм буде виконуватися в 4 рази довше.
6161

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

64-
# Fast solution
64+
# Швидке рішення
6565

66-
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.
66+
Пройдемося по масиву і в процесі будемо накопичувати проміжну суму елементів в змінній `s`. Якщо в певний момент `s` стане меншою за 0, присвоїмо `s=0`. Максимальне значення з усіх `s` і буде відповіддю.
6767

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

7070
```js run demo
7171
function getMaxSubSum(arr) {
@@ -89,6 +89,6 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6
8989
alert( getMaxSubSum([-1, -2, -3]) ); // 0
9090
```
9191

92-
The algorithm requires exactly 1 array pass, so the time complexity is O(n).
92+
Цей алгоритм потребує рівно один прохід по масиву, його оціночний час виконання - O(n).
9393

94-
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.
94+
Ви можете дізнатися більше про цей алгоритм тут: [Maximum subarray problem](http://en.wikipedia.org/wiki/Maximum_subarray_problem). Якщо досі не цілком зрозуміло, як це працює, будь ласка, подивіться алгоритм у прикладах вище, це буде краще за будь-які слова.

1-js/05-data-types/04-array/10-maximal-subarray/task.md

+7-7
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@ importance: 2
22

33
---
44

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

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

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

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

13-
For instance:
13+
Наприклад:
1414

1515
```js
1616
getMaxSubSum([-1, *!*2, 3*/!*, -9]) == 5 (the sum of highlighted items)
@@ -21,10 +21,10 @@ getMaxSubSum([*!*100*/!*, -9, 2, -3, 5]) == 100
2121
getMaxSubSum([*!*1, 2, 3*/!*]) == 6 (take all)
2222
```
2323

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

2626
```js
2727
getMaxSubSum([-1, -2, -3]) = 0
2828
```
2929

30-
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.
30+
Будь ласка, подумайте над швидким рішенням: [O(n<sup>2</sup>)](https://uk.wikipedia.org/wiki/Нотація_Ландау) або навіть над рішенням O(n), якщо зможете.

1-js/05-data-types/04-array/2-create-array/task.md

+8-9
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,17 @@ importance: 5
22

33
---
44

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

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

9-
1. Create an array `styles` with items "Jazz" and "Blues".
10-
2. Append "Rock-n-Roll" to the end.
11-
3. Replace the value in the middle by "Classics". Your code for finding the middle value should work for any arrays with odd length.
12-
4. Strip off the first value of the array and show it.
13-
5. Prepend `Rap` and `Reggae` to the array.
9+
1. Створіть масив `styles` з елементами "Jazz" та "Blues".
10+
2. Додайте "Rock-n-Roll" в кінець масиву.
11+
3. Замініть значення в середині масиву на "Classics". Ваш код повинен шукати медіанний елемент у масивах будь-якої довжини.
12+
4. Видаліть перший елемент масиву та покажіть його.
13+
5. Вставте `Rap` та `Reggae` на початок масиву.
1414

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

1717
```js no-beautify
1818
Jazz, Blues
@@ -21,4 +21,3 @@ Jazz, Classics, Rock-n-Roll
2121
Classics, Rock-n-Roll
2222
Rap, Reggae, Classics, Rock-n-Roll
2323
```
24-

1-js/05-data-types/04-array/3-call-array-this/solution.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
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`.
1+
Виклик `arr[2]()` це - синтаксично старий-добрий `obj[method]()`, в ролі `obj` ми маємо `arr`, а в ролі `method` ми маємо `2`.
22

3-
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:
3+
Ми маємо виклик функції `arr[2]` як методу об’єкту. Відповідно, він отримає в якості `this` об’єкт `arr` та виведе масив:
44

55
```js run
66
let arr = ["a", "b"];
@@ -12,4 +12,4 @@ arr.push(function() {
1212
arr[2](); // a,b,function(){...}
1313
```
1414

15-
The array has 3 values: initially it had two, plus the function.
15+
Масив має 3 елемента, спочатку їх було 2, плюс функція.

1-js/05-data-types/04-array/3-call-array-this/task.md

+2-3
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ importance: 5
22

33
---
44

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

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

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

1616
arr[2](); // ?
1717
```
18-

1-js/05-data-types/04-array/5-array-input-sum/solution.md

+3-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
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.
1+
Зверніть увагу на одну важливу річ у вирішенні цієї задачі. Ми не конвертуємо `value` в число одразу після `prompt`, тому що одразу після операції `value = +value` ми не зможемо відрізнити порожній рядок (зупинення роботи функції) від нуля (дійсне число). Тому ми робимо це пізніше.
22

33

44
```js run demo
@@ -8,9 +8,9 @@ function sumInput() {
88

99
while (true) {
1010

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

13-
// should we cancel?
13+
// Обриваємо введення даних?
1414
if (value === "" || value === null || !isFinite(value)) break;
1515

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

2626
alert( sumInput() );
2727
```
28-

1-js/05-data-types/04-array/5-array-input-sum/task.md

+6-6
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@ importance: 4
22

33
---
44

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

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

9-
- Asks the user for values using `prompt` and stores the values in the array.
10-
- Finishes asking when the user enters a non-numeric value, an empty string, or presses "Cancel".
11-
- Calculates and returns the sum of array items.
9+
- Просить користувача ввести дані за допомогою `prompt` та зберігає їх в масив.
10+
- Закінчує робити запити в користувача після того, як введено не числове значення, порожня строка або натиснуто "відмінити".
11+
- Підраховує та повертає суму елементів масиву.
1212

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

1515
[demo]

0 commit comments

Comments
 (0)