Dec 22, 2017

Write JavaScript code that accepts an array of integer and output the sum of two largest integers from array. But the sum of those two largest integers should be even number.

Write JavaScript code that accepts an array of integer and output the sum of two largest integers from the array. But the sum of those two largest integers should be even number.

Example:

#1
var int_array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// should output 7+9 = 16

#2
var int_array = [9, 5, 3, 2, 8, 14, 5, 7, 3, 11, 12]

// should output 12+14 = 26

Following is the solution to the above interview question.

 

//var int_array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
 var int_array = [9, 5, 3, 2, 8, 14, 5, 7, 3, 11, 12];
 var first_max_number = Math.max.apply(null, int_array); //Find first max number
 
 var index = int_array.indexOf(first_max_number);
 if (index > -1) { //Once get max number pop from array
  int_array.splice(index, 1);
 }
 
 var second_max_number =0;
 for (i=0; i < int_array.length; i++){ //for second max number 
   second_max_number = Math.max.apply(null, int_array); //find second max number
  if(isEven(first_max_number) && isEven(second_max_number)){ // check both number should be event or odd
   break; //Once condition get satisfy, break the look 
  }else if(isOdd(first_max_number) && isOdd(second_max_number)){
   break;
  }
 
  index = int_array.indexOf(second_max_number);
  if (index > -1) { //pop second max number from the array
   int_array.splice(index, 1);
  }
 }
 var sum = first_max_number + second_max_number;
 alert(first_max_number +" + "+ second_max_number +" = "+ sum);
 
 function isEven(n) { //check event number
  return n % 2 == 0;
 }

 function isOdd(n) { // check odd number
    return Math.abs(n % 2) == 1;
 }

Hope it will help you to in the future.

No comments:

Post a Comment