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))
Related
its me again. This time I tried to make a Selection Sort using JavaScript. Everything went well until my code didn't print the specific output that I want. If you tried to run my code below, the second-last index in the array didn't sort properly. Can anyone give me a brief explanation?
Here's the code by the way,
var num = [30,1,90,3,2,34];
var bilnum = num.length,i,j,min;
var temp = 0;
for(i = 0; i < bilnum - 1; i++){
min = i;
for(j = i + 1; j < bilnum ; j++){
if(num[j] < num[min]){
min = j;
}
if(min != i){
temp = num[i];
num[i] = num[min];
num[min] = temp;
}
}
}
document.write(num)
You need to move the below snippet from the inner loop to the end of the outer loop as you need to swap after finding the min index.
if(min != i){
temp = num[i];
num[i] = num[min];
num[min] = temp;
}
So the code will look something like this
var num = [30,1,90,3,2,34];
var bilnum = num.length,i,j,min;
var temp = 0;
for(i = 0; i < bilnum - 1; i++){
min = i;
for(j = i + 1; j < bilnum ; j++){
if(num[j] < num[min]){
min = j;
}
}
if(min != i){
temp = num[i];
num[i] = num[min];
num[min] = temp;
}
}
console.log(num);
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; }
I have a problem with my exercise. I have to draw something like this:
https://screenshots.firefox.com/3qaHB7dcr3n610hi/jsbin.com
And this is my code
var empty = "";
for(var i=0; i < 5; i++) {
empty += "*";
console.log(empty)
}
but with this code I can only make this:
*
**
***
****
*****
I have no idea how to reverse this loop to start it from top from 5 stars, i tried something like this:
var empty = "";
for (i = 5; i <= 0;i--) {
empty+="*";
console.log(empty);
}
But doesn't work. Anybody know how to do this? I will be grateful :)
Your approach builds the first part.
The second part can be accomplished using the function slice in descending direction.
var empty = "";
var i = 0;
// Build the first part
for (; i < 5; i++) {
empty += "*";
console.log(empty)
}
// Here i = 5, so this is the initialization for the following loop.
// Loop in descending direction using the function slice.
for (; i > 0; i--) {
console.log(empty.slice(0, i))
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Your condition was wrong. Check this.
for(let i = 1; i <= 5; i++) {
console.log('\"' + '*'.repeat(i) + '\"');
}
for(let i = 5; i > 0; i--) {
console.log('\"' + '*'.repeat(i) + '\"');
}
Instead of a for/loop you could use a while loop to change the direction:
let stars = 0;
let count = 0;
while (count < 9) {
if (count < 5) stars++;
if (count >= 5) stars--;
const line = Array(stars).fill('*').join('');
console.log(line);
count++;
}
Just in case you need a nested for loop. (As some exercises sometimes do)
var k = 0;
for(var i = 1; i < 12; i++){
var stx = "";
for(var j = k; j < i; j++){
stx += "*";
}
if(i > 5) k += 2
if(i == 6) continue
console.log(stx);
}
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);
};
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;
}