I have an issue with getting the sum of two arrays and combining their averages while rounding off.
I don't want to hardcode but rather pass two random arrays. so here is the code but it keeps returning NaN
function sumAverage(arr) {
var result = 0;
// Your code here
// set an array
arr = [];
a = [];
b = [];
arr[0] = a;
arr[1] = b;
var sum = 0;
// compute sum of elements in the array
for (var j = 0; j < a.length; j++) {
sum += a[j];
}
// get the average of elements in the array
var total = 0;
total += sum / a.length;
var add = 0;
for (var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math += add / b.length;
result += math + total;
Math.round(result);
return result;
}
console.log(sumAverage([
[2, 3, 4, 5],
[6, 7, 8, 9]
]));
If you wanted to do it a bit more functionally, you could do something like this:
function sumAverage(arrays) {
const average = arrays.reduce((acc, arr) => {
const total = arr.reduce((total, num) => total += num, 0);
return acc += total / arr.length;
}, 0);
return Math.round(average);
}
console.log('sum average:', sumAverage([[1,2,3], [4,5,6]]));
Just try this method..this kind of issues sometimes occured for me.
For example
var total = 0;
total = total + sum / a.length;
And every concat use this method..
Because you are assigning the value [] with the same name as the argument? This works, see jFiddle
function sumAverage(arr) {
var result = 0;
//arr = [];
//a = [];
//b = [];
a = arr[0];
b = arr[1];
var sum = 0;
// compute sum of elements in the array
for(var j = 0; j < a.length; j++ ){
sum += a[j] ;
}
// get the average of elements in the array
var total = 0;
total += sum / a.length;
var add = 0;
for(var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math += add / b.length;
result += math + total;
Math.round(result);
return result;
}
document.write(sumAverage([[2,3,4,5], [6,7,8,9]]));
As said in comments, you reset your arguments...
Use the variable "arguments" for dynamic function parameters.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
I suggest to use two nested loops, one for the outer array and one for the inner arrays. Then sum values, calculate the average and add averages.
function sumAverage(array) {
var result = 0,
sum,
i, j;
for (i = 0; i < array.length; i++) {
sum = 0;
for (j = 0; j < array[i].length; j++) {
sum += array[i][j];
}
result += Math.round(sum / array[i].length);
}
return result;
}
console.log(sumAverage([[2, 3, 4, 5], [6, 7, 8, 9]])); // 12
The problem is that you are emptying arr by saying arr = [].
Later, you are iterating over a which is empty too.
Again when you say total += sum / a.length;, sum is 0 and a.length is 0 so 0/0 becomes NaN. Similarly for math. Adding Nan to NaN is again NaN and that's what you get.
Solution is to not empty passed arr and modify your code like below:
function sumAverage(arr) {
var result = 0;
// Your code here
// set an array
//arr = [];
//a = [];
//b = [];
a = arr[0];
b = arr[1];
var sum = 0;
// compute sum of elements in the array
for (var j = 0; j < a.length; j++) {
sum += a[j];
}
// get the average of elements in the array
var total = 0;
total = sum / a.length;
var add = 0;
for (var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math = add / b.length;
result = math + total;
result = Math.round(result);
return result;
}
console.log(sumAverage([
[2, 3, 4, 5],
[6, 7, 8, 9]
]));
Basically I see a mistake here:
arr[0] = a; arr[1] = b;
That should be
a= arr[0]; b= arr[1];
and then remove:
arr = [];
I suggest you write your function like this:
function sum(arr) {
var arr1 = arr[0]
var sum1 = 0;
arr1.map(function(e){sum1+=e});
var arr2 = arr[1]
var sum2 = 0;
arr2.map(function(e){sum2+=e});
return Math.round(sum1/arr1.length + sum2/arr2.length);
}
Related
I'm trying to find the number of adjacent element trios with a given sum.
Example:
Inputs arr = [1,2,3,12,1,4,9,6] sum = 6
Output = 2
([1,2,3,12,1,4,1,6])
My Code:
function getCount(arr, sum) {
var count = 0;
var indexes = [];
for (var i = 0; i < arr.length-2; i++) {
for (var j = i + 1; j < arr.length-1; j++) {
for (var k = j + 1; k < arr.length; k++){
if ((arr[i] + arr[j] + arr[k] == sum) && indexes.includes(i) && indexes.includes(j)) {
count++;
}
}
}
}
return count;
}
getCount([1,2,3,12,3,4,9,6],19);
But this is not work for adjacent elements.
I would just use a single loop/pass here:
function getCount(arr, sum) {
if (arr.length < 3) return 0;
var count = 0;
var first = arr[0];
var second = arr[1];
var third;
for (var i=2; i < arr.length; i++) {
third = arr[i];
var currSum = first + second + third;
if (currSum == sum) ++count;
first = second;
second = third;
}
return count;
}
console.log(getCount([], 3));
console.log(getCount([1, 2], 3));
console.log(getCount([1, 2, 3], 3));
console.log(getCount([1, 2, 3], 6));
console.log(getCount([1,2,3,12,3,4,9,6], 19));
The strategy here is to just walk down the input array once, keeping track of the current, previous, and previous previous values at each step. Then, we compute the sum of those three values, and compare against the input target sum.
I'm working on the 'Two Sum' problem in Leetcode.
I'm sure this code is correct, I've tested it in Repl and it looks correct there, but Leetcode is giving me an error.
Here's my code:
var arr = [];
var twoSum = function(nums, target) {
for(var i = 0; i < nums.length; i++){
for(var j = i+1; j < nums.length; j++){
console.log(nums[i] + ', ' + nums[j]);
var tot = nums[i] + nums[j];
if(tot === target){
arr.push(i,j);
console.log(arr);
return arr;
}
}
}
};
//var a = [2, 7, 11, 15];
//var b = 9;
var a = [2, 3, 4];
var b = 6;
twoSum(a, b);
The error I'm getting is as follows:
Input:
[3,2,4]
6
Output:
[0,1,1,2]
Expected:
[1,2]
Why is it expecting [1, 2]? Surely it should expect [0, 1] in this case, and then why is my code adding to the arr array twice? It looks like a bug to me...
Note: I see there's many posts about this problem on Leetcode, but none address the specific issue I have run into in Javascript.
Why is it expecting [1, 2]?
Because 2 + 4 = 6
Surely it should expect [0, 1] in this case
No, because 3 + 2 = 5
and then why is my code adding to the arr array twice?
Because you declared the array outside of the function. It is being re-used for every call to the function. Move the array declaration into your twoSum function or even better: Simply return [i, j] instead of pushing into the empty array.
Here is another solution you can try...
var twoSum = function(nums, target) {
let map = {};
for (let i = 0; i < nums.length; i++) {
let compliment = target - nums[i];
if (map[compliment]) {
return [(map[compliment] - 1), i];
} else {
map[nums[i]] = i + 1;
}
}
};
twoSum([2, 3, 4],6);
Click Here to RUN
Here is an optimum solution
/**
* #param {number[]} nums
* #param {number} target
* #return {number[]}
*/
function twoSum(nums, target) {
const numsObjs = {}; // create nums obj with value as key and index as value eg: [2,7,11,15] => {2: 0, 7: 1, 11: 2, 15: 3}
for (let i = 0; i < nums.length; i++) {
const currentValue = nums[i];
if (target - currentValue in numsObjs) {
return [i, numsObjs[target - currentValue]];
}
numsObjs[nums[i]] = i;
}
return [-1, -1];
}
console.log(twoSum([2, 7, 11, 15], 9))
This is my solution, which is a brute force method that uses javascript to search for all possible pairs of numbers.
var twoSum = function(nums, target) {
let numarray = new Array(2);
for (var i = 0; i < nums.length; i++) {
for (var j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
numarray[0] = i;
numarray[1] = j;
}
}
}
return numarray;
};
EDITED:
Can someone help me with the problem below further. I have a class and an array inside the class. I want now use a for loop to sum the length of the previous array length, but for each iteration. If i == 1 I want sum the length of arr[0].x.length, If i == 2 I want sum the length of arr[0].x.length+arr[1].x.length, ect. It will be a lot of code to check each iteration.
Is there a simple way to do this? Instead allways use a new line like
if (i == 1) n = n + arr[i-1].x.length;
if (i == 2) n = n + arr[i-1].x.length+arr[i-2].x.length;
if (i == 3) n = n + arr[i-1].x.length+arr[i-2].x.length+arr[i-3].x.length;
function Class() {
var x = [];
}
for (var i = 0; i < 9; i++) {
arr[i] = new Class();
}
I add 4 items to each object.
arr[0].x.push(...)
arr[0].x.push(...)
...
arr[1].x.push(...)
arr[1].x.push(...)
...
var n = 0;
for (var i = 0; i < arr.length; i++) {
if (i == 1) {
n = n + arr[i-1].x.length;
} else if (i == 2) {
n = n + arr[i-1].x.length+arr[i-2].x.length;
} else if (i == 3) {
n = n + arr[i-1].x.length+arr[i-2].x.length+arr[i-3].x.length;
}
// ect.
}
You could use reduce to get a total of all the lengths of your sub-arrays. For example:
const arrs = [[1, 2, 3], [4, 5, 6]];
const sum = arrs.reduce((acc, arr) => acc += arr.length, 0);
console.log(sum);
// 6
Just nest the loop two times: go over the indexes once then go up to that index from 0 in an inner loop:
for (var i = 0; i < arr1.length; i++) {
for(var j = 0; j <= i; j++) {
n = n + arr1[j].length;
}
}
Edit: benvc's answer is what you are looking for if you want to use reduce.
var arr = [[1,2,3], [4,5,6], [7]];
var n = 0;
for (var i = 0; i < arr.length; i++){
n += arr[i].length;
}
console.log(n);
I'm trying to create a function that will add the numbers in an array and return their sum. For some reason it's returning 1 instead of 15 and I'm not sure why.
var myArray = [1,2,3,4,5];
function addThemUp(myArray) {
var arrayTotal = myArray.length;
var totalSum = 0;
for(var x = 0; x <arrayTotal; x++) {
totalSum += myArray[x];
return(totalSum)
}
}
addThemUp(myArray)
You placed the return statement inside the loop, so it will sum the first element only and then return. Instead, you should allow the loop to complete, and return the sum only after its done:
function addThemUp (myArray) {
var arrayTotal = myArray.length;
var totalSum = 0;
for(var x = 0; x < arrayTotal; x++){
totalSum += myArray[x];
}
return(totalSum); // This is where the return should be
}
In your case, you need to fix where the return of totalSum is, to be the last statement of your function (after the loop).
That being said, you may find that adding up all the numbers in an array is much cleaner and simpler to do with reduce:
function addThemUp(myArray) {
return myArray.reduce(function(a, b) { return a + b; });
}
var myArray = [1, 2, 3, 4, 5];
console.log(addThemUp(myArray));
You should return sum after for loop
var myArray = [1, 2, 3, 4, 5];
function addThemUp(myArray) {
var arrayTotal = myArray.length;
var totalSum = 0;
for (var x = 0; x < arrayTotal; x++) {
totalSum += myArray[x];
}
return totalSum;
}
console.log("Sum of all elements: " + addThemUp(myArray));
This question already has answers here:
How to find the sum of an array of numbers
(59 answers)
Closed 6 years ago.
How can I turn this into a function that takes an array of any length and gives you the total?
var points = new Array(100);
for (var i = 0; i < 100; i++) {
points[i] = i + 1;
}
for(var i = 0; i < points.length; i++) {
console.log(points[i]);
}
You could do it in two loops, but you might as well just do one loop that does both tasks.
var array = [],
sum = 0;
for (var i = 1; i <= 10000; i++) {
array[i-1] = i;
sum += i;
}
If you want to generalize the task of finding the sum of an array, you can use a function like so:
function arraySum(array) {
var sum = 0;
for (var i = 0; i < array.length; i++)
sum += array[i];
return sum;
}
For those who can understand it though, using reduce is a best answer:
function arraySum(array) {
return array.reduce(function(a,b){return a+b}, 0);
}
You can do get the sum using the for loop itself simply by using a variable
var points = new Array(100),
sum = 0;
for (var i = 0; i < 100; i++) {
points[i] = i + 1;
}
for (var i = 0; i < points.length; i++) {
sum += points[i];
}
console.log(sum);
You can reduce these two operations using fill() and forEach() to generate the array and reduce() to get the sum
var points = new Array(10000); // create an array of size 10000
points.fill(1); // fill it with 1 which helps ti=o iterate using foreach
points.forEach(function(v, i) { // iterate the array, you can also use simple for loop here
points[i] = v + i; // update the value
});
var sum = points.reduce(function(a, b) { // find sum
return a + b;
});
console.log(sum);
Using for loop and reduce()
var points = []; // initialize an array
for (var i = 1; i <= 10000; i++) {
points.push(i);
}
var sum = points.reduce(function(a, b) { // find sum
return a + b;
});
console.log(sum);
Also you can do the addition and array creation in single for loop
var points = [], // initialize an array
sum = 0;
for (var i = 1; i <= 10000; i++) {
points.push(i); // pushing value to array
sum += i; // summation
}
console.log(sum, points);
var result = 0;
for(var i = 0; i < points.length; i++) {
result += points[i];
}
Function that takes an array of any length and returns the sum:
function sumArray(arrayToSum){
var result = 0;
for(var i = 0; i < arrayToSum.length; i++) {
result += points[i];
}
return result;
}
function arraysum(arraylength) {
var arraysum = 0;
var array1 = new Array();
for(i=1; i<=arraylength; i++) {
array1.push(i);
}
for(i = 0; i< array1.length; i++) {
arraysum += array1[i];
}
return arraysum;
}
Now when you call the function
arraysum(x)
pass the function some variable or integer for example 1, 15, or 10000.
A very elegant and compact solution is to use reduce. It accumulates the array values to reduce it to a single value by applying each value and a start value to a given function, whose return value is used as the start value for the next iteration:
function sum (a, b) {
return a + b;
}
console.log(points.reduce(sum, 0));
If you need to support older browser (e.g. IE 8) you can use a Polyfill.
If you need to create the list of numbers as well, you can create it with
var points = Array.apply(0, Array(10000))
.map(function (current, index) {
return index + 1;
});
It creates an array of 10000 elements and assigns each element it's index + 1.