Simple Javascript for loop hangs browser - javascript

This Javascript hangs browser when the number of iteration is set to 5. However, if set to 4, it runs normally. What is the problem?
var sample = [
[1,2,3],
[4,5,6],
[7,8,9]];
for(i = 0; i < 5; i++)
swapColumn(sample, 0, 1);
function swapColumn(array, x, y)
{
for(i = 0; i < array.length; i++)
{
temp = array[i][x];
array[i][x] = array[i][y];
array[i][y] = temp;
}
}

Don't forget to use var to declare variables
var sample = [
[1,2,3],
[4,5,6],
[7,8,9]];
for(var i = 0; i < 5; i++)
swapColumn(sample, 0, 1);
function swapColumn(array, x, y)
{
for(var i = 0; i < array.length; i++)
{
var temp = array[i][x];
array[i][x] = array[i][y];
array[i][y] = temp;
}
}
Otherwise they are treated as global variables, and you are actually overwriting i everytime you enter swapColumn

Related

Javascript array won't change inside of for loop

I am trying to rotate a 2dimensional array in javascript
the code outside the forloop to switch the values works but when i try to do that inside the for loop the variables are not changing
i think it is some sort of reference problem and i searched for that but i can't find a solution to this problem
temp = tempboard[0][1];
console.log("unchanged:"+tempboard[0][1]+""+tempboard[6][1]);
tempboard[0][1] = tempboard[6][1];
tempboard[6][1] = temp;
console.log("changed:"+tempboard[0][1]+""+tempboard[6][1]);
for(i = 0; i < board.length; i++){
for(j = 0; j < board[0].length; j++){
/*a = tempboard[i][j];
b = tempboard[j][i];
temp = a;
a = b;
b = temp;
console.log(a+" "+b);*/
temp = tempboard[i][j];
console.log("unchanged:"+tempboard[i][j]+""+tempboard[j][i]);
tempboard[i][j] = tempboard[j][i];
tempboard[j][i] = temp;
console.log("changed:"+tempboard[j][i]+""+tempboard[i][j]);
}
}
I think it will be easier to build a new array based on the old one.
In the below code a new array is build in reverse based on the original one.
arr = [[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]];
console.log(JSON.stringify(Rotate2D(arr)));
function Rotate2D(array) {
//Create a new empty array with the same size as the original one.
let returnArr = [...Array(array.length)].map(e => Array(array[0].length));
let maxIndexI = array.length - 1;
let maxIndexJ = array[0].length - 1;
//Fill the return array rotated
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array[0].length; j++) {
returnArr[maxIndexI - i][maxIndexJ - j] = array[i][j]
}
}
return returnArr;
}
Try adding "let" keyword to your for loop, it could be an hoisting issue;
for(let i = 0; i < board.length; i++){
for(let j = 0; j < board[0].length; j++){
/*a = tempboard[i][j];
b = tempboard[j][i];
temp = a;
a = b;
b = temp;
console.log(a+" "+b);*/
temp = tempboard[i][j];
console.log("unchanged:"+tempboard[i][j]+""+tempboard[j][i]);
tempboard[i][j] = tempboard[j][i];
tempboard[j][i] = temp;
console.log("changed:"+tempboard[j][i]+""+tempboard[i][j]);
}
}

For loop through array.length only executes once

