Skip to content

Instantly share code, notes, and snippets.

@Beraliv
Last active October 21, 2017 10:29
Show Gist options
  • Save Beraliv/0b4002ea0bffc1a959555393b92a961d to your computer and use it in GitHub Desktop.
Save Beraliv/0b4002ea0bffc1a959555393b92a961d to your computer and use it in GitHub Desktop.
Get all number pairs which [[a, b], a * b = value], for a given value
/**
* mostly ES5 without featured code
* except for let and arrow functions which are better for reading and understanding
*
* FYI
* 1) a => a > 0 equals function (a) { return a > 0; } and is just a syntax sugar
* 2) let is used as an example of best practices
* 3) map is used to change the element to the result
* [-3, 1, 15].map(a => a < 0 ? [a, 0] : [0, a]) => [[-3, 0], [0, 1], [0, 15]]
* 4) filter is used to get only those elements which function is true for the condition
* [-3, 0, 15].filter(a => a > 0) => [15]
* 5) reverse is used to change the elements order to the opposite
* [1, 2, 3].reverse() => [3, 2, 1]
* 6) concat pushes the elements of both arrays to the resulted array
* [1, 2, 3].concat([4, 5, 6]) => [1, 2, 3, 4, 5, 6]
*
*/
function findPairsInSorted(arr, value) {
let results = [];
let len = arr ? arr.length : 0;
if (len < 1) {
return results;
}
for (let i = 0, j = len - 1; i < j;) {
if (value % arr[i] !== 0) {
i++;
}
else if (value / arr[i] < arr[j]) {
j--;
}
else if (value / arr[i] > arr[j]) {
i++;
}
else {
results.push([arr[i], arr[j]]);
i++;
j--;
}
}
return results;
}
function solve(arr, value) {
let sortedArr = arr.sort((a, b) => a - b);
if (value > 0) {
let positive = findPairsInSorted(sortedArr.filter(a => a > 0), value);
let negative = findPairsInSorted(sortedArr.filter(a => a < 0), value);
return negative.concat(positive);
}
if (value < 0) {
let all = sortedArr.filter(a => a < 0).reverse().concat(sortedArr.filter(a => a > 0));
return findPairsInSorted(all, value);
}
return sortedArr.filter(a => a !== 0).map(a => a < 0 ? [a, 0] : [0, a]);
}
solve([ 3, 4, 5, -2, 10, 11, 12, -1, 0, 7, 8 ], 10);
solve([ 10, 1, -1, -10, 0 ], -10);
solve([ 1, 18, 3, 6, 9, 2 ], 18);
solve([ 10, 1, -1, -10, 0 ], 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment