Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a chessboard with two queens on it [duplicate]

Tags:

javascript

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
like image 530
grant taylor Avatar asked Sep 07 '19 21:09

grant taylor


1 Answers

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);
like image 169
ggorlen Avatar answered Sep 29 '22 07:09

ggorlen