6

Im looking to make an 8 x 8 chessboard in my terminal. I've made the proper 8 x 8 grid but can't add the two queens now as 1's

I keep trying as you can see in the code arrayz[0][1] = 1. I'm wondering if the problem is with my looping or there's an easy way to insert two ones into the problem.

const generateBoard= function(){

  let arrayz = []
  let set= []
  let newArray = []


  for (i = 0; i < 8; i++){

      newArray.push(0)
  } 
  for (y = 0; y < 8; y++){
      //newArray[0][1] = 1
      arrayz.push(newArray)  
      arrayz[0][1] = 1 //my failed code that im trying to use to input a single one

  }  
  return arrayz
}  

console.log(generateBoard(whiteQueen, blackQueen))



[ [ 0, 1, 0, 0, 0, 0, 0, 0 ],
  [ 0, 1, 0, 0, 0, 0, 0, 0 ],
  [ 0, 1, 0, 0, 0, 0, 0, 0 ],
  [ 0, 1, 0, 0, 0, 0, 0, 0 ],
  [ 0, 1, 0, 0, 0, 0, 0, 0 ],
  [ 0, 1, 0, 0, 0, 0, 0, 0 ],
  [ 0, 1, 0, 0, 0, 0, 0, 0 ],
  [ 0, 1, 0, 0, 0, 0, 0, 0 ] ] //what i keep getting
  [ [ 0, 1, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, , 0, 0, 0, 0, 0, 1 ] ]//what i want
ggorlen
  • 44,755
  • 7
  • 76
  • 106
grant taylor
  • 105
  • 3
  • 1
    You're pushing the same row over and over again. You should add a _new_ row in each loop. – georg Sep 07 '19 at 21:28

1 Answers1

9

This code creates only one board row array, newArray, rather than the desired 8. All 8 entries in the array arrayz are just references to newArray. Modifying any one of them will modify all 8, which is obviously not the intent.

In fact, printing the output here on Stack Overflow shows:

[
  [
    /**id:2**/
    0,
    1,
    0,
    0,
    0,
    0,
    0,
    0
  ],
  /**ref:2**/,
  /**ref:2**/,
  /**ref:2**/,
  /**ref:2**/,
  /**ref:2**/,
  /**ref:2**/,
  /**ref:2**/
]

Which labels each reference array as a pointer to the first element which has the id 2. Here's the runnable example:

const generateBoard= function(){

  let arrayz = []
  let set= []
  let newArray = []


  for (i = 0; i < 8; i++){

      newArray.push(0)
  } 
  for (y = 0; y < 8; y++){
      //newArray[0][1] = 1
      arrayz.push(newArray)  
      arrayz[0][1] = 1 //my failed code that im trying to use to input a single one

  }  
  return arrayz
}  

console.log(generateBoard())

The reference problem can be addressed in a variety of ways. For example, changing

arrayz.push(newArray)  

to

arrayz.push(newArray.slice()); 

makes a true copy of newArray using Array#slice, eliminating the unwanted aliasing.


Another way to make a 2d grid of zeroes is using the Array constructor, Array#fill and Array#map:

const board = Array(8).fill().map(() => Array(8).fill(0));
board[0][1] = 1;
console.log(board);
ggorlen
  • 44,755
  • 7
  • 76
  • 106