Created
April 4, 2018 16:08
-
-
Save HERRKIN/419ce12452bba26d52574da9d9563cc7 to your computer and use it in GitHub Desktop.
Test code file for Luminux, should be run with babel-node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const binarySearch = (items, x) => { | |
let low = 0 | |
let high = items.length - 1 | |
while (low <= high) { | |
const mid = parseInt((low + high) / 2, 10) | |
const current = items[mid] | |
if (current > x) { | |
high = mid - 1 | |
} else if (current < x) { | |
low = mid + 1 | |
} else { | |
return current === x ? current : null | |
} | |
} | |
return null | |
} | |
const quickSort = array => { | |
if(array.length < 2) { | |
return array; | |
} | |
let pivot = array[0]; | |
let lesser = []; | |
let greater = []; | |
for(let i = 1; i < array.length; i++) { | |
if(array[i] < pivot) { | |
lesser.push(array[i]); | |
} else { | |
greater.push(array[i]); | |
} | |
} | |
return [...quickSort(lesser),pivot, ...quickSort(greater)] | |
} | |
const findSumPairs = (array, x) => { | |
const sorted = quickSort(array) | |
const results = sorted.reduce((prev, current) => { | |
const searchElement = Math.abs(current - x) | |
if(prev.filter(a => | |
(a[0] === current && a[1] === searchElement) || (a[1] === current && a[0] === searchElement) | |
).length ){ | |
return prev | |
} | |
if(binarySearch(sorted, searchElement)){ | |
return [...prev, [current, searchElement]] | |
} | |
return prev | |
},[]) | |
return results | |
} | |
console.log('EJEMPLO 1 array A = [1,2,3,4], X=10') | |
console.log('Answer: ', findSumPairs([1,2,3,4], 10)) | |
console.log('EJEMPLO 2 array A = [10,2,3,1], X=5') | |
console.log(findSumPairs([10,2,3,1], 5)) | |
console.log('EJEMPLO 3 array A = [4, 3, 1, 2, 5, 6], X=5') | |
console.log(findSumPairs([4, 3, 1, 2, 5, 6], 5)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment