Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Array Addition test cases
    For some reason my code isn't passing the test and I'm pretty sure it's correct. One of the test cases was [1,2,3,4] so the maximum is 4 and the sum of the others is 1+2+3=6. Clearly 4 != 6 and my code produces false. Anyone else experiencing this?
    function ArrayAdditionI(arr) { 
    
      // code goes here  
      var max = Math.max.apply(Math, arr),
          sum = 0;
    
      for (i = arr.length - 1; i >= 0; i -= 1) {
        if (arr[i] != max) {
          sum += arr[i];
        }
      }
      return (sum === max); 
    }
    
    aarongchou posted this question on 1/12/14 | javascript, array, addition
    Answers
  • +
  • 3
  • -
  • The challenge description says you should return
    true
    if any combination of numbers in the array can be added up to equal the largest number. In this case (1,2,3) you can add 1 + 3 to equal 4, so the result is
    true
    Tip: look into array permutations :)
  • +
  • 0
  • -
  • Ah, I misread the question. I thought it said the sum of all remaining numbers, not a combination. Thanks @Grillparzer!
    Log in to write an answer.