Problem with JavaScript Array - javascript

TilesArray.tiles has a wrong output, alert(TilesArray.array); gives me the correct output with randomized numbers, but at the end TilesArray.tiles has the same array in each index.
for (i = 0; i < 200; i++) {
for (j = 0; j < 200; j++) {
TilesArray.array[j] = (Math.round(Math.random() * 499 + 1));
}
alert(TilesArray.array);
TilesArray.tiles[i] = TilesArray.array;
}
Any solution to fix the issue?

You need to copy the array. Could be done with slice()
for (i = 0; i < 200; i++) {
for (j = 0; j < 200; j++) {
TilesArray.array[j] = (Math.round(Math.random() * 499 + 1));
}
alert(TilesArray.array);
TilesArray.tiles[i] = TilesArray.array.slice(0);
}

You're continuously adding a reference to the same array to tiles. To get around this, create a new array in each iteration of the outer loop:
for (i = 0; i < 200; i++) {
TilesArray.array = []; // This is the line
for (j = 0; j < 200; j++) {
TilesArray.array[j] = (Math.round(Math.random() * 499 + 1));
}
alert(TilesArray.array);
TilesArray.tiles[i] = TilesArray.array;
}
Or even better? Add everything directly to your tiles array (it's one less variable to worry about):
for (i = 0; i < 200; i++) {
TilesArray.tiles[i] = [];
for (j = 0; j < 200; j++) {
TilesArray.tiles[i][j] = (Math.round(Math.random() * 499 + 1));
}
}

At each iteration, you fill your TilesArray.array with new random values, and store a reference to this unique array in TilesArray.tiles[i]. But the array of random values is always the same. You just have many pointers to the same array.
You need to allocate a new array at each iteration :
for (i = 0; i < 200; i++) {
TilesArray.array = [];
for (j = 0; j < 200; j++) {
TilesArray.array[j] = (Math.round(Math.random() * 499 + 1));
}
alert(TilesArray.array);
TilesArray.tiles[i] = TilesArray.array;
}

Related

JS - Convert nested forloops into single loop

I need to convert this nested loop into a single loop.
This is the loop with the scenario:
First incrementer is i which starts from 0 and should run till 10
Second incrementer is j which starts from where i left off + 1 and runs till 10
.
.
My Nested Loop
for (var i = 0; i < 10; i++) {
for (var j = i + 1; j < 10; j++) {
if (some_condition) {
do_sth()
}
}
}
My Attempt at conversion
var i = 0;
while (i < 10){
var j = i + 1;
if (j < 10) {
if (some_condition) {
do_sth()
}
j++;
}
i++;
}
Unfortunately, my attempt doesn't produce the expected results.
The second snippet does not give the output which the first snippet delivers.
Can anyone please suggest me what my mistake is or provide me a better solution to achieve my target?
Thanks!
Not sure it improves readability complexity, but the following should produce the same.
var i = 0, j = 1;
while (i < 9) {
console.log(i, j);
j += 1;
if (j >= 10) {i += 1; j = i + 1}
}
You need to update i inside else statement or use continue. And declare j outside of the while body.
But keep in mind that this neither change "the order of complexity" nor "optimise" your code.
var i = 0;
var j = 1;
while (i < 10) {
if (j < 10) {
if (true) {
console.log(i, j)
}
j++;
} else {
i++;
j = i + 1;
}
}
You could adjust the loop lenght of i and check if j is greater or equal than 9, then increment i and start with fresh j.
var i = 0,
j = 1;
while (i < 9) {
console.log(i, j);
// do you stuff
if (j >= 9) j = ++i;
j++;
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

Too short loop and infinite loop?

I'm trying to make a code that would represent the Law of Large numbers in mathematics. However, I've been having trouble trying to print 20 different numbers with one execution of a code. If I have the for loop limit to little (i.e. any number less than 12), it will only print out one number. If I have the limit too big (numbers bigger than 13), it will print out an infinite set of numbers.
var numPeople = [];
var coin = [0, 1];
var sameSide = [];
for (var i = 0; i < 9; i++) {
numPeople.push(i);
}
function coinFlip() {
for (var i = 0; i < numPeople.length; i++) {
coinChance = Math.floor(Math.random() * 100);
if (coinChance < 50) {
coinSide = coin[1];
} else {
coinSide = coin[2];
}
numPeople[i] = coinSide;
}
}
for (var i = 0; i < 2; i++) {
coinFlip();
for (var i = 0; i < numPeople.length; i++) {
for (var j = i; j < numPeople.length - i; i++) {
if (numPeople[i] === numPeople[j]) {
sameSide.push(true);
}
}
}
console.log(sameSide.length);
}

getting different random numbers in a loop not random

I am filling an array with random numbers with a loop, but the random number is exactly the same for each item in the array, I think this is because of the seed value that Math.rand() uses. How can i get a different number each time?
for(var i = 0; i < 10; i++){
number[i] = getRandom(0, 100);
}
function getRandom(a, b){
var num = Math.floor((Math.random()*b)+a);
return num;
}
Works fine for me:
http://jsfiddle.net/kzUUt/
You need to declare number though...
var number = new Array(10);
for(var i = 0; i < 10; i++)
{
number[i] = getRandom(0, 100);
console.log(number[i]);
}
function getRandom(a, b)
{
var num = Math.floor((Math.random()*b)+a);
return num;
}
Here is working demo.
var number = new Array();
for (var i = 0; i < 10; i++) {
number[i] = getRandom(0, 100);
}
function getRandom(a, b) {
return Math.floor((Math.random() * b) + a);
}
for (var j = 0; j < 10; j++) {
alert(number[j]);
}

how to multiply and adding two dimensional arrays

I have variable with string values in two dimensional array format.
var arrayList=[["1","2"],["6","3600","11","60"],["1","2","3","4","5","6"]];
What I want,each odd position value multiply with next even position and finally adding that values
like.
["1","2"]=(1*2);
["6","3600","11","60"]=((6*3600)+(11*60));
["1","2","3","4","5","6"]=((1*2)+(3*4)+(5*6))
for this I written the following code,second and third cases are not working.
really sorry might be it's very basic question but I tested each and every line it's seems code is correct but in second and third cases getting Nan.
var result=[];
for (var index = 0; index < arrayList.length; index++) {
var innerResult=0;
for (var jndex = 0; jndex < arrayList[index].length; jndex++) {
var cali=parseInt(arrayList[index][jndex])*parseInt(arrayList[index][jndex+1]);
innerResult=innerResult+cali;
jndex=jndex+2;
};
result.push(innerResult);
};
result
I am getting like this [3,Nan,Nan].
please can anyone help me.
Thanks
You're incrementing jndex on each loop and then you are adding 2 more at the end of that loop. You have two options, changing this:
for (var jndex = 0; jndex < arrayList[index].length; jndex++) {
to:
for (var jndex = 0; jndex < arrayList[index].length; jndex+=2 ) {
or this:
jndex=jndex+2;
to:
jndex=jndex+1;
If you do the first one, you no longer need the increment within the loop.
I have written this algorithm that I believe might help you.
var array = [["1","2"],["6","3600","11","60"],["1","2","3","4","5","6"]];
array.map(function(subArray){
var total = 0;
for(var i = 1; i < subArray.length; i += 2)
total += parseInt(subArray[i], 10) * parseInt(subArray[i - 1], 10);
return total;
});
The jindex will be incremented by the loop as well. This will mean the jindex is incremented by 3 each loop.
Consider the case where jindex is arrayList[index].length - 1; when you parseInt(arrayList[index][jndex+1]) you will reach outside the bounds of the array, and get undefined (and parseInt(undefined) is NaN again).
If you fix those, you should find your code works;
var result = [];
for (var index = 0; index < arrayList.length; index++) {
var innerResult = 0;
for (var jndex = 0; jndex < arrayList[index].length - 1; jndex++) {
var cali = parseInt(arrayList[index][jndex]) * parseInt(arrayList[index][jndex + 1]);
innerResult = innerResult + cali;
jndex = jndex + 1;
};
}
http://jsfiddle.net/Bwx2g/
Try this:
var result = [];
for (var index = 0; index < arrayList.length; index++) {
var innerResult = 0;
for (var jndex = 0; jndex < arrayList[index].length;) {
var cali = (parseInt(arrayList[index][jndex]) * parseInt(arrayList[index][jndex + 1]));
innerResult = innerResult + cali;
jndex = jndex + 2;
}
result.push(innerResult);
}
Inner for loop changed to while loop (you have double increment in for loop):
var result = [];
for (var index = 0; index < arrayList.length; index++) {
var innerResult = 0;
var j = 0;
while (j < arrayList[index].length) {
var cali = parseInt(arrayList[index][j]) * parseInt(arrayList[index][j + 1]);
innerResult = innerResult + cali;
j += 2;
}
result.push(innerResult);
};

Filling a bi-dimensional array in JavaScript using a for loop

So, I need to fill a bi-dimensional array in JavaScript and I'm doing it the following way:
var i = 0, j = 0;
for (i = 0; i < roomWidth / tileWidth; i += 1) {
roomBuffer[i] = [];
}
for (i = 0; roomWidth / tileWidth; i += 1) {
for (j = 0; j < roomHeight / tileHeight; j += 1) {
roomBuffer[i][j] = 1;
}
}
alert("Hello world");
The problem is that it not only doesn't work but any code that comes after it, it's not executed. In this case the alert("Hello world");. What am I doing wrong guys?
change
for (i = 0; roomWidth / tileWidth; i += 1) {
to
for (i = 0; i < roomWidth / tileWidth; i += 1) {
You don't need to declare i and j before the loops. If their existence is solely for the loops, they are better off as local variables. Also, you can combine loops.
Also, what #Yuriy Zubarev said is right. The middle statement in the for-loop is a condition that must hold true throughout the loop.
for (var i = 0; i < roomWidth / tileWidth; i++) {
roomBuffer[i] = [];
for (var j = 0; j < roomHeight / tileHeight; j++) {
roomBuffer[i][j] = 1;
}
}
alert("Hello world");
Have a look at this fiddle.
change your
for (i = 0; roomWidth / tileWidth; i += 1)
to
for (i = 0; i < roomWidth / tileWidth; i += 1)
You can simplify your code by using a small helper function
// create an array of length len filled with value
fill = function(len, value) {
for (var a = []; len-- > 0; a.push(value));
return a;
}
Your code:
size = roomWidth / tileWidth
roomBuffer = fill(size, fill(size, 1))

Categories