-2

I have a code below but there's a problem with the current implementation in the function entriesToDel. It will not always produce n distinct co-ordinates to be turned blank in a puzzle. It should always produce an array with n elements consisting of two-element arrays storing the co-ordinates of an element and every element of the output should produce distinct co-ordinates but I'm not sure how to do that as I'm quite new to this.

// a function to randomly select n (row,column) entries of a 2d array
function entriesToDel(n) {
        var array = [];
        for (var i = 0; i < n; i++) {
            var row = Math.round(3*Math.random());
            var col = Math.round(3*Math.random());
            array.push([row,col]);
        }
        return array;
}
LofiChill
  • 1
  • 2
  • 2
    Create an array with all possible coordinates. [Shuffle it](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array). Take the first n elements. – James Mar 07 '22 at 18:04

1 Answers1

0

A simple solution would be using a set instead of an array and add random numbers until you have enough unique entries.

In case you dont know what a set is: A set works similarly to an array, but it does not allow for duplicates (duplicates will be ignored). (It also does not give elements a fixed position; you can't access an entry of a set with set[i])

const size = 3 // define size of grid in variable

function entriesToDel(n) {

 // create set of positions
 const positions = new Set() // create set
 while(positions.size < n) { // repeat until set has enough entries
  positions.add(Math.floor((size ** 2) * Math.random())) // add random position (duplicates will be ignored by the set)
 }

 // convert set of positions to array of coordinates
 const cords = []
 for(const position of positions) { // iterate through positions
  // convert position to column and row and add to array
  const row = Math.floor(position / size)
  const column = position % size
  cords.push([row, column])
 }

 return cords

}

This solution is nice and simple. An issue is that if you're really unlucky, the random number generator will keep on generating the same number, resulting in a possibly very long calculation time. If you want to exclude this (very unlikely) possibility, it would be reasonably to use the more complex solution provided by James.

dtpnftscdsatp
  • 273
  • 1
  • 11