I started playing around with coderbyte a place to test your programming skills. I was stumped for a bit on this question Array Addition I:

"Using the JavaScript language, have the function ArrayAdditionI(

Use the

But eventually hammered it out. I saw some people using multiple for loops as well as nested loops. I took a different approach and just did math with the exception of one for loop.

Here is my code example with assertions if you anyone is interested.

"Using the JavaScript language, have the function ArrayAdditionI(

**arr**) take the array of numbers stored in**arr**and return the string**true**if any combination of numbers in the array can be added up to equal the**largest number**in the array, otherwise return the string**false**. For example: if**arr**contains [4, 6, 23, 10, 1, 3] the output should return**true**because 4 + 6 + 10 + 3 = 23. The array will not be empty, will not contain all the same elements, and may contain negative numbers.Use the

**Parameter Testing**feature in the box below to test your code with different arguments."But eventually hammered it out. I saw some people using multiple for loops as well as nested loops. I took a different approach and just did math with the exception of one for loop.

Here is my code example with assertions if you anyone is interested.

var array_addition = function (arr) { // code goes here var sorted_arr = arr.sort(function(a, b) { return a - b; }), largest = sorted_arr.pop(), sum = 0, i; sorted_arr.forEach(function (number) { sum += number; }); //base condition is the total < largest if (sum < largest) { return false; } if ( largest === sum ) { //condition 1: everything in the array adds up to largest return true; } else if (sorted_arr.indexOf(Math.abs(largest - sum)) > 0) { //condition 2: largest - total gives you the difference in array return true; } else { //condition 3: traversal logic. Find any number in the array that adds up to the largest doing subtraction math for (i = 0; i < sorted_arr.length; i++) { return sorted_arr.indexOf(largest - sorted_arr[i]) > 0; } } return false; } var assert = function (actual, expected) { if (actual === expected) { console.log('assertion passed'); } else { console.log('assertion failed: expected: ' + expected + " actual: " + actual ); } } assert(true, array_addition([3,5,-1,8,12])); assert(true, array_addition([11,10,-2,1,1,1])); assert(false, array_addition([5,7,16,1,2])); assert(false, array_addition([10,9,16,7,2]));

## Comments

## Post a Comment