Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

95
Vistas
Recursive function not returning correct array

I have a function that I'm using to build an array-based grid for a game. It takes in a "blank" 8x8 array as follows:

const initialBoardState = [
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']]
]

I've written a function generateBoard to assign ['O'] at two random coordinates on the array.

Simply put, the function adds a single ['O'], then calls itself again with the intention of adding a second ['O'].

There is a count variable that counts how many times the function is executed. Because I only want two ['O'], the function terminates when count>1

However, the function is returning a grid with only one ['O']. Thoughts as to what I've done wrong?

Function:

let xRandomValue;
let yRandomValue;
let coordinates = [];

const generateBoard = (board) => {
  let count = 0
   xRandomValue = Math.floor(Math.random() * 8);
   yRandomValue = Math.floor(Math.random() * 8);

  for (let i = 0; i < board.length; i++) {
    if (i === yRandomValue) {
      for (let j = 0; j < board[yRandomValue].length; j++) {
        if (j === xRandomValue) {
          board[yRandomValue][xRandomValue] = ["O"];
        }
      }
    }
  }
  coordinates.push(xRandomValue)
  coordinates.push(yRandomValue)
  count++
  if(count>1){
    generateBoard(board)
  }
  return board;
};


console.log(generateBoard(initialBoardState))
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda