Help? Solved "Valid Sudoku" but dissatisfied with a magic number usage

The problem: https://leetcode.com/problems/valid-sudoku/

 
There was a natural way I wanted to traverse the board, which was that rows, columns, and boxes were traversed independently but within the same nested loop.

So the row number is always board[i][j]
The column number is always board[j][i]
And the box number is always <magical modulus formula>

I could calculate the i-th row for the box, but I ran into a dead-end with the j-th index, and saw that if I modded 12, it kept the pattern I wanted:

0,1,2, 0,1,2, 0,1,2, 3,4,5, 3,4,5, 3,4,5, 6,7,8, 6,7,8, 6,7,8, 0,1,2, 0,1,2, 0,1,2 ...

For example, when checking the 4th row (i=3), it checks the 4th column (j=3), and the 4th box counting from top to the right and wrapping back.

The % 12 isn't required from i=0 though i=2. But with i=3 and beyond it works and is needed.

(Also I'm choosing to just interpret '.' as 0 with its own index in my set that tracks dupes, since the number being checked is different in the grid.)

# @param {Character[][]} board
# @return {Boolean}
def is_valid_sudoku(board)
  set = [9]+[1]*9
  
  for i in 0..8
    row, col, box = set.dup, set.dup, set.dup
    
    for j in 0..8
      box_i = (i/3) * 3 + (j/3)
      box_j = ((i/3*3) + (j%3) + (i*3)) % 12
      row_num = board[i][j].to_i
      col_num = board[j][i].to_i
      box_num = board[box_i][box_j].to_i
      row[row_num] -= 1
      col[col_num] -= 1
      box[box_num] -= 1
      return false if row[row_num] < 0
      return false if col[col_num] < 0
      return false if box[box_num] < 0
    end
  end
  
  true
end
Comments (0)