Skip to content

Instantly share code, notes, and snippets.

@clsource
Last active August 16, 2020 00:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clsource/0c1dc215450dc13cb766701867a95044 to your computer and use it in GitHub Desktop.
Save clsource/0c1dc215450dc13cb766701867a95044 to your computer and use it in GitHub Desktop.
Find the Outlier

Encuentra el 'outlier' de paridad

Dado un arreglo de enteros (con un mínimo de 3 elementos, pero puede ser bien grande), el cual está compuesto en su totalidad por números pares o impares, excepto por un elemento (el outlier), escriba un método que encuentre ese outlier.

Esta función debe ser implementada en JavaScript y no se pueden utilizar librerias externas. Completa la función en el archivo pregunta1.js.

Ejemplos:

[2, 4, 0, 100, 4, 11, 2602, 36]
Debería retornar: 11 (el único elemento impar)

[160, 3, 1719, 19, 11, 13, -21]
Debería retornar: 160 (el único elemento par)
(() => {
/**
*
* @param {number[]} elements
*/
const findOutlier = (elements) => {
// First check the first three elements
if(elements.length < 3) {
return false;
}
const isEven = (num) => {
return num % 2 === 0
}
const isListEven = () => {
const first = isEven(elements[0]) ? 1 : 0;
const second = isEven(elements[1]) ? 1 : 0;
const third = isEven(elements[2]) ? 1 : 0;
// Check which type quantity is majority
// even (1) + even (1) + even (1) = even (x3) > odd (x0) = even
// even (1) + odd (0) + even (1) = even (x2) > odd (x1) = even
// even (1) + odd (0) + odd (0) = even(z1) < odd(x2) = odd
// odd (0) + odd (0) + odd (0) = even(x0) < odd(x3) = odd
// if quantity of even is more than the quantity of odds
// then the list is even as majority
return (first + second + third) > 1;
};
const listTypeEven = isListEven(elements);
for(let i = 0; i < elements.length; i++) {
// If the element is even and the list is even = ok
// or If the element is odd and the list is odd = ok
// If they are not the same type then we found our outlier
if(!(isEven(elements[i]) && listTypeEven)) {
return elements[i];
break;
}
}
};
const test1 = [2, 4, 0, 100, 4, 11, 2602, 36];
const test2 = [160, 3, 1719, 19, 11, 13, -21];
console.assert(findOutlier(test1) == 11);
console.assert(findOutlier(test2) == 160);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment