-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclosestPair.js
More file actions
39 lines (34 loc) · 987 Bytes
/
closestPair.js
File metadata and controls
39 lines (34 loc) · 987 Bytes
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
function closestSumPair(arr1, arr2, target) {
var arr1Sorted = arr1.sort((a, b) => a - b);
var arr2Sorted = arr2.sort((a, b) => a - b);
i = 0;
j = arr2Sorted.length - 1;
var smallestDiff = Number(Math.abs(arr1Sorted[0] + arr2Sorted[0] - target));
var closestPair = (arr1Sorted[0], arr2Sorted[0]);
while (i < arr1Sorted.length && j >= 0) {
var v1 = arr1Sorted[i];
var v2 = arr2Sorted[j];
var currentDiff = v1 + v2 - target;
if (Number(Math.abs(currentDiff)) < smallestDiff) {
smallestDiff = Number(Math.abs(currentDiff));
closestPair = (v1, v2);
}
if (currentDiff == 0) {
return closestPair;
} else if (currentDiff < 0) {
i += 1;
} else {
j -= 1;
}
console.log(v1, v2);
}
return closestPair;
}
arr = [-1, 3, 8, 2, 9, 5];
function numOfIds(pool) {
let totalCount = 0;
for (let i = 0; i < pool.length; i = i + 8) {
if (pool.substring(i, 7) == '8') totalCount++;
}
return totalCount;
}