Untitled
unknown
plain_text
8 days ago
2.3 kB
3
Indexable
Never
#define ROW_SIZE 9 #define COL_SIZE 9 // return true if its valid set, return false if we've seen a duplicate bool validateSet(uint32_t* current_set, char new_val) { int number = new_val - '1'; // "5" - "1" = 4 (more of an index) bool seen = (*current_set >> number) & 0x1; // 0x000010000 >> 4 = 0x1 // 0x000000000 | 0x000010000 = 0x000010000 *current_set = *current_set | (0x1 << number); // 0x000010000 = 1 << 4 return !seen; } bool isColumnValid (char **board, int col_number) { uint32_t set = 0x000000000; for (int i = 0; i < COL_SIZE; i++) { char current_num = board[i][col_number]; // 5, 3, ., . if (current_num == '.') continue; bool is_valid = validateSet(&set, current_num); if (!is_valid) return false; } return true; } bool isRowValid(char** board, int row_number) { uint32_t set = 0x000000000; for (int i = 0; i < ROW_SIZE; i++) { char current_num = board[row_number][i]; // 5, 3, ., . if (current_num == '.') continue; bool is_valid = validateSet(&set, current_num); if (!is_valid) return false; } return true; } bool isSquareValid(char** board, int square_number) { // First, find the starting indices of the square // 0 -> 0,0; 1 -> 0,3; 2 -> 0,6 // 3 -> 3,0; 4 -> 3,3; 5 -> 3,6 // 6 -> 6,0; 7 -> 6,3; 8 -> 6,6 uint32_t set = 0x000000000; int row = square_number - (square_number % 3), col = (square_number % 3) * 3; for (int i = row; i <= row + 2; i++) { for (int j = col; j <= col + 2; j++) { char current_num = board[i][j]; // 5, 3, ., . if (current_num == '.') continue; bool is_valid = validateSet(&set, current_num); if (!is_valid) return false; } } return true; } bool isValidSudoku(char** board, int boardSize, int* boardColSize){ for (int i = 0; i < ROW_SIZE; i++) { bool valid_col = isColumnValid(board, i); bool valid_row = isRowValid(board, i); bool valid_square = isSquareValid(board, i); if (!(valid_col & valid_row & valid_square)) return false; } return true; }
Leave a Comment