Created
September 14, 2022 11:52
-
-
Save polaroidkidd/5b4aa3ad938272678b3b00e9186abf8e to your computer and use it in GitHub Desktop.
Codility Demo JavaScript
This file contains 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
'use strict'; | |
// you can write to stdout for debugging purposes, e.g. | |
// console.log('this is a debug message'); | |
/** | |
* | |
* @param {number[]} A | |
* @returns {number} | |
*/ | |
function solution(A) { | |
// get rid of negatives | |
const sorted = A.sort().filter((v) => v > 0); | |
// return early if array consisted only of negatives | |
if (sorted.length === 0) { | |
return 1; | |
} | |
// handle edge case where array has length 1 | |
if (sorted.length === 1) { | |
return sorted[0] > 1 ? 1 : 2; | |
} | |
let smallest = NaN | |
for (let i = sorted.length - 1; i >= 1; i--) { | |
if(sorted.length === 2){ | |
if(sorted[i] - sorted[i-1] <=1){ | |
smallest = sorted[i] +1 | |
} | |
if(sorted[i-1] > 1){ | |
smallest = 1; | |
} | |
} | |
if(sorted[i] - sorted[i-1] > 1){ | |
smallest = sorted[i-1] +1 | |
} | |
} | |
if(isNaN(smallest)){ | |
smallest = sorted[sorted.length -1] +1; | |
} | |
return smallest; | |
} | |
const a = [1, 2, 4, 6, 3]; // expected 5 | |
const b = [-1, -3, 1]; // expected 2 | |
const c = [-1, -3, 1, 2]; // expected 3 | |
const d = [-1, -3, 1, 3]; // expected 2 | |
const e = [-1, -3, 1, 2, 3, 5]; // expected 4 | |
const f = [-1, -3, -21]; // expected 1 | |
const g = [-1, -3, 3, 4]; // expected 1 | |
const passes = [ | |
solution(a), // === 5 ? true : 'failed a', | |
solution(b), // === 2 ? true : 'failed b', | |
solution(c), // === 3 ? true : 'failed c', | |
solution(d), // === 2 ? true : 'failed d', | |
solution(e), // === 4 ? true : 'failed e', | |
solution(f), // === 1 ? true : 'failed f', | |
solution(g), // === 1 ? true : 'failed f', | |
]; | |
const expected = [ | |
5, | |
2, | |
3, | |
2, | |
4, | |
1, | |
1 | |
] | |
console.info("passes: ", passes) | |
console.info("expecd: ", expected) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment