Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

86
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!