Skip to content

Instantly share code, notes, and snippets.

@brybrophy
Last active August 28, 2018 19:53
Show Gist options
  • Select an option

  • Save brybrophy/ad3942e699bb9c6700c31efad38455a0 to your computer and use it in GitHub Desktop.

Select an option

Save brybrophy/ad3942e699bb9c6700c31efad38455a0 to your computer and use it in GitHub Desktop.

Revisions

  1. brybrophy revised this gist Aug 28, 2018. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion sudoku2.js
    Original file line number Diff line number Diff line change
    @@ -61,7 +61,7 @@ function validateSubGrids(grid) {

    for (let i = 0; i < grid.length; i += 3) {
    for (let j = 0; j < grid.length; j += 3) {
    subGrid.push(getSubGridRow(grid, i, j));
    subGrids.push(getSubGridRow(grid, i, j));
    }
    }

  2. brybrophy created this gist Aug 28, 2018.
    69 changes: 69 additions & 0 deletions sudoku2.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,69 @@
    function sudoku2(grid) {
    return (
    validateRows(grid) &&
    validateRows(rotateGrid(grid)) &&
    validateSubGrids(grid)
    );
    }

    // Validate each row.
    function validateRows(grid) {
    let valid = true;

    for (const row of grid) {
    if (!valid) {
    break;
    }

    let dict = {};

    row.filter(item => item !== ".").forEach(item => {
    if (dict[item]) {
    valid = false;
    } else {
    dict[item] = 1;
    }
    });
    }

    return valid;
    }

    // Rotate the grid by 90deg.
    // This allows us to then validate the columns as rows.
    function rotateGrid(grid) {
    return grid.map((inArr, i) => {
    const newArr = [];

    for (const arr of grid) {
    newArr.push(arr[i]);
    }

    return newArr.reverse();
    });
    }

    // Convert each 3x3 grid into a row of 9.
    // This allows us to validate the sub grids as rows.
    function validateSubGrids(grid) {
    const subGrids = [];
    const getSubGridRow = function(grid, curRow, curCol) {
    const currentSubGrid = [];

    for (let row = curRow; row < curRow + 3; row++) {
    for (let col = curCol; col < curCol + 3; col++) {
    currentSubGrid.push(grid[row][col]);
    }
    }

    return currentSubGrid;
    };

    for (let i = 0; i < grid.length; i += 3) {
    for (let j = 0; j < grid.length; j += 3) {
    subGrid.push(getSubGridRow(grid, i, j));
    }
    }

    return validateRows(subGrids);
    }