Skip to content

Commit 88f59b5

Browse files
committed
Create Array Addition I
1 parent 8996826 commit 88f59b5

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Array Addition I

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/***************************************************************************************
2+
* *
3+
* CODERBYTE BEGINNER CHALLENGE *
4+
* *
5+
* Array Addition I *
6+
* Using the JavaScript language, have the function ArrayAdditionI(arr) take the array *
7+
* of numbers stored in arr and return the string true if any combination of numbers *
8+
* in the array can be added up to equal the largest number in the array, otherwise *
9+
* return the string false. For example: if arr contains [4, 6, 23, 10, 1, 3] the *
10+
* output should return true because 4 + 6 + 10 + 3 = 23. The array will not be empty, *
11+
* will not contain all the same elements, and may contain negative numbers. * *
12+
* *
13+
* SOLUTION *
14+
* To get the largest number I am going to sort the array in ascending order which *
15+
* leaves the largest number at the end of the array. I can get largest number using *
16+
* pop() function. To get the total I am going to use two nested loops. The outer *
17+
* loop goes through every number in the array. The inner loop then adds all the other *
18+
* numbers in the array and then compares the total to the largest number. If a match *
19+
* is found then return true else return false. *
20+
* *
21+
* Steps for solution *
22+
* 1) Sort array in ascending order. *
23+
* 2) Remove largest number from array and store in largest *
24+
* 3) Loop through each number in array *
25+
* 4) Add every other number to this number and see if total matches largest *
26+
* 5) If match return True else return False
27+
* *
28+
***************************************************************************************/
29+
30+
function ArrayAdditionI(arr) {
31+
32+
arr.sort(function(a,b){return a - b})
33+
var largest = arr.pop();
34+
var sum = 0;
35+
for (var i = 0; i < arr.length; i++){
36+
sum += arr[i];
37+
for (var j = 0; j < arr.length; j++){
38+
if (i != j) {
39+
sum += arr[j];
40+
if (sum == largest) {
41+
return true;
42+
}
43+
}
44+
}
45+
for (var k = 0; k < arr.length; k++) {
46+
if (i != k) {
47+
sum -= arr[k];
48+
if (sum == largest) {
49+
return true;
50+
}
51+
}
52+
}
53+
sum = 0;
54+
}
55+
56+
return false;
57+
58+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy