(Solution) Find Closet to Zero
by Sanjay Yadav
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/1.3.1/jasmine.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/1.3.1/jasmine.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/1.3.1/jasmine-html.js"></script>
<title>Jasmine Spec Runner</title>
JavaScript
//Using TDD, write a function that will find the number closest to zero from a list of integers.
/* possible runtime of O(n2) */
function closetToZero_bubblesort(array) {
for (i = 0; i < array.length; i++) {
for (j = i + 1; j < array.length; j++) {
if (
(Math.abs(array[j]) < Math.abs(array[i])) ||
// handle the situation when there are negative and positive number with same value. bubble the positive number to top.
(Math.abs(array[j]) == Math.abs(array[i]) && (array[j] > array[i]))
) {
var swap_temp = array[i]
array[i] = array[j]
array[j] = swap_temp
}
}
}
return array[0]
}
/* runtime of O(n) */
function closetToZero(array) {
var closetToZero = array[0];
for (i = 1; i < array.length; i++) {
if (
(Math.abs(array[i]) < Math.abs(closetToZero)) ||
// handle the situation when there are negative and positive number with same value. choose the positive number
(Math.abs(array[i]) == Math.abs(closetToZero) && (array[i] > closetToZero))
) {
closetToZero = array[i]
}
}
return closetToZero
}
describe('Closest to zero exercise', function() {
it('should find number closet to zero in an array with positive numbers', function() {
expect(closetToZero([1, 5, 9, 2])).toBe(1);
});
it('should find number closet to zero in an array with 1 element', function() {
expect(closetToZero([1])).toBe(1);
});
it('should find number closet to zero in an array with negative numbers', function() {
expect(closetToZero([-1, -10, -9, -3])).toBe(-1);
});
it('should find number closet to zero in an array with positive numbers, negative numbers, zero and duplicate numbers', function() {
expect(closetToZero([-10, -9, -3, 5, 9, 2, -15, -2])).toBe(2);
});
});
// load jasmine htmlReporter
$(function() {
var env = jasmine.getEnv();
env.addReporter(new jasmine.HtmlReporter());
env.execute();
});