Skip to content

Instantly share code, notes, and snippets.

@Tatsh
Last active July 28, 2018 13:43
Show Gist options
  • Save Tatsh/e93ae0a674a5747f830916e0d1e196fc to your computer and use it in GitHub Desktop.
Save Tatsh/e93ae0a674a5747f830916e0d1e196fc to your computer and use it in GitHub Desktop.
Demo test question on Codility.
const sorted = (a) => Array.prototype.sort.call(a, (a, b) => a - b);
const tail = (n, a) => Array.prototype.slice.call(a, n);
const abs = Math.abs;
const solution = (a) => {
const sa = sorted(a);
let last = abs(a[0]);
for (const x of tail(1, sa)) {
const negative = x < 0;
const ax = abs(x);
if (ax === 0 || last === ax) {
continue;
}
if (abs(ax - last) > 1) {
if (negative) {
return last - 1;
} else {
return last + 1;
}
}
last = ax;
}
};
console.log(solution([1, 3, 7, 4, 1, 2]) === 5);
console.log(solution([-1, -3]) === 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment