Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

99
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda