Program to check is a sudoku board correct?

114 Views Asked by At

I hope someone can help me understand what I am doing wrong. this is the instruction I got:

Instructions: [code need to be in C] In this exercise, I was required to write a program that checks the correctness of a sudoku puzzle board of size N*N where the root of N is an integer. The matrix will represent the Sudoku board. The tests must be performed by a single pass on each row, column and sub-square. Note that the matrix is sent to the functions as the starting address of an array!

work process of checkSudoku: (part of the instructions) Note: Each step is at least one separate function

  • It is necessary to receive from the user a correct board size for sudoku.
  • The matrix must be initialized while receiving data from the user.
  • The matrix must be presented.
  • You must write a function that accepts the board and additional necessary variables and returns whether the board is normal A sudoku board is correct if all rows, columns and squares are correct.
  • The test result must be printed.

I am not allowed to use malloc.

Hint: the memset function defined in string.h can be used by you to reset the auxiliary array.

The problem I have: when I insert valid sudoku board it says is incorrect even when its correct.

This is my code:

#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>

// --- *** Sudoku Game *** ---

// -------------------------------------------------------------
/*
 * getBoardSize - Function to get a valid size for a square matrix from the user.
 *
 * This function prompts the user to enter a size for a square matrix. It checks
 * if the entered size is a perfect square, and if not, it asks the user to
 * choose another size until a valid one is provided.
 *
 * @return N - Valid size for a square matrix.
 */

int getBoardSize() {
    int N;
    double squareRoot;

    // Keep asking for a size until a valid one is provided
    do {
        // Prompt the user to enter a size
        printf("Enter size: ");
        scanf("%d", &N);

        // Calculate the square root of the entered size
        squareRoot = sqrt(N);

        // Check if the size is a perfect square
        if (squareRoot != (int)(squareRoot)) {
            printf("Choose another size.\n");
        }

    } while (squareRoot != (int)(squareRoot));

    // Return the valid size for a square matrix
    return N;
}
// -----------------------------------------------------------------
/*
 * initializeMatrix - Function to initialize a matrix with user-input elements.
 *
 * This function takes the number of rows, number of columns, and a 2D array
 * representing a matrix. It prompts the user to enter elements for each
 * position in the matrix.
 *
 * @param rows - Number of rows in the matrix.
 * @param cols - Number of columns in the matrix.
 * @param matrix - 2D array representing the matrix to be initialized.
 */

void initializeMatrix(int rows, int cols, int matrix[rows][cols]) {
    printf("Enter matrix elements:\n");
    // Loop through each row
    for (int i = 0; i < rows; i++) {
        // Loop through each column in the current row
        for (int j = 0; j < cols; j++) {
            // Prompt user for input and store it in the matrix
            scanf("%d", &matrix[i][j]);
        }
    }
}

// -----------------------------------------------------------------
/*
 * printMatrix - Function to print a matrix to the console.
 *
 * This function takes the number of rows, number of columns, and a pointer
 * to the matrix data. It prints the matrix in a tabular format to the console.
 *
 * @param rows - Number of rows in the matrix.
 * @param cols - Number of columns in the matrix.
 * @param matrix - Pointer to the matrix data.
 */

void printMatrix(int rows, int cols, int *matrix) {
    printf("Matrix:\n");

    // Loop through each row
    for (int i = 0; i < rows; i++) {
        // Loop through each column in the current row
        for (int j = 0; j < cols; j++) {
            // Print the current element in the matrix
            printf("%d\t", *(matrix + i * cols + j));
        }
        printf("\n");
    }
}

// -----------------------------------------------------------------
/*
 * displayMatrix - Function to handle the entire process of matrix display.
 *
 * This function prompts the user to enter the size of the matrix, creates a matrix
 * with the specified size, initializes the matrix with user input, and finally,
 * displays the matrix.
 */

void displayMatrix() {
    // Get the board size from the user
    int N = getBoardSize();

    // Create a matrix with the specified size
    int matrix[N][N];

    // Initialize the matrix with user input
    initializeMatrix(N, N, matrix);

    // Print the matrix
    printMatrix(N, N, &matrix[0][0]);  // Use printMatrix instead of displayMatrix
}

