Initializing and creating an array in Javascript - javascript

I want to make an array w[i][j] where each w[i][j] is itself an array of numbers.
If I try to do it naively by declaring an empty array w
and assigning variable by looping through it I get the error:
const w : Array<Array<Array<number>>> = [];
for(let i = 0; i < N; i++){
for(let j = 0; j < N; j++){
w[i][j] = [1,2,3];
}
}
TypeError: Cannot set property '0' of undefined.
Instead I am forced to initialze each element of the array to be empty, using the below code. Only after doing this am I able to make the array with no problems. This can't be the best practice. What am I misunderstanding and what should I write instead?
const w : Array<Array<Array<number>>> = [];
for(let i = 0; i < N; i++){
w[i] = [];
for(let j = 0; j < N; j++){
w[i][j] = [];
}
}

You are getting the error because w[i] is not set when you are trying to set w[i][j].
Fix
Do an init or load in the loop e.g.
const N = 5;
const w: Array<Array<Array<number>>> = [];
for (let i = 0; i < N; i++) {
w[i] = w[i] || [];
for (let j = 0; j < N; j++) {
w[i][j] = [1, 2, 3];
}
}
console.log(w); // All good 🌹

Related

Performance: why is the first implementation of the same algorithm significantly faster

The algorithm is taken from LeetCode: https://leetcode.com/problems/maximum-product-of-word-lengths/description/
Here is the jsperf I created (I have some local tests which gives the same result): https://jsperf.com/maximum-product-of-word-lengths
Here is the first "slow" implementation:
function maxProduct (words) {
if (!words || !words.length) return 0;
let len = words.length;
let values = [];
// console.log(values)
for (let i = 0; i < len; ++i) {
let tmp = words[i];
let num = 0, len = tmp.length;
for (let j = 0; j < len; ++j) {
num |= 1 << (tmp.charCodeAt(j) - 'a'.charCodeAt(0));
}
values[i] = {
num: num,
len: tmp.length
};
}
let maxProduct = 0;
for (let i = 0; i < len; ++i) {
for (let j = 0; j < len; ++j) {
if ((values[i].num & values[j].num) == 0) {
maxProduct = Math.max(maxProduct, values[i].len * values[j].len);
}
}
}
return maxProduct;
};
Here is the "fast" implementation:
function maxProductFast (words) {
var temp = [];
for(var i = 0; i < words.length; i++){
var tempObj = {};
tempObj.item = words[i];
var num = 0;
for(var j = 0; j < words[i].length; j++){
num |= 1 << (words[i].charCodeAt(j) - 97);
}
tempObj.num = num;
temp.push(tempObj);
}
var res = 0;
for(var i = 0; i < temp.length; i++){
for(var j = i + 1; j < temp.length; j++){
var item1 = temp[i];
var item2 = temp[j];
if((item1.num & item2.num) == 0) {
res = Math.max(res, item1.item.length * item2.item.length);
}
}
}
return res;
}
They're not the same. The second algorithm has a loop with a complexity of (n*(n+1))/2 where each progressive step is from i+1 to the length of temp. the first algorithm has a two nested for loops each with a cost of n^2. the complexity of both will reduce to O(n^2). I believe that both of these will have a similar performance with a significantly large enough set.
The reason you would do n+1 for each sub iteration is because you are trying to find the max of any pair of items. if you place your elements in a grid you will notice that any diagonal pair a_3 * a_2 = a_2 * a_3 produces the same value. you can basically halve the collection and save a few cycles.

How to I run a function for each piece of an array within a for loop in Javascript?

