Sudoku

Description


Sudoku is a number-placement puzzle. The objective is to fill a 9 × 9 grid with digits so that each column, each row, and each of the nine 3 × 3 sub-grids that compose the grid contains all of the digits from 1 to 9.

This algorithm should check if the given grid of numbers represents a correct solution to Sudoku.

Example

For the first example below, the output should be true. For the other grid, the output should be false: each of the nine 3 × 3 sub-grids should contain all of the digits from 1 to 9.

Input/Output

  • [execution time limit] 4 seconds (js)

  • [input] array.array.integer grid

A matrix representing 9 × 9 grid already filled with numbers from 1 to 9.

  • [output] boolean

true if the given grid represents a correct solution to Sudoku, false otherwise.

[JavaScript (ES6)] Syntax Tips

1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
    console.log("This prints to the console when you Run Tests");
    return "Hello, " + name;
}

Solution


1
2
3
4
5
6
7
8
9
10
11
12
13
function sudoku(grid) {
  return grid.every((row, i)=>{
      return row.every((el,j)=>{
          return grid.every((r,k)=>{
              return (i == k || el !== grid[k][j]) &&
                  (j == k || el !== grid[i][k]);
          });
      });
  }) && [0,1,2].every((i)=>[0,1,2].every(j=>{
      var tmp = grid.slice(i*3,i*3+3).map(r=>r.slice(3*j, 3*j+3));
      return tmp.reduce((a,b)=>a.concat(b)).filter((el,id,self)=>self.indexOf(el)===id).length === 9;
  }));
}