-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_triplet.js
59 lines (45 loc) · 1.59 KB
/
find_triplet.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
// Write a function that returns a triplet of numbers from the supplied array,
// with a sum equal to a specific integer.
const test = require('node:test');
const assert = require('node:assert');
const find_triplet = (array, sumToCheck) => {
array.sort((a,b) => a - b);
const arrayLength = array.length;
let left, right;
for (let index = 0; index < arrayLength - 2; index++) {
left = index + 1;
right = arrayLength - 1;
while (left < right) {
const value = array[index];
const leftValue = array[left];
const rightValue = array[right];
if (value + leftValue + rightValue === sumToCheck) {
return [value, leftValue, rightValue];
}
else if (value + leftValue + rightValue < sumToCheck)
left++;
else
right--;
}
}
// Not found.
return [];
}
test('Found passing test', (t) => {
const array = [4, 1, 9, 8, 5, 2, 3, 23, 50, 22, 19, 10];
const sum = 35;
const numbersMatched = find_triplet(array, sum);
assert.deepEqual(numbersMatched, [2, 10, 23]);
});
test('Alternative found passing test', (t) => {
const array = [4, 1, 9, 8, 5, 2, 3, 23, 50, 22, 19, 10];
const sum = 69;
const numbersMatched = find_triplet(array, sum);
assert.deepEqual(numbersMatched, [9, 10, 50]);
});
test('Not found passing test', (t) => {
const array = [4, 1, 9, 8, 5, 2, 3, 23, 50, 22, 20];
const sum = 999;
const numbersMatched = find_triplet(array, sum);
assert.deepEqual(numbersMatched, []);
});