// -----------------------------------------------------------------
/*------------------------------------------------------------------
 |  CHECK IF THE SUDOKU BOARD IS VALID: ROWS, COLS, SUB-SQUAR
 -------------------------------------------------------------------*/

// Function to check if a row is correct.
bool isRowCorrect(int size, int *matrix, int row) {
    int seen[size + 1]; // Array to keep track of numbers seen
    memset(seen, 0, sizeof(seen));

    for (int j = 0; j < size; j++) {
        int num = *(matrix + row * size + j);

        if (num < 1 || num > size || seen[num] != 0) {
            return false; // Invalid number or duplicate in the row
        }

        seen[num] = 1; // Mark the number as seen
    }

    return true; // Row is correct
}

// Function to check if a column is correct.
bool isColumnCorrect(int size, int *matrix, int col) {
    int seen[size + 1]; // Array to keep track of numbers seen
    memset(seen, 0, sizeof(seen));

    for (int i = 0; i < size; i++) {
        int num = *(matrix + i * size + col);

        if (num < 1 || num > size || seen[num] != 0) {
            return false; // Invalid number or duplicate in the column
        }

        seen[num] = 1; // Mark the number as seen
    }

    return true; // Column is correct
}

// Function to check if a sub-square is correct.
bool isSubSquareCorrect(int size, int *matrix, int startRow, int startCol) {
    int seen[size + 1]; // Array to keep track of numbers seen
    memset(seen, 0, sizeof(seen));

    for (int i = startRow; i < startRow + 3; i++) {
        for (int j = startCol; j < startCol + 3; j++) {
            int num = *(matrix + i * size + j);

            if (num < 1 || num > size || seen[num] != 0) {
                return false; // Invalid number or duplicate in the sub-square
            }

            seen[num] = 1; // Mark the number as seen
        }
    }

    return true; // Sub-square is correct
}

// -----------------------------------------------------------------

// Function to check if the Sudoku board is correct.
bool isSudokuCorrect(int size, int *matrix) {
    for (int i = 0; i < size; i++) {
        if (!isRowCorrect(size, matrix, i) || !isColumnCorrect(size, matrix, i)) {
            return false; // Invalid row or column
        }
    }

    // Check each sub-square
    for (int i = 0; i < size; i += 3) {
        for (int j = 0; j < size; j += 3) {
            if (!isSubSquareCorrect(size, matrix, i, j)) {
                return false; // Invalid sub-square
            }
        }
    }

    return true; // Sudoku board is correct
}

// Function to check and print the correctness of the Sudoku board.
// Function to check and print the correctness of the Sudoku board.
void checkAndPrintSudoku() {
    // Get the board size from the user
    int N = getBoardSize();

    // Create a matrix with the specified size
    int matrix[N][N];

    // Initialize the matrix with user input
    initializeMatrix(N, N, matrix);

    // Check and print the correctness of the Sudoku board
    if (isSudokuCorrect(N, &matrix[0][0])) {
        printf("The Sudoku board is correct.\n");
    } else {
        printf("The Sudoku board is incorrect.\n");
    }

    // Print the matrix
    printMatrix(N, N, &matrix[0][0]);  // Use printMatrix instead of displayMatrix
}

// ---MAIN---------------------------------------------------------


int main() {
checkAndPrintSudoku();

    return 0;

}

This is the output, you can see the numbers I put, it suppose to say that the board is correct.

Enter size: 4
Enter matrix elements:
3
4
1
2
1
2
4
3
4
3
2
1
2
1
3
4
The Sudoku board is incorrect.
Matrix:
3       4       1       2
1       2       4       3
4       3       2       1
2       1       3       4

Thank you very much.

I tried to rewrite the code, I tried to change certain pieces of code but I couldn't get it. I even used the internet and I just can't do it. I would appreciate it if someone could find the error so I can continue.

1

There are 1 best solutions below

2
n. m. could be an AI On
for (int i = 0; i < size; i += 3) 

You forgot that the input board is K²×K², for an arbitrary K, and assumed that K is always 3.