Loop trough array and sum the length - javascript

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);

Related

find all numbers disappeared in array

Please help me to solve this leetcode problem using javascript as I am a beginner and dont know why this code is not working
Ques: Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
var findDisappearedNumbers = function (nums) {
var numLength = nums.length;
nums.sort(function (a, b) { return a - b });
for (var i = 0; i < nums.length - 1; i++) {
if (nums[i + 1] === nums[i]) {
nums.splice(i, 1);
}
}
for (var k = 0; k < nums.length; k++) {
for (var j = 1; j <= numLength; j++) {
if (nums[k] !== j) {
return j;
}
}
}
};
if there is any error in my code please let me know;
i have done the following thing
first i have sorted the array in ascending order
then i have cut all the duplicate elements
then i have created loop that will check if nums[k] !== j ;
and it will return j which is the missing number;
for example this is the testcase [4,3,2,7,8,2,3,1]
first my code will sort this in ascending order [1,2,2,3,3,4,7,8]
then it will remove all duplicate elements and it will return [1,2,3,4,,7,8]
and then it will check nums[k] is not equal to j and it will print j
I think it'd be easier to create a Set of numbers from 1 to n, then just iterate through the array and delete every found item from the set:
var findDisappearedNumbers = function(nums) {
const set = new Set();
for (let i = 0; i < nums.length; i++) {
set.add(i + 1);
}
for (const num of nums) {
set.delete(num);
}
return [...set];
};
console.log(findDisappearedNumbers([4,3,2,7,8,2,3,1]));
To fix your existing code, I'm not sure what the logic you're trying to implement in the lower section, but you can iterate from 1 to numLength (in the outer loop, not the inner loop) and check to see if the given number is anywhere in the array. Also, since you're mutating the array with splice while iterating over it in the upper loop, make sure to subtract one from i at the same time so you don't skip an element.
var findDisappearedNumbers = function(nums) {
var numLength = nums.length;
nums.sort(function(a, b) {
return a - b
});
for (var i = 0; i < nums.length - 1; i++) {
if (nums[i + 1] === nums[i]) {
nums.splice(i, 1);
i--;
}
}
const notFound = [];
outer:
for (var j = 1; j < numLength; j++) {
for (var k = 0; k < nums.length; k++) {
if (nums[k] === j) {
continue outer;
}
}
notFound.push(j);
}
return notFound;
};
console.log(findDisappearedNumbers([4, 3, 2, 7, 8, 2, 3, 1]));
#CertainPerformance certainly cracked it again using the modern Set class. Here is a slighly more conservative approach using an old fashioned object:
console.log(missingIn([4,3,2,7,8,2,3,1]));
function missingIn(arr){
const o={};
arr.forEach((n,i)=>o[i+1]=1 );
arr.forEach((n) =>delete o[n] );
return Object.keys(o).map(v=>+v);
}
My solution for the problem to find the missing element
var findDisappearedNumbers = function(nums) {
const map={};
const result=[];
for(let a=0;a<nums.length;a++){
map[nums[a]]=a;
}
for(let b=0;b<nums.length;b++){
if(map[b+1]===undefined){
result.push(b+1)
}
}
return result;
};
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]
Example 2:
Input: nums = [1,1]
Output: [2]

Find the number of adjacent element trios with given sum

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.

3 variable sequence sum

So basically there are two sequences from I to j and j to k.
For example 3 to 5 and 5 to 2.
And we need to know the sum. 3 + 4 + 5 + 4 + 3 + 2.
And my code is not working.
var arr = [];
var sum = 0;
function pushIn(i, j, k){
for(var a = i; a < j; a++){
arr.push(a);
}
for(var a = j; a == k; a--){
arr.push(a);
}
for(var i = 0; i <arr.length;i++){
sum += arr[i];
}
}
}
I think the problem lies in your second for loop
Perhaps you should try this
for(var a = i; a < j; a++){
arr.push(a);
}
for(var a = j; a > k; a--){
arr.push(a);
}
for(var i = 0; i <arr.length;i++){
sum += arr[i];
}
Hope this helps
In for loop, second argument is a comparator- condition for executing the code block.
In your second loop, condition is never met hence it does not iterate at all.
In your case, I am assuming you want loop to be iterated unless it is less than or equals to k hence you need to make it >= so that condition will meet andloop will be iterated.
var arr = [];
var sum = 0;
function pushIn(i, j, k) {
for (var a = i; a < j; a++) {
arr.push(a);
}
for (var a = j; a >= k; a--) {
arr.push(a);
}
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
console.log(pushIn(3, 5, 2));
You may use .concat() and .reduce() to get the resultant value:
let reducer = (i, j, k) => [].concat(
Array.from({length: j - (i - 1)}, (_, index) => i + index),
Array.from({length: j - k}, (_, index) => j - (index + 1))
).reduce((r, c) => r + c, 0);
console.log(reducer(3, 5, 2));

Unable to push a function return in a loop

I have this function which returns an array of prime numbers:
function getPrimeFactors(n) {
var factors = [];
for (i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
var count = 0;
while (n % i === 0) {
n = n / i;
count++;
}
for (j = 1; j <= count; j++) {
factors.push(i);
}
}
}
if (n !== 1) {
factors.push(n);
}
return factors;
}
var numbers = [2, 3, 4, 5];
var array = [];
I want to get prime factors of all the numbers in the numbers array and push it into a new array (array)
for(i = 0; i < numbers.length; i++) {
array.push(getPrimeFactors(numbers[i]));
}
What am i doing wrong?
As mentioned by Damien Gold in the answer that was deleted, use var in your for-loops to make the variables local and to prevent your 2 functions from interfering with each other.
function getPrimeFactors(n) {
var factors = [];
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
var count = 0;
while (n % i === 0) {
n = n / i;
count++;
}
for (var j = 1; j <= count; j++) {
factors.push(i);
}
}
}
if (n !== 1) {
factors.push(n);
}
return factors;
}
And:
var numbers = [2, 3, 4, 5];
var array = [];
for(var i = 0; i < numbers.length; i++) {
array.push(getPrimeFactors(numbers[i]));
}
As a sidenote,
you are pushing arrays into your array instead of adding the values contained in your getPrimeFactors-array. If you instead want to push the resulting numbers into one array, try this:
for(var i=0; i<numbers.length; i++) {
array = array.concat(getPrimeFactors(numbers[i]));
}

Javascript sum of arrays and average

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);
}

Categories