Sudoku Validation in Ruby

Ruby @ Freshers.in

Sudoku validation is a crucial task in game development and puzzle-solving applications, ensuring that a given Sudoku board adheres to specific rules. In Ruby, writing a function to validate a 9×9 Sudoku board is essential for verifying its correctness. In this article, we’ll delve into how to implement a function in Ruby to determine the validity of a Sudoku board, considering rules such as no repetition in rows, columns, and sub-grids, with comprehensive examples and outputs provided for clarity.

Understanding Sudoku Validation Rules

Validating a Sudoku board involves ensuring that each row, each column, and each 3×3 sub-grid contains all digits from 1 to 9 without repetition.

Example: Validating Sudoku in Ruby

Let’s define a Ruby function called valid_sudoku? to determine the validity of a 9×9 Sudoku board.

def valid_sudoku?(board)
  rows = Array.new(9) { Hash.new(0) }
  cols = Array.new(9) { Hash.new(0) }
  boxes = Array.new(9) { Hash.new(0) }

  board.each_with_index do |row, i|
    row.each_with_index do |val, j|
      next if val == '.'

      box_index = (i / 3) * 3 + j / 3

      return false if rows[i][val] > 0 ||
                      cols[j][val] > 0 ||
                      boxes[box_index][val] > 0

      rows[i][val] += 1
      cols[j][val] += 1
      boxes[box_index][val] += 1
    end
  end

  true
end

# Test the function with examples
sudoku_board1 = [
  ["5","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
]

sudoku_board2 = [
  ["8","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
]

puts valid_sudoku?(sudoku_board1)   # Output: true
puts valid_sudoku?(sudoku_board2)   # Output: false

Output:

true
false
Author: user