-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.union.two.js
More file actions
90 lines (76 loc) · 1.85 KB
/
array.union.two.js
File metadata and controls
90 lines (76 loc) · 1.85 KB
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
86
87
88
89
90
/*
* @title: Union Array
* @description: find union of two arrays - sorted
* @author: Thorsten Kober
* @email: [email protected]
*/
function binarySearch(arr, n) {
let start = 0;
let end = arr.length - 1;
let middle;
while (start <= end) {
middle = Math.floor((start + end) / 2);
if (arr[middle] === n) {
return middle;
}
if (arr[middle] > n) {
end = middle - 1;
} else {
start = middle + 1;
}
}
return -1;
}
function findUnion(one, two) {
const oneLength = one.length;
const twoLength = two.length;
let short;
let long;
if (oneLength <= twoLength) {
short = one.slice(0);
long = two.slice(0);
} else {
short = two.slice(0);
long = one.slice(0);
}
short.sort((a, b) => a - b).slice(0);
const union = short.slice(0);
for (let i = 0; i < long.length; i++) {
if (binarySearch(short, long[i]) === -1) {
union.push(long[i]);
}
}
return union.sort((a, b) => a - b);
}
function findIntersection(one, two) {
const oneLength = one.length;
const twoLength = two.length;
const intersection = [];
let short;
let long;
if (oneLength <= twoLength) {
short = one.slice(0);
long = two.slice(0);
} else {
short = two.slice(0);
long = one.slice(0);
}
short.sort((a, b) => a - b).slice(0);
for (let i = 0; i < long.length; i++) {
if (binarySearch(short, long[i]) !== -1) {
intersection.push(long[i]);
}
}
return intersection.sort((a, b) => a - b);
}
// npx jest algorithms/array/array.union.two.js
test('findUnion()', () => {
const one = [7, 1, 5, 2, 3, 6];
const two = [3, 8, 6, 20, 7];
expect(findUnion(one, two)).toEqual([1, 2, 3, 5, 6, 7, 8, 20]);
});
test('findIntersection()', () => {
const one = [7, 1, 5, 2, 3, 6];
const two = [3, 8, 6, 20, 7];
expect(findIntersection(one, two)).toEqual([3, 6, 7]);
});