Skip to content

Commit 62baa39

Browse files
average pair find program added
1 parent 3d39634 commit 62baa39

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Multiple-Pointers/average-pair.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Write a function called averagePair. Given a sorted array of integers and a target average,
2+
// determine if there is a pair of values in the array where the average of the pair equals the target average.
3+
// There may be more than one pair that matches the average target.
4+
5+
function averagePair(inputSortedArray, pairAverage) {
6+
// validations
7+
if (!Array.isArray(inputSortedArray)) {
8+
return 'Input parameter should be array only'
9+
}
10+
const arrCounts = inputSortedArray.length
11+
let resultArr = []
12+
if (arrCounts > 0) {
13+
let leftIndex = 0, rightIndex = arrCounts - 1
14+
while (leftIndex < rightIndex) {
15+
// console.log(leftIndex, rightIndex)
16+
const leftIndexVal = inputSortedArray[leftIndex]
17+
const rightIndexVal = inputSortedArray[rightIndex]
18+
const sum = (leftIndexVal + rightIndexVal)/2
19+
if (sum === pairAverage) {
20+
resultArr.push(leftIndexVal, rightIndexVal)
21+
break
22+
} else if (sum < pairAverage) {
23+
leftIndex++
24+
} else {
25+
rightIndex--
26+
}
27+
}
28+
29+
}
30+
console.log('---------------------------------------------')
31+
return resultArr.length > 0 ? resultArr : undefined
32+
}
33+
34+
console.log(averagePair([1, 2, 3], 2.5)); // true
35+
console.log(averagePair([1, 3, 3, 5, 6, 7, 10, 12, 19], 8)); // true
36+
console.log(averagePair([-1, 0, 3, 4, 5, 6], 4.1)); // false
37+
console.log(averagePair([], 4)); // false

0 commit comments

Comments
 (0)