sudoku.js

Codewars 알고리즘 풀이


Problem

  • Complete the Sudoku puzzle so that each and every row, column, and region contains the numbers one through nine only once.
    • 각 행(row), 열(column), 영역(region)에 1-9의 숫자가 한 번만 포함되도록 Sudoku 퍼즐을 완성한다.
  • If the board is valid return ‘Finished!’, otherwise return ‘Try again!’.
    • board가 유효하면 ‘Finished!’를 반환하고, 그렇지 않으면 ‘Try again!’을 반환한다.



Solution 01

function sudoku(board) {
  let sum1 = 0;
  let sum2 = 0;
  let index = 0;
  let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0];
  
  for (let i = 0; i < 9; i++) {
    for (let j = 0; j < 9; j++) {
      sum1 += board[i][j];
      sum2 += board[j][i];
      index = Math.floor(i / 3) * 3 + Math.floor(j / 3);
      arr[index] += board[i][j];
    }
    
    if (sum1 !== 45 || sum2 !== 45) {
      return 'Try again!';
    } else {
      sum1 = 0;
      sum2 = 0;
    }
  }
  
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== 45) {
      return 'Try again!';
    }
  }
  
  return 'Finished!';
}

sudoku([
  [5, 3, 4, 6, 7, 8, 9, 1, 2],
  [6, 7, 2, 1, 9, 5, 3, 4, 8],
  [1, 9, 8, 3, 4, 2, 5, 6, 7],
  [8, 5, 9, 7, 6, 1, 4, 2, 3],
  [4, 2, 6, 8, 5, 3, 7, 9, 1],
  [7, 1, 3, 9, 2, 4, 8, 5, 6],
  [9, 6, 1, 5, 3, 7, 2, 8, 4],
  [2, 8, 7, 4, 1, 9, 6, 3, 5],
  [3, 4, 5, 2, 8, 6, 1, 7, 9]
]);  // Finished!
sudoku([
  [5, 3, 4, 6, 7, 8, 9, 1, 2],
  [6, 7, 2, 1, 9, 0, 3, 4, 9],
  [1, 0, 0, 3, 4, 2, 5, 6, 0],
  [8, 5, 9, 7, 6, 1, 0, 2, 0],
  [4, 2, 6, 8, 5, 3, 7, 9, 1],
  [7, 1, 3, 9, 2, 4, 8, 5, 6],
  [9, 0, 1, 5, 3, 7, 2, 1, 4],
  [2, 8, 7, 4, 1, 9, 6, 3, 5],
  [3, 0, 0, 4, 8, 1, 1, 7, 9]
]);  // Try again!


Solution 02

function sudoku(rows) {
  let columns = [];
  let blocks = [];
  
  for (let i = 0; i < 9; i++) {
    columns[i] = [];
    
    for (let j = 0; j < 9; j++) {
      const a = Math.floor(i / 3) + Math.floor(j / 3) * 3;
      
      blocks[a] = blocks[a] || [];
      
      blocks[a].push(rows[i][j]);
      columns[i].push(rows[j][i]);
    }
  }
  
  const isValidRow = row => row.slice(0).sort((a, b) => a - b).join('') === '123456789';
  
  const isValid = rows.every(isValidRow) && columns.every(isValidRow) && blocks.every(isValidRow);
  
  return isValid ? 'Finished!' : 'Try again!';
}

sudoku([
  [5, 3, 4, 6, 7, 8, 9, 1, 2],
  [6, 7, 2, 1, 9, 5, 3, 4, 8],
  [1, 9, 8, 3, 4, 2, 5, 6, 7],
  [8, 5, 9, 7, 6, 1, 4, 2, 3],
  [4, 2, 6, 8, 5, 3, 7, 9, 1],
  [7, 1, 3, 9, 2, 4, 8, 5, 6],
  [9, 6, 1, 5, 3, 7, 2, 8, 4],
  [2, 8, 7, 4, 1, 9, 6, 3, 5],
  [3, 4, 5, 2, 8, 6, 1, 7, 9]
]);  // Finished!
sudoku([
  [5, 3, 4, 6, 7, 8, 9, 1, 2],
  [6, 7, 2, 1, 9, 0, 3, 4, 9],
  [1, 0, 0, 3, 4, 2, 5, 6, 0],
  [8, 5, 9, 7, 6, 1, 0, 2, 0],
  [4, 2, 6, 8, 5, 3, 7, 9, 1],
  [7, 1, 3, 9, 2, 4, 8, 5, 6],
  [9, 0, 1, 5, 3, 7, 2, 1, 4],
  [2, 8, 7, 4, 1, 9, 6, 3, 5],
  [3, 0, 0, 4, 8, 1, 1, 7, 9]
]);  // Try again!