Skip to content

Commit 7da397b

Browse files
committed
1-js/05-data-types/05-array-methods/
Ru translation: Tasks from 9 to 11 have been translated.
1 parent 298e04f commit 7da397b

5 files changed

Lines changed: 55 additions & 55 deletions

File tree

1-js/05-data-types/05-array-methods/10-average-age/solution.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@ function getAverageAge(users) {
33
return users.reduce((prev, user) => prev + user.age, 0) / users.length;
44
}
55

6-
let john = { name: "John", age: 25 };
7-
let pete = { name: "Pete", age: 30 };
8-
let mary = { name: "Mary", age: 29 };
6+
let vasya = { name: "Вася", age: 25 };
7+
let petya = { name: "Петя", age: 30 };
8+
let masha = { name: "Маша", age: 29 };
99

10-
let arr = [ john, pete, mary ];
10+
let arr = [ vasya, petya, masha ];
1111

1212
alert( getAverageAge(arr) ); // 28
1313
```

1-js/05-data-types/05-array-methods/10-average-age/task.md

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
1-
importance: 4
1+
важность: 4
22

33
---
44

5-
# Get average age
5+
# Получить средний возраст
66

7-
Write the function `getAverageAge(users)` that gets an array of objects with property `age` and gets the average.
7+
Напишите функцию `getAverageAge(users)`, которая принимает массив объектов со свойством `age` и возвращает его среднее значение.
88

9-
The formula for the average is `(age1 + age2 + ... + ageN) / N`.
9+
Формула вычисления среднего арифметического значения: `(age1 + age2 + ... + ageN) / N`.
1010

11-
For instance:
11+
Например:
1212

1313
```js no-beautify
14-
let john = { name: "John", age: 25 };
15-
let pete = { name: "Pete", age: 30 };
16-
let mary = { name: "Mary", age: 29 };
14+
let vasya = { name: "Вася", age: 25 };
15+
let petya = { name: "Петя", age: 30 };
16+
let masha = { name: "Маша", age: 29 };
1717

18-
let arr = [ john, pete, mary ];
18+
let arr = [ vasya, petya, masha ];
1919

