how to populate a 3 x 3 grid randomly in java script?

I have a 2D grid of 3×3 points.

every point in this grid has an own coordinate (x,y).

The user can choose a random number between 1 and 9 as input. Depending on which number the user has chosen, random points are filled accordingly in the grid. For example, if the user selects 9, all points in the grid are always occupied. if the user selects 8, one random point is always free and so on.

has someone a tipp for me how to do that in java script?

I’ve tried it with a 2D array but that did not work. I’m absolutely new in programming. Thanks in advance!

Answer

I don’t know if this fits based on your description. The basic idea is to maintain 2 separate arrays, one array contains all of your grid cells, the other array is the remaining cells that are free to occupy. As you loop through and occupy cells, remove that cell from the free array.

const gridCells = [];
for (let i=0; i<9; i++) {
  gridCells[i] = document.getElementById('cell' + i);
}

const select = document.getElementById('select');
select.addEventListener('change', () => {
  for (let cell of gridCells) {
    cell.innerHTML = 'free';
  }
  let freeCells = [...gridCells];
  let occupyCount = parseInt(select.value, 10);
  for (let i=0; i<occupyCount; i++) {
    const occupyIndex = Math.floor(Math.random() * freeCells.length);
    freeCells[occupyIndex].innerHTML = 'occupied';
    freeCells.splice(occupyIndex, 1);
  }
});
table td {
  border: 1px solid black;
}
<label>
Pick a number:
  <select id="select">
    <option value="0">Pick a Number</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
  </select>
</label>
<table>
  <tr>
    <td id="cell0">free</td>
    <td id="cell1">free</td>
    <td id="cell2">free</td>
  </tr>
  <tr>
    <td id="cell3">free</td>
    <td id="cell4">free</td>
    <td id="cell5">free</td>
  </tr>
  <tr>
    <td id="cell6">free</td>
    <td id="cell7">free</td>
    <td id="cell8">free</td>
  </tr>
</table>