0

Sorry I really cant find the error in my code.

So i had this code which populates a 2 dimensional array with certain random values which act like a board and has a current size of 5x5.

function createTableArray() {
var boardSize = 5;
var board = new Array(boardSize);
var boardCol = new Array(boardSize);
var prevVal = 0;

for (var i=0;i<boardSize;i++) {
    for (var j=0;j<boardSize;j++) {
        boardCol[j] = getRandomColVal(i, boardSize - j);
    }
    board[i] = boardCol;

    console.log(i + " within loop temp Col : " + boardCol);
    console.log(i + " within loop Board : " + board[i]);
}


console.log("Before returning");
for (var i=0;i<boardSize; i++) {
    console.log(i + " Board: " + board[i]); 
}

return board;
}

I created a "before returning" log to check the board again but as a result all the board content only has the same values as the last boardCol. (Sorry for the poor explanation, I'll just present it visually).

It was supposed to be like this (since this is the value of boardCol when I logged it):

 Array [ 5,8,12,13,14 ] 
 Array [ 20,24,25,27,28 ] 
 Array [ 38,39,40,41,43 ] 
 Array [ 48,54,55,56,57 ] 
 Array [ 64, 67, 71, 72, 73 ]

But it turned out like this:

 Array [ 68, 71, 72, 73, 74 ] 
 Array [ 68, 71, 72, 73, 74 ] 
 Array [ 68, 71, 72, 73, 74 ] 
 Array [ 68, 71, 72, 73, 74 ] 
 Array [ 68, 71, 72, 73, 74 ]

Sorry, I really don't get how it all have the same values.

2
  • 2
    You need to create boardCol inside the loop that fills board, or they’ll all just be references to the same array. Commented Jul 29, 2014 at 17:26
  • @minitech Thank you! So it really was a referencing problem.. Commented Jul 29, 2014 at 17:51

1 Answer 1

2

Like minitech said in a comment: you need a distinct array for each column of board. Try this:

function createTableArray() {
    var boardSize = 5;
    var board = new Array(boardSize);

    for (var i=0; i<boardSize; i++) {
        var boardCol = new Array(boardSize);
        for (var j=0; j<boardSize; j++) {
            boardCol[j] = getRandomColVal(i, boardSize - j);
        }
        board[i] = boardCol;
    }
    return board;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.