2020
alert( getAverageAge(arr) ); // (25 + 30 + 29) / 3 = 28
2121
```
Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
Let's walk the array items:
2-
- For each item we'll check if the resulting array already has that item.
3-
- If it is so, then ignore, otherwise add to results.
1+
Давайте пройдёмся по элементам массива:
2+
- Для каждого элемента мы проверим, есть ли в массиве с результатом этот элемент.
3+
- Если есть, то игнорируем его, а если нет добавляем к результатам.
44

55
```js run demo
66
function unique(arr) {
@@ -15,25 +15,25 @@ function unique(arr) {
1515
return result;
1616
}
1717

18-
let strings = ["Hare", "Krishna", "Hare", "Krishna",
19-
"Krishna", "Krishna", "Hare", "Hare", ":-O"
18+
let strings = ["кришна", "кришна", "харе", "харе",
19+
"харе", "харе", "кришна", "кришна", ":-O"
2020
];
2121

22-
alert( unique(strings) ); // Hare, Krishna, :-O
22+
alert( unique(strings) ); // кришна, харе, :-O
2323
```
2424

25-
The code works, but there's a potential performance problem in it.
25+
Код работает, но в нём есть потенциальная проблемма с производительностью.
2626

27-
The method `result.includes(str)` internally walks the array `result` and compares each element against `str` to find the match.
27+
Метод `result.includes(str)` внутри себя обходит массив `result` и сравнивает каждый элемент с `str`, чтобы найти совпадение.
2828

29-
So if there are `100` elements in `result` and no one matches `str`, then it will walk the whole `result` and do exactly `100` comparisons. And if `result` is large, like `10000`, then there would be `10000` comparisons.
29+
Таким образом, если `result` содержит `100` элементов и ни один не сопоставляет со `str`, тогда он обойдёт весь `result` и сделает ровно `100` сравнений. А если `result` большой, например, `10000`, то будет произведено `10000` сравнений.
3030

31-
That's not a problem by itself, because JavaScript engines are very fast, so walk `10000` array is a matter of microseconds.
31+
Само по себе это не проблема, потому что движки JavaScript очень быстрые, поэтому обход `10000` элементов массива занимает считанные микросекунды.
3232

33-
But we do such test for each element of `arr`, in the `for` loop.
33+
Но мы делаем такую проверку для каждого элемента `arr` в цикле `for`.
3434

35-
So if `arr.length` is `10000` we'll have something like `10000*10000` = 100 millions of comparisons. That's a lot.
35+
Поэтому, если `arr.length` равен `10000`, у нас будет что-то вроде `10000*10000` = 100 миллионов сравнений. Это многовато.
3636

37-
So the solution is only good for small arrays.
37+
Вот почему данное решение подходит только для небольших массивов.
3838

39-
Further in the chapter <info:map-set-weakmap-weakset> we'll see how to optimize it.
39+
Далее в главе <info:map-set-weakmap-weakset> мы увидим, как его оптимизировать.
Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
1-
importance: 4
1+
важность: 4
22

33
---
44

5-
# Filter unique array members
5+
# Оставить уникальные элементы массива
66

7-
Let `arr` be an array.
7+
Пусть `arr` – массив строк.
88

9-
Create a function `unique(arr)` that should return an array with unique items of `arr`.
9+
Напишите функцию unique(arr), которая возвращает массив, содержащий только уникальные элементы `arr`.
1010

11-
For instance:
11+
Например:
1212

1313
```js
1414
function unique(arr) {
15-
/* your code */
15+
/* ваш код */
1616
}
1717

18-
let strings = ["Hare", "Krishna", "Hare", "Krishna",
19-
"Krishna", "Krishna", "Hare", "Hare", ":-O"
18+
let strings = ["кришна", "кришна", "харе", "харе",
19+
"харе", "харе", "кришна", "кришна", ":-O"
2020
];
2121

22-
alert( unique(strings) ); // Hare, Krishna, :-O
22+
alert( unique(strings) ); // кришна, харе, :-O
2323
```

1-js/05-data-types/05-array-methods/9-shuffle/solution.md

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
The simple solution could be:
1+
Простое решение может быть:
22

33
```js run
44
*!*
@@ -12,18 +12,18 @@ shuffle(arr);
1212
alert(arr);
1313
```
1414

15-
That somewhat works, because `Math.random() - 0.5` is a random number that may be positive or negative, so the sorting function reorders elements randomly.
15+
Это конечно будет работать потому, что `Math.random() - 0.5` отдаёт случайное число, которое может быть положительным или отрицательным, следовательно функция сортировки меняет порядок элементов случайным образом.
1616

17-
But because the sorting function is not meant to be used this way, not all permutations have the same probability.
17+
Но поскольку метод `sort` не предназначен для использования в таких случаях, не все возможные варианты имеют одинаковую вероятность.
1818

19-
For instance, consider the code below. It runs `shuffle` 1000000 times and counts appearances of all possible results:
19+
Например, рассмотрим код ниже. Он запускает `shuffle` 1000000 раз и считает вероятность появления для всех возможных вариантов `arr`:
2020

2121
```js run
2222
function shuffle(array) {
2323
array.sort(() => Math.random() - 0.5);
2424
}
2525

26-
// counts of appearances for all possible permutations
26+
// подсчёт вероятности для всех возможных вариантов
2727
let count = {
2828
'123': 0,
2929
'132': 0,
@@ -39,13 +39,13 @@ for (let i = 0; i < 1000000; i++) {
3939
count[array.join('')]++;
4040
}
4141

42-
// show counts of all possible permutations
42+
// показать количество всех возможных вариантов
4343
for (let key in count) {
4444
alert(`${key}: ${count[key]}`);
4545
}
4646
```
4747

48-
An example result (for V8, July 2017):
48+
Результат примера (для V8, июль 2017):
4949

5050
```js
5151
123: 250706
@@ -56,24 +56,24 @@ An example result (for V8, July 2017):
5656
321: 125223
5757
```
5858

59-
We can see the bias clearly: `123` and `213` appear much more often than others.
59+
Теперь мы отчётливо видим допущенное отклонение: `123` и `213` появляются намного чаще чем остальные варианты.
6060

61-
The result of the code may vary between JavaScript engines, but we can already see that the approach is unreliable.
61+
Результаты этого кода могут варьироваться при запуске на разных движках JavaScript, но очевидно что такой подход не надёжен.
6262

63-
Why it doesn't work? Generally speaking, `sort` is a "black box": we throw an array and a comparison function into it and expect the array to be sorted. But due to the utter randomness of the comparison the black box goes mad, and how exactly it goes mad depends on the concrete implementation that differs between engines.
63+
Так почему это не работает? Если говорить простыми словами, то `sort` это "чёрный ящик": мы бросаем в него массив и функцию сравнения ожидая получить отсортированный массив. Но из-за абсолютной хаотичности сравнений чёрный ящик сходит с ума, и как именно он сходит с ума, зависит от конкретной его реализации, которая различна на разных движках JavaScript.
6464

65-
There are other good ways to do the task. For instance, there's a great algorithm called [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). The idea is to walk the array in the reverse order and swap each element with a random one before it:
65+
Есть и другие хорошие способы решить эту задачу. Например, есть отличный алгоритм под названием [Тасование Фишера — Йетса](https://ru.wikipedia.org/wiki/%D0%A2%D0%B0%D1%81%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5_%D0%A4%D0%B8%D1%88%D0%B5%D1%80%D0%B0_%E2%80%94_%D0%99%D0%B5%D1%82%D1%81%D0%B0). Суть заключается в том, чтобы проходить по массиву в обратном порядке и менять местами каждый элемент со случайным элементом, который находится перед ним.
6666

6767
```js
6868
function shuffle(array) {
6969
for (let i = array.length - 1; i > 0; i--) {
70-
let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i
71-
[array[i], array[j]] = [array[j], array[i]]; // swap elements
70+
let j = Math.floor(Math.random() * (i + 1)); // случайный индекс от 0 до i
71+
[array[i], array[j]] = [array[j], array[i]]; // перестановка элементов
7272
}
7373
}
7474
```
7575

76-
Let's test it the same way:
76+
Давайте проверим эту реализацию на том же примере:
7777

7878
```js run
7979
function shuffle(array) {
@@ -83,7 +83,7 @@ function shuffle(array) {
8383
}
8484
}
8585

86-
// counts of appearances for all possible permutations
86+
// подсчёт вероятности для всех возможных вариантов
8787
let count = {
8888
'123': 0,
8989
'132': 0,
@@ -99,13 +99,13 @@ for (let i = 0; i < 1000000; i++) {
9999
count[array.join('')]++;
100100
}
101101

102-
// show counts of all possible permutations
102+
// показать количество всех возможных вариантов
103103
for (let key in count) {
104104
alert(`${key}: ${count[key]}`);
105105
}
106106
```
107107

108-
The example output:
108+
Пример вывода:
109109

110110
```js
111111
123: 166693
@@ -116,6 +116,6 @@ The example output:
116116
321: 166316
117117
```
118118

119-
Looks good now: all permutations appear with the same probability.
119+
Теперь всё в порядке: все варианты появляются с одинаковой вероятностью.
120120

121-
Also, performance-wise the Fisher-Yates algorithm is much better, there's no "sorting" overhead.
121+
Кроме того, если посмотреть с точки зрения производительности, то алгоритм "Тасование Фишера — Йетса" намного быстрее, так как в нём нет лишних затрат на сортировку.

0 commit comments

Comments
 (0)