Friday, November 18, 2016

Write a method get sum of two element which closest to Zero

Here is the code in Javascript:



/*
 * Please implement this method to return the sum of the two elements closest to zere. If there are two elements equally close to zero like -2 and 2.
 * consider the positive element to be "closer" to zero than the negative one.
 * 
 *
 */

function sumOfTwoElementsClosestToZero(arr) {
    var length = arr.length;
    var first = arr[0];
    var second = arr[0];

    for (var i = 0; i < length; i++) {
        if (arr[i] == 0) {
            continue;
        }
        if (abs(first) > abs(arr[i]) || (abs(first) == abs(arr[i]) && arr[i] > 0)) {
            first = arr[i];
        }
    }

    for (var i = 0; i < length; i++) {
        if (arr[i] == 0) {
            continue;
        }
        if (abs(arr[i]) > abs(first) && (abs(second) > abs(arr[i]) || abs(second) == abs(arr[i]) && arr[i] > 0)) {
            second = arr[i];
        }
    }

    return (second + first);
}

function abs(num) {
    return num < 0 ? -num : num;
}


console.log("test 1 : " + (sumOfTwoElementsClosestToZero([7, 8, 3, 4, 2, 8, -3, 4, -2, -100]) == 5));
console.log("test 2 : " + (sumOfTwoElementsClosestToZero([7, 8, -3, 4, 2, 8, -3, 4, -2, -100]) == -1));
console.log("test 3 : " + (sumOfTwoElementsClosestToZero([7, 8, 3, 4, -1, 8, -3, 4, -2, -100]) == -3));
console.log("test 4 : " + (sumOfTwoElementsClosestToZero([7, 8, 3, 4, 2, 8, -3, 4, -2, -100]) == 5));
console.log("test 5 : " + (sumOfTwoElementsClosestToZero([-3, -2, -1, 1, 0, 2]) == 3));