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

208
Views
Complete the algorithm for generating Sudoku puzzles

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;
}

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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.

about 4 years ago · Juan Pablo Isaza Report
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!