DEV Community

loading...

Discussion on: Checking Sudoku with Functional JavaScript

Collapse
kepta profile image
Kushan Joshi • Edited

Here is how I would solve this:

const range = (length) => Array.from({ length }, (_, k) => k);

// Returns a total of 27 arrays [ row0, col0, square0, ...., row8, col8, square8]
function getArrays(sudoku) {
  const toXY = (i) => ({ x: Math.floor(i / 3), y: i % 3 });
  const getRow = (i) => sudoku[i];
  const getCol = (i) => range(9).map((cell) => sudoku[cell][i]);
  const getSquare = (i) =>
    range(9).map(
      (cell) =>
        sudoku[3 * toXY(i).x + toXY(cell).x][3 * toXY(i).y + toXY(cell).y]
    );
  return range(9).flatMap((i) => [getRow(i), getCol(i), getSquare(i)]);
}

// check if only numbers 1 to 9 are used in an array
const validateArray = (array) => {
  const validSet = new Set(range(9).map((i) => i + 1));
  return array.every((number) => validSet.has(number));
};

const checkSudoku = (sudoku) => getArrays(sudoku).every(validateArray);

Now this is not "my solution is better than yours", it is more of a - "different solutions to the same problem". We all are here to learn! I learned a bit from you and I really hope you learn something new from me too<3.

Please don't hesitate to ask any question!