-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbiggest-numbers-mult.js
85 lines (67 loc) · 2.57 KB
/
biggest-numbers-mult.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
function getBiggestNumbersMult(list){
list = list.split(' ').map(num =>
Number(num));
if(list.length === 2){
return list[0] > list[1] ?
`${list[1]} ${list[0]}` :
`${list[0]} ${list[1]}`;
}
// Считаю количество минусовых чисел
let negative = [];
let negativePos = [];
let notNegative = false;
for(let i = 0; i < list.length; i++){
if(list[i] < 0){
negative.push(list[i]);
negativePos.push(i);
}
}
// Если негативное только одно, тогда убираю из массива.
if(negative.length === 1){
list.splice(negativePos[0], 1);
notNegative = true;
}
/* Ищу наибольшие значения или наименьшие среди минусовых.
В sign приходит false если работаю с минусовыми и
true для плюсовых */
const getBigger = (nums, sign) => {
let bigger = nums[0];
biggerPos = 0;
for(let i = 1; i < nums.length; i++){
const current = nums[i];
if( (!sign && current < bigger) ||
(sign && current > bigger) ){
bigger = current;
biggerPos = i;
}
}
return biggerPos;
}
const firstNegativePos = notNegative ? null :
getBigger(negative, false);
const firstPositivePos = getBigger(list, true);
const firstNegative = negative[firstNegativePos];
const firstPositive = list[firstPositivePos];
// Удаляю наибольшие значения чтобы не мешались
negative.splice(firstNegativePos, 1);
list.splice(firstPositivePos, 1);
const secondNegativePos = notNegative ? null :
getBigger(negative, false);
const secondPositivePos = getBigger(list, true);
const secondNegative = negative[secondNegativePos];
const secondPositive = list[secondPositivePos];
const negativeMult = firstNegative * secondNegative;
const positiveMult = firstPositive * secondPositive;
const getResult = (first, second) => {
return first > second ?
`${second} ${first}` :
`${first} ${second}`;
}
let result;
if(negativeMult > positiveMult)
result = getResult(firstNegative, secondNegative);
else
result = getResult(firstPositive, secondPositive);
return result;
}
getBiggestNumbersMult('-4 3 -5 2 5');