-
Notifications
You must be signed in to change notification settings - Fork 0
/
splitArrayManyOccurences.js
59 lines (43 loc) · 1.48 KB
/
splitArrayManyOccurences.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
//Task 1 Your function takes an array of integers (arr), and an integer (x).
//You need to find the position in arr that splits the array in two, where one side has as many occurrences of x as the other side
//has occurrences of any number but x
//So, given an array like this: [5, 5, 2, 3, 5, 1, 6] and x being "5", the function should return "4" (Position 4, holding
//the number "3" above is the point where you have 2 5's on the one side, and two "not fives" on the other.
function solution(X, A) {
var numberOfX = A.filter(function(value) {
return value === X
}).length
var count = 0
for (i = 0; i < A.length; i ++) {
var secondHalfLength = A.length - (i + 1)
var missingXs = numberOfX - count
if (count === (secondHalfLength - missingXs)) return i
if (A[i] === X) count++
}
return -1
}
console.log(solution(5, [5, 5, 2, 3, 5, 1, 6]))
console.log(solution(4, [4, 4, 2, 3, 5, 1, 6, 4, 1, 3]))
console.log(solution(3, [3,3,1,3,2,1]))
//second version
function solution(X, A) {
const totalX = A.filter(function(value) {
return value === X ? true : false
}).length
if (A.length < 3) return -1
let count = 0
for (i = 0; i < A.length; i++) {
let pivotX = A[i] === X ? 1 : 0
let leftX = totalX - count - pivotX
let leftSideLength = A.length - i - 1
if (count > 0) {
if (count === (leftSideLength - leftX)) {
return i
}
}
if (A[i] === X) {
count++
}
}
return -1
}