Last active
October 21, 2017 10:29
-
-
Save Beraliv/a2b02fdc6e832bf969ea2dfa08d8dbac to your computer and use it in GitHub Desktop.
Get all number pairs which [[a, b], a * b = value], for a given value
This file contains hidden or 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
/** | |
* ES6 and featured code | |
*/ | |
let combineGetters = (...getters) => state => getters.reduce(({ payload }, getter) => ({ payload: getter(state, payload) }), { payload: state }); | |
let 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; | |
}; | |
let solve = arr => value => { | |
let {negative = [], mixed = [], zeroBased = [], positive = []} = combineGetters( | |
(state, payload) => payload.sort((a, b) => a - b), | |
(_, payload) => { | |
if (value > 0) { | |
return { | |
positive: findPairsInSorted(payload.filter(a => a > 0))(value), | |
negative: findPairsInSorted(payload.filter(a => a < 0))(value) | |
}; | |
} | |
if (value < 0) { | |
return { | |
mixed: findPairsInSorted([ | |
...payload.filter(a => a < 0).reverse(), | |
...payload.filter(a => a > 0) | |
])(value) | |
}; | |
} | |
return { | |
zeroBased: payload.filter(a => a !== 0).map(a => a < 0 ? [a, 0] : [0, a]) | |
}; | |
} | |
)(arr).payload; | |
return [...negative, ...mixed, ...zeroBased, ...positive]; | |
}; | |
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