2023-05-01 16:16:48 +10:00
|
|
|
/**
|
|
|
|
|
* @author mrmagic2020
|
|
|
|
|
* @description The function will find the parity outlier from an array of integers.
|
|
|
|
|
* @see https://en.wikipedia.org/wiki/Parity_(mathematics)
|
|
|
|
|
* @param {number[]} integers - An array of integers.
|
|
|
|
|
* @returns {number} - The parity outlier.
|
|
|
|
|
* @example parityOutlier([1, 3, 5, 8, 9]) = 8
|
|
|
|
|
*/
|
|
|
|
|
const parityOutlier = (integers) => {
|
|
|
|
|
let oddsCount = 0 // define counter for odd number(s)
|
|
|
|
|
let evensCount = 0 // define counter for even number(s)
|
|
|
|
|
let odd, even
|
|
|
|
|
|
|
|
|
|
for (const e of integers) {
|
2023-10-03 23:08:19 +02:00
|
|
|
if (!Number.isInteger(e)) {
|
|
|
|
|
// detect non-integer elements
|
2023-05-01 16:16:48 +10:00
|
|
|
return null
|
|
|
|
|
}
|
2023-10-03 23:08:19 +02:00
|
|
|
if (e % 2 === 0) {
|
|
|
|
|
// an even number
|
2023-05-01 16:16:48 +10:00
|
|
|
even = e
|
|
|
|
|
evensCount++
|
2023-10-03 23:08:19 +02:00
|
|
|
} else {
|
|
|
|
|
// an odd number
|
2023-05-01 16:16:48 +10:00
|
|
|
odd = e
|
|
|
|
|
oddsCount++
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (oddsCount === 0 || evensCount === 0) return null // array has only odd/even number(s)
|
|
|
|
|
if (oddsCount > 1 && evensCount > 1) return null // array has more than one even and odd number
|
|
|
|
|
|
|
|
|
|
return oddsCount === 1 ? odd : even
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export { parityOutlier }
|