I have this so far, trying to get it to find the sum of each one of any number of inputted numbers with integers and "-"s.
When I run this,
var howM = prompt("How many cards?")
var arr = [];
for (var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for (var i = 0; i <= howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace(/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
sumpre.push(sum);
}
console.log(sumpre)
I have also tried
var howM = prompt("How many cards?")
var arr = [];
for (var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
for (var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace(/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
}
console.log(sum);
In both cases I get the sum for the first piece in the array and then undefined. How do I get it to run for each piece? I kind of have an idea of what is wrong with it I just don't quite know how to fix it.
You need to use a second counter for the nested for loop, like so:
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for(var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace (/-/g, "");
for (var j = 0; j < eXt.length; j++) {
sum += parseInt(eXt.substr(j, 1));
}
sumpre.push(sum);
}
console.log(sumpre)
Your var sum = 0; inside your for-loop meaning sum variable will not be accessible outside of the loop

Can someone please tell me why this code wont run?

var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
for(var i = 0; i <= howM; i++)
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace (/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1)); }
console.log(sum);
It tells me this "TypeError: Cannot read property 'replace' of undefined
at eval:13:11" which makes no sense to me because its right above it.
The intetended body of the loop for(var i = 0; i <= howM; i++) is not enclosed in braces {..}. As a result, only the statement var sum = 0; will be executed in the loop. Also, you probably meant to say i < howM. So you want something like this for the loop:
for(var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace (/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
}
console.log(sum);
Check the comments:
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < parseInt(howM); i++)
arr.push(prompt("Enter a card:")); //No curly braces is fine when its a single line. When there's no braces, JS just runs the next line x amount of times
console.log(arr)
var sum = 0; //Create sum out here. Setting it to zero every loop defeats the purpose
for(var i = 0; i < arr.length; i++)//You said "i <= howM". Better to use the length of the array that is being looped through
{ //Use curly braces to show what code to execute repeatedly
var eXt = arr[i]; //Set eXt to the current number
eXt = eXt.replace("-", ""); //No need for regex
sum += parseInt(eXt); //Convert the input to a number, then add it to sum
}
console.log(sum);
The second for loop doesn't have brackets around it. You can MUST use brackets UNLESS it is a one line loop. For example:
This is fine:
for (var i=0;i<100;i++)
console.log(i);
This is NOT:
for (var i=0;i<100;i++)
var x = i;
x++;
console.log(x);
So the second for loop should be this:
for(var i = 0; i <= howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace (/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
console.log(sum);
}
Also in the first for loop I would use arr[i] = value instead.

How to make a for loop dynamic?

I am have 2 arrays like [2,3] and [1000,1200,500,600,1600] .
I need to write a for loop for this like.
1.start index from 0 and end index at 2.
2.start time from 2 and end index with sum of first 2 element (2+3)= 5.
var arr = [2,3];
for(var i = 0; i<arr.length;i++)
{
//this loop runs 2 time
for(var j = 0 ; j < 2 ; j++)//for the first time
for(var j = 2 ; j < 5 ; j++)//for the second time
}
How to make this dynamic for loop? Can someone please help me code?
This would do what you want and would be extendible.
var arr = [2,3];
var sum = 0;
for(var i = 0; i<arr.length;i++)
{
sum += arr[i]
if (i === 0) {
for(var j = 0 ; j < arr[0] ; j++)
// Do first thing
}
if (i > 0) {
for(var j = arr[0] ; j < sum ; j++)
// Do second thing
}
}
Hope you are expecting this.
var arr = [2, 3];
for (var i = 0; i < arr.length; i++) {
//this loop runs 2 time
if (i == 0) {
//for the first time
for (var j = 0; j < arr[0]; j++) { }
} else if (i == 1) {
//for the second time
var totalSum = arr[0] + arr[1];
for (var j = arr[0]; j < totalSum; j++) //for the second time
{ }
}
}
If you want it to be generic, i.e. you have the array arr containing counts of elements to process, you could do it like this:
var arr = [2,3];
// k is the index into the second array, initialize to 0 here
for(var i = 0, k = 0; i < arr.length;i++)
{
//this loop runs for each element in the arr[] array
for(var j = 0 ; j < i; j++, k++) // increment k
{
// k is now the value you want:
// first time through the loop 0, 1
// second time through the loop 2, 3, 4
}
}
Another tweak would be to just keep track of the start element if it's important for j to be the value:
var arr = [2,3];
var start = 0;
for(var i = 0; i < arr.length; i++)
{
var end = start + arr[i]; // end is 2,5 in sample
for(var j = start ; j < end; j++)
{
// first time through the loop 0, 1
// second time through the loop 2, 3, 4
}
start = end; // now start at the next index, 0,2 in sample
}
Do something like this:
var k = 0;
for(var j = 0 ; j < 2 ; j++) {
k+=arr[j];
}//for the first time
for(var i = 2 ; i < k ; i++) {
//other code
}

How to add array of arrays in javascript

I have a Javascript array with multiple arrays inside. I was trying to loop through the array to return an aggregated array. So far I have done following with no luck:
var a = [[1,2,3],[4,5,56],[2,5,7]];
var x = [];
for ( var i = 0; i < a.length; i++) {
for ( var j = 0; j < a[i].length; j++) {
console.log(a[i][i] = a[i][j]+a[j][i]);
}
}
I am trying to obtain the following result:
console.log(a); // -> [7,12,66]
Any suggestions or pin points where I can look for examples of similar things would be appreciated.
assuming the elements of a has the same length, the following should work
var x=[];
for(var i=0; i<a[0].length; i++){
var s = 0;
for(var j=0; j<a.length; j++){
s += a[j][i];
}
x.push(s);
}
a[0].map(function(b,i){return a.reduce(function(c,d){return c+d[i];},0);})
// [7, 12, 66]
From dc2 to dc1, try this:
var a = [[1,2,3],[4,5,56],[2,5,7]];
var x = [];
for ( var i =0; i < a.length; i++){
for ( var j = 0; j < a[i].length; j++){
x[j] = x[j] || 0;
x[j] = x[j] + a[i][j];
}
}
This worked in testing, and doesn't error with different array lengths.

Categories

Resources