The code below only executes through the first for loop once, yet all the other for loops perform as expected. Does anyone know why this is the case? I'm not sure how relevant the bulk of the (inefficient, poorly formatted) code within the loop is but I include it nonetheless.
var numbers = [9795526789839145, 2861747566959730, 4498854833783559, 6301982162016598, 1131197164065322];
for (i = 0; i < numbers.length; i++) {
var current = numbers[i];
var currentStr = current.toString();
var reverseStr = currentStr.split('').reverse().join('');
var reverseArr = [];
for (i = 0; i < reverseStr.length; i++) {
reverseArr.push(reverseStr[i]);
}
var A = 0;
for (i = 0; i < reverseArr.length; i += 2) {
A += Math.round((reverseArr[i]));
}
var evenDigits = [];
for (i = 1; i < reverseArr.length; i += 2) {
evenDigits.push(reverseArr[i]);
}
for (i = 0; i < evenDigits.length; i++) {
evenDigits[i] = evenDigits[i] * 2;
if (evenDigits[i] > 9) {
var temp = evenDigits[i].toString();
var firstInt = Math.round(temp[0]);
var secondInt = Math.round(temp[1]);
evenDigits[i] = firstInt + secondInt;
}
}
var B = 0;
for (i = 0; i < evenDigits.length; i++) {
B += evenDigits[i];
}
var sum = A + B;
if (sum % 10 == 0) {
console.log('Yes');
} else console.log('No');
}
In your code you are using same instance of 'i' variable to iterate all loops.
Solution is to use different index variables to iterate external and internal loops
var numbers = [9795526789839145, 2861747566959730, 4498854833783559, 6301982162016598, 1131197164065322];
var i = 0;
var j = 0;
for (j=0; j < numbers.length; j++) {
var current = numbers[j];
/...
}
JavaScript behaves like this because 'i' is not scoped to block (like in Java od C#). In ES2015 you can use let or const to bind variable to block scope (in this sample to for loop)

Can't get inside my for loop (Javascript)

I am trying to iterate over the variable pieces, but somehow it is not triggering. In the function below, pieces.length turns 4, but piecesNew turns [] - moreover console.log(i) is never reached.
What is happening?
self.reworkPieces = function(pieces) {
var piecesNew = [];
console.log(pieces.length)
for (var i; i <= pieces.length; i++) {
console.log(i)
piecesNew[i] = {
c: pieces[i].r,
r: pieces[i].c,
p: i
}
}
console.log(piecesNew)
return piecesNew;
};
undefined is not less than or greater than any number.
var i; // undefined
i < 10; // false
i > 10; // false
You simply need to make sure i is equal to 0.
You also want i to never be equal to pieces.length so use < instead of <= (the last index of an array is always length - 1, e.g. an array of length 3 has indexes 0, 1 and 2 – the first index is always 0, not 1)
So:
for (var i = 0; i < pieces.length; i++) {
...
define value for variable i, var i = 0
self.reworkPieces = function(pieces) {
var piecesNew = [];
console.log(pieces.length)
for (var i = 0; i <= pieces.length; i++) {
console.log(i)
piecesNew[i] = {
c: pieces[i].r,
r: pieces[i].c,
p: i
}
}
console.log(piecesNew)
return piecesNew;
};
self.reworkPieces = function(pieces) {
var piecesNew = [];
console.log(pieces.length)
for (var i = 0; i <= pieces.length; i++) {
console.log(i)
piecesNew[i] = {
c: pieces[i].r,
r: pieces[i].c,
p: i
}
}
console.log(piecesNew)
return piecesNew;
};
Change:
for (var i; i <= pieces.length; i++)
To:
for (var i = 0; i < pieces.length; i++)
Initialize var i = 0 initially then it will work
self.reworkPieces = function(pieces) {
var piecesNew = [];
console.log(pieces.length)
for (var i = 0; i <= pieces.length - 1; i++) {
console.log(i)
piecesNew[i] = {
c: pieces[i].r,
r: pieces[i].c,
p: i
}
}
console.log(piecesNew)
return piecesNew;
};

Arrays acting odd

So, I'm working on a javascript application that can solve any size matrix. I'm running into a SUPER weird problem, where my main array only has the value of 0 after a certain point. The input should be a data set, like this
1, 8
2, 10
3, 13
4, 17
5, 22
But I'm having trouble with it. When I run the code, the console.log prints out a pretty derpy array
[[1, 1, 1, 8],
[0, 0, 0, 0],
[0, 0, 0, 0]]
It gets even weirder. If I move the console.log to before I call the rref function, I get the same thing.
Anybody ever seen this before? Anyone know how to fix it? Thanks!
//Matrix object
var matrix = {
startingDataSet: [],
degree: 0,
M: []
}
//splits up user input into a more readable format
function getDataFromString(data) {
var points = data.split("\n");
for (var i=0; i<points.length; i++) {
points[i] = points[i].split(", ");
points[i][0] = parseInt(points[i][0]);
points[i][1] = parseInt(points[i][1]);
}
return points;
}
//finds the degree of the polynomail from the matrix object's data
function setPolynomialDegree(original) {
var data = original;
console.log(original);
//temporary data set to hold numbers in
var tempNumbers = [];
var degree = 1;
//move the original set of Y values into the temporary data set
for (var i = 0; i < data.length; i++) {
tempNumbers.push(data[i][1]);
}
//while the numbers in tempdata are not the same, execute subtraction
while (tempNumbers[0] != tempNumbers[1]) {
var newnums = []
var l = tempNumbers.length;
//find the difference for every set of numbers (0 & 1, 1 & 2, 2 & 3, etc.), and push those into the new data set
for (var i = 0; i < l - 1; i++) {
newnums.push(tempNumbers[i + 1] - tempNumbers[i]);
}
//replace old data set with new one
tempNumbers = newnums;
//increase polynomial degree by one
degree += 1;
}
return degree;
}
//add 2 arrays together
function addrows(r1, r2) {
var temprow = [];
for (var i = 0; i < r1.length; i++) {
temprow.push(r1[i] + r2[i]);
}
return temprow;
}
//multiply array by constant
function multrow(r1, num) {
var temprow = [];
for (var i = 0; i < r1.length; i++) {
temprow.push(r1[i] * num);
}
return temprow;
}
//rref function
function rref(mtrx, deg) {
var temp1 = [];
var temp2 = [];
for (var row = 0; row < mtrx.length; row++) {
for (var j = 0; j < mtrx.length-1; j++) {
temp1 = multrow(mtrx[row], mtrx[j+1][row]);
temp2 = multrow(mtrx[j+1], mtrx[row][row]);
temp1 = multrow(temp1, -1);
mtrx[j+1] = addrows(temp1, temp2);
}
}
return mtrx;
}
//Main function that will solve the matrix
function solveFromDataSet(data) {
data = getDataFromString(data);
for (var i=0; i<data.length; i++) {
matrix['startingDataSet'].push(data[i]);
}
matrix.degree = setPolynomialDegree(matrix.startingDataSet);
matrix.M = [];
for (var i = 0; i < matrix.degree; i++) {
var row = [];
for (var j = matrix.degree; j > 0; j--) {
row.push(Math.pow(data[i][0], j - 1));
}
row.push(data[i][1]);
matrix['M'][i] = row;
}
var var_array = rref(matrix['M']);
console.log(matrix.M);
return matrix.M;
}

Is it possible to define and initialize multidimensional arrays in JavaScript in one line of code?

Sorry if this is too basic, but I am struggling at defining 4-dimensional array (of size 6x6x6x6) in JavaScript and initializing it to all 1's. What's the easiest way to do this?
Thanks!
You can use the literal syntax, but it would be very big and cumbersome. You may want to try something like this:
var x = [1, 1, 1, 1, 1, 1];
for (var i = 1; i < 4; i++) {
x = [x, x, x, x, x, x];
}
I found a slightly simpler solution:
var x = 1;
for (var i = 0; i < 4; i++) {
x = [x, x, x, x, x, x];
}
Seems like there should be easier way, but this will do it.
var array = [];
for(var i=0; i<6; i++) {
for(var j=0; j<6; j++) {
for(var k=0; k<6; k++) {
for(var l=0; l<6; l++) {
array[i][j][k][l]=1;
}
}
}
}
Edit
To generate an n-dimensional AxBxCxDx... array (untested):
Array.prototype.fill = function(elem, n) {
for(var i=0; i<n; i++, this.push(elem));
}
function generateArray() {
var dimensions = Array.prototype.slice.call(arguments);
var x = 1;
for (var i = dimensions.length-1; i >= 0; i--) {
x = [].fill(x, dimensions[i]);
}
return x;
}
to generate a 2x3x4x5 matrix:
generateArray(2,3,4,5);
I implemented ddlshack's generalized method, but ran into an issue due to the fact that arrays are "pass by reference" in JavaScript. This resulted in each dimension of the array holding multiple references to the same array rather than copies of it. To correct the issue, I implemented the solution as follows (the only other difference being that I used a second function rather than modify Array's prototype).
var fillArray = function(val, dim) {
var a = [];
for (var i = 0; i < dim; i++) {
if (Object.prototype.toString.call(val) === "[object Array]") {
val = val.slice(0);
}
a.push(val);
}
return a;
};
var generateArray = function() {
var dimensions = Array.prototype.slice.call(arguments),
val = 0;
for (var i = (dimensions.length - 1); i >= 0; i--) {
val = fillArray(val, dimensions[i]);
}
return val;
};

Categories

Resources