Reputation: 99
I'm writing a simple minesweeper game in Javascript. I have a 2-dimensional array (called "mineInput") to hold the locations of all the mines. And I have a separate array "result" which records the number of mines adjacent to each cell.
I have 2 nested for loops to iterate over each row and each column in "result" and check every sell in 'mineInput". If there is a mine, I increment the mine count with result[i][j]++;
. However I noticed weird behavior where the entire column is incremented instead of just one cell.
this:
[ [ 0, 0, 0 ],
[ 0, 0, 0 ],
[ 0, 0, 0 ] ]
followed by: result[i][j]++;
becomes:
[ [ 0, 1, 0 ],
[ 0, 1, 0 ],
[ 0, 1, 0 ] ]
instead of:
[ [ 0, 0, 0 ],
[ 0, 1, 0 ],
[ 0, 0, 0 ] ]
Here is the full code (pls excuse the obscene number of console logs). https://repl.it/BIYH/2
Any idea what's wrong?
Upvotes: 1
Views: 226
Reputation: 19027
I guess the problem is in the following code:
var result = [];
var newRow = [];
for (var i = 0; i < rowCount; i++) {
newRow.push(0);
}
for (var i = 0; i < rowCount; i++) {
result.push(newRow);
}
You add the same array over and over again to the array result
. Instead, you want to create a new array for each row:
var result = [];
for (var i = 0; i < rowCount; i++) {
var newRow = [];
for (var j = 0; j < rowCount; j++) {
newRow.push(0);
}
result.push(newRow);
}
An array is an object in javascript, and objects are always passed by reference.
Upvotes: 1
Reputation: 12028
The issue is early in your code where you initialise your arrays
var result = [];
var newRow = [];
for (var i = 0; i < rowCount; i++) {
newRow.push(0);
}
for (var i = 0; i < rowCount; i++) {
result.push(newRow);
}
You have created only one newRow
array and added it to your result
array 3 times. So you could show this like:
newRow == [0,0,0]
result == [newRow, newRow, newRow]
When you increment you add to one cell in the newRow
array which gives
newRow == [0,1,0]
result == [newRow, newRow, newRow] therefore
result = [[0,1,0],[0,1,0],[0,1,0]]
you can fix this like this:
var result = [];
for (var i = 0; i < rowCount; i++) {
// create a new array for each row
var newRow = [];
for (var i = 0; i < rowCount; i++) {
newRow.push(0);
}
result.push(newRow);
}
Upvotes: 4