Skip to content

Arrays #72

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 3 commits into from Mar 2, 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
4 changes: 2 additions & 2 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,5 @@ alert( fruits.length ); // 4
*/!*
```

That's because arrays are objects. So both `shoppingCart` and `fruits` are the references to the same array.
Това е защото масивите са обекти. Така че `shoppingCart` и `fruits` са референции към един и същ масив.

8 changes: 4 additions & 4 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,18 @@ 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 ); // ?
```

44 changes: 22 additions & 22 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.
Кодът всъщност е 2 вложени цикъла. Външният итерира през елементите на масива, а вътрешният пресмята субсумите, започвайки от текущия елемент.

```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,25 +57,25 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6
alert( getMaxSubSum([100, -9, 2, -3, 5]) ); // 100
```

The solution has a time complexity 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://en.wikipedia.org/wiki/Big_O_notation). С други думи, ако увеличим размера на масива 2 пъти, алгоритъмът ще работи 4 пъти по-дълго.

For big arrays (1000, 10000 or more items) such algorithms can lead to a serious sluggishness.
При големи масиви (1000, 10000 or more items) такива алгоритми могат да доведат до сериозно забавяне.

# 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` стане отрицателно число тогава `s=0`. Максимумът от всички такива `s` щв бъде отговорът.

If the description is too vague, please see the code, it's short enough:
Ако описанието е твърде неясно, моля погледнете кода. Той е достатъчно кратък:

```js run demo
function getMaxSubSum(arr) {
let maxSum = 0;
let partialSum = 0;

for (let item of arr) { // for each item of arr
partialSum += item; // add it to partialSum
maxSum = Math.max(maxSum, partialSum); // remember the maximum
if (partialSum < 0) partialSum = 0; // zero if negative
for (let item of arr) { // за всеки елемент на масива
partialSum += item; // добавяме го към partialSum
maxSum = Math.max(maxSum, partialSum); // запомняме максимума
if (partialSum < 0) partialSum = 0; // нула ако е отрицателно
}

return maxSum;
Expand All @@ -89,6 +89,6 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6
alert( getMaxSubSum([-1, -2, -3]) ); // 0
```

The algorithm requires exactly 1 array pass, so the time complexity is O(n).
Алгоритъмът се нуждае точно от 1 обхождане на масива, така че сложността е 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)
```

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://en.wikipedia.org/wiki/Big_O_notation) или дори O(n) ако можете.
14 changes: 7 additions & 7 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,15 +2,15 @@ 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:

Expand Down
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` и показва масива в alert:

```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 плюс функцията.
4 changes: 2 additions & 2 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 Down
2 changes: 1 addition & 1 deletion 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` wняма да можем да различим празен стринг(знак стоп) от нула(валидно число). Вместо това, го правим по-късно.


```js run demo
Expand Down
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` и запазва стойностите в масив.
- Спира да иска числа след като потребителят въведе нещо, различно от число, празен стринг или натисне "Cancel".
- Пресмята и връща сумата на елементите в масива.

P.S. A zero `0` is a valid number, please don't stop the input on zero.
P.S. Нулата `0` е валидно число, моля не спирайте въвеждането на данни след нула.

[demo]
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy