Home > Back-end >  Sudoku solution validator on Codewars
Sudoku solution validator on Codewars

Time:08-15

This code in JavaScript works, but can somebody explain to me what board[3][8] != board[8][3] does or to be more precise how does this peace of code checks if rows and columns numbers are not repeated. Thank you!

function validSolution(board) {

  let count0 = 0;
  let count1 = 0;
  let count2 = 0;
  let count3 = 0;
  let count4 = 0;
  let count5 = 0;
  let count6 = 0;
  let count7 = 0;
  let count8 = 0;
  let count9 = 0;

  for (let i = 0; i < board.length; i  ) {
  count0  = board[i][0];
  count1  = board[i][1];
  count2  = board[i][2];
  count3  = board[i][3];
  count4  = board[i][4];
  count5  = board[i][5];
  count6  = board[i][6];
  count7  = board[i][7];
  count8  = board[i][8];
  }
  return (count0 === 45 && count1 === 45 && count2 === 45 && count3 === 45 
   && count4 === 45 && count5 === 45 && count6 === 45 && count7 === 45 &&
   count8 === 45 && board[3][8] != board[8][3] );
}

CodePudding user response:

That additional check does make sure there's at least some variation in the numbers on the board, but it does not make sure the solution is actually valid.

Take this board for example:

let board = [
 [5,5,5,5,5,5,5,5,5],
 [5,5,5,5,5,5,5,5,5],
 [5,5,5,5,5,5,5,5,5],
 [4,5,5,5,5,5,5,5,6],
 [5,5,5,5,5,5,5,5,5],
 [6,5,5,5,5,5,5,5,4],
 [5,5,5,5,5,5,5,5,5],
 [5,5,5,5,5,5,5,5,5],
 [5,5,5,5,5,5,5,5,5]
];

All of these rows have totals of 45, and grid positions [3][8] and [8][3] are not equal. validSolution incorrectly considers this board to be a valid solution...

I came up with another validation method:

function validSolution(board) {
  var boardx = board.map(x => new Set(x).size == 9 ? x.reduce((a,b) => a b, 0) : 0);
  var boardy = board[0].map((x,col,b) => board.map(x => x[col])).map(x => new Set(x).size == 9 ? x.reduce((a,b) => a b, 0) : 0);
  return new Set(boardx).size == 1 && boardx[0] == 45 && new Set(boardy).size == 1 && boardy[0] == 45;
}

A little explanation:

boardx will calculate the sum of each row (x.reduce((a,b) => a b, 0)) if it consists of 9 unique values (new Set(x).size == 9 1)

boardy will calculate the sum of each column, but first it has to 'rotate' the grid (board[0].map((x,col,b) => board.map(x => x[col])), followed by the same method we did earlier.

For a valid board, boardx and boardy should both consist of 9 elements of value 45. So, we check if both boardx and boardy only have 1 unique value, and that value is 45


1 The Set object can only store unique values, therefore it's a perfect tool to quickly check the number of unique elements in an array.

CodePudding user response:

I don't think that [3][8] != [8][3] is necessary? In sudoku those two cells don't matter to each other.

  • Related