Thread: Sudoku Program in "C"

  1. #1
    Registered User
    Join Date
    Oct 2014
    Posts
    11

    Sudoku Program in "C"

    Hi guys, this is my first post. I felt like sharing what I've been working on, a program that can solve a sudoku puzzle. Feel free to use, improve and share back! Cheers!

    sudoku.c
    Attached Files Attached Files

  2. #2
    Tweaking master Aslaville's Avatar
    Join Date
    Sep 2012
    Location
    Rogueport
    Posts
    528
    Is this working for you?

    Code:
    void try_for_number(int rand_r, int rand_c, int rand_number)
    	{	
    		int empty = 0;
    		int temp_var[9][x];
    		int count = 0;

  3. #3
    Registered User
    Join Date
    Oct 2014
    Posts
    11
    Aslaville, I meant to comment those lines except the function header and <code>int empty = 0;</code>

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    For starters, many people are leery of downloading random files on the internet. Posting your code, with nice, proper formatting and indentation, in [code][/code] tags would be good. To make it look nice on the forum, it's usually easier to use spaces for indentation instead of tabs. Most good editors can convert quite easily, so you don't have to do it by hand.

    Next, it would help if you included any necessary header files or other .c files. I can't compile without sudoku.h. Again, nicely formatted/indented in [code][/code] tags. Along the same lines, only include what you need. You have no need for conio.h, you don't use any of it's functions. You should avoid that header in general, since it is old and outdated, and it's non-portable, so it wont work on many modern systems.

    Then, make sure you compile with warnings set to maximum. For GCC and MinGW, use the -Wall flag, otherwise check your compiler documentation. I commented out conio.h and sudoku.h, compiled and got the following:
    Code:
    $ make sudoku
    gcc -Wall -ggdb3 -pedantic -std=gnu99 -O0 -o sudoku sudoku.c -lm -lpthread -lrt
    sudoku.c: In function ‘put_number’:
    sudoku.c:289:15: warning: unused variable ‘l’ [-Wunused-variable]
    sudoku.c:289:12: warning: unused variable ‘k’ [-Wunused-variable]
    sudoku.c:289:9: warning: unused variable ‘j’ [-Wunused-variable]
    sudoku.c: In function ‘set_to_value_or_space’:
    sudoku.c:557:10: warning: unused variable ‘response’ [-Wunused-variable]
    sudoku.c: In function ‘put_number’:
    sudoku.c:355:1: warning: control reaches end of non-void function [-Wreturn-type]
    sudoku.c: In function ‘test_boxes’:
    sudoku.c:231:1: warning: control reaches end of non-void function [-Wreturn-type]
    • Get rid of all unused variables. They just clutter things up.
    • If you don't want to return a value from a function, declare it with void return type, otherwise you must always return a valid value. Failure to do so results in undefined behavior (see Question 11.33 -- that FAQ is an excellent resource, spend some time perusing it when you can). Note, for line 231, it looks like you do return a variable in all cases, but the compiler can't tell for sure. You only use if and else if (no plain else at the end as a "default" or "catch-all" case), meaning the 9 returns only happen when some run-time condition is met; the compiler just can't know whether that is guaranteed to happen all the time. So it is warning you that there's is a chance your function wont return a value.
    • If you're going to hard-code the initial value of the puzzle, then use an array intializer. See below
    • Global variables are evil, read this: Global Variables Are Bad. Declare them in an appropriate function and pass them as needed.
    • Magic numbers are also evil. Define constants with good, descriptive names, and use them everywhere.
    • You use descriptive names, but sometimes they seem pointlessly long. Why sudoku_second_box instead of second_box? But see the next point.
    • A 2-d array where one dimension has only 1 entry is silly. Just make a 1-D array. However, when you find yourself naming variables foo1, foo2, etc, or first_foo, second_foo, etc, you should think adding an array dimension. Thus, you could simply declare int box[NUM_BOXES][NUMS_PER_BOX], and use a loop (maybe with a few math tricks like / divide and % modulus) to populate, process, print, etc all the boxes. Similar techniques could apply to the column and row processing as well.


    Array initializer
    Code:
    int sudoku = {
        {0, 0, 1, 0, 0, 0, 8, 0, 0}, // row 1
        {0, 5, 0, 0, 1, 0, 0, 4, 0}, // row 2
    ...
    };
    You could either do that when you declare sudoku in main, or you could declare it in an init function and use a loop to assign to the game board.


    Sorry, gotta run, but that should give you some ideas.

  5. #5
    Registered User
    Join Date
    Oct 2014
    Posts
    11
    Thank you very much, Anduril462. I intended attaching the whole project, but the file embedder didn't recognize the .dev file (I use Dev C++), but I have learnt my lesson, I will post the code next time.
    I included
    Code:
    <conio.h>
    because I wanted to use the
    Code:
    clrscr()
    function in it, but true to what you said, its quite obsolete.
    I tried this:


    1
    2
    3
    4
    5
    int sudoku = {
    {0, 0, 1, 0, 0, 0, 8, 0, 0}, // row 1
    {0, 5, 0, 0, 1, 0, 0, 4, 0}, // row 2
    ...
    };



    But I got compiler-specific issues (I was cross-compiling), when I tried using the
    Code:
    sudoku[9][9]
    array, such as 'index' and 'maximum' values
    mismatch, especially with
    MS Visual Studio. I found that a 'for loop' was more
    efficient and a function for putting in values just like you suggested.

    <quote>You could either do that when you declare sudoku in main, or you could declare it in an init function and use a loop to assign to the game board.</quote>

    I'm going to try my best to avoid global variables where possible. I have acknowledged all your corrections, once again thank you.

    Last edited by Suigen; 10-02-2014 at 02:33 AM.

  6. #6
    Registered User
    Join Date
    Oct 2014
    Posts
    11
    I hope this editor translates this out well, though I previewed it. Here's the code once again:

    Code:
    /*            
            You may delete this comment if you feel you do not need it.
            
                This program is available for use under the General Public License and the GNU License.
            You may copy, edit, cut, use any part or all of this source file or rewrite the code
            contained therein, and republish it, as long as you do not use it for commercial purposes,
            so that you may give back to the community.
            -----------------------------------------------------------------------------------------
            |                                                                                        |
            |    Sudoku Calculator                                                                    |
            |    =============================================================================        |
            |        This program, aptly named, attempts to solve a sudoku puzzle already defined     |
            |     in it.                                                                                |
            |        I used a 9 x 9 array named 'sudoku[9][9]' to store the values of the sudoku      |
            |    puzzle. The sudoku puzzle in question originally has 23 'exposed' cells. An            |
            |    being solved.                                                                        |
            |                                                                                       |
            |    Go through the program to understand how it works. The code has hopefully been        |
            |    comprehensively commented.                                                            |
            |                                                                                        |
            |    Note:                                                                                 |
            |    =====                                                                                |
            |        My program's best answer so far is 47 'discovered cells', while obeying the     |
            |    rules of sudoku, which if you add to 23 'exposed cells ' brings a total of 70         |
            |    'known' cells. After this, it meets a dead end.                                        |
            |        I tried to make it loop, when it meets a dead end, by making the function call    |
            |    itself (iteration), reset the puzzle array values, and try a different route,        |
            |    but that isn't still smart enough, because chances are high, it wil meet a dead end    |
            |    again (I ran it in several instances). You can put any of the numbers 1 - 9 in 58    |
            |    (81 - 23) cells in different ways in any order. There are ((9 ^ 58) - x) wrong         |
            |    ways, where x is the number of right ways and x is not very big, because of         |
            |    restrictions  (i.e Rules of Sudoku).                                                |
            |        My knowlede(and experience) limits me, so I will garner more information on how    |
            |    to solve difficult puzzles like the one I'm trying to solve and learn 'pointers'    |
            |    properly for larger memory allocation and 'data structures' so that I can handle    |
            |    data properly through the implementation of 'lists', 'queues' and the like and come    |
            |    up with a better algorithm for solving any sudoku puzzle. You can try to see if you |                        
            |    can come up with a better solution.                                                    |
            |        You can compile and run this at any time. Cheers :D    (Use 'Ctrl + C' to break)    |                                    |
            -----------------------------------------------------------------------------------------                                                                                        |
    
    
    */
    
    
    #include <stdio.h>
    #include <stdlib.h>
    
    
    // Most traditional c compilers don't support the boolean type, hence the type definition below.
    
    
    #define TRUE 1       // Definition of constants for the boolean datatype.
    #define FALSE 0
    typedef int boolean;
    
    
    // Functions' Prototypes
    /**********************************************************************/
    int main(void);                                                          //
    void my_sudoku_func(void);                                              //
    void reset(void);                    // List of all the functions,     //
    void flush_cells(void);                // I used in this program.        //
    void set_exposed_cells(void);                                          //
    void set_to_value_or_space();                                          //
    void set_rows(void);                                                  //
    void set_columns(void);                                                  //
    void set_boxes(void);                                                 //
    void set_all(void);                                                      //
    void missing_numbers(void);                                           //
    int put_number(void);                                                  //
    void try_for_number(int, int, int);                                      //
    boolean text_boxes(int);                                              //
    /*********************************************************************/
    
    
    // Declarations of integer arrays to store values in the rows of the Sudoku.
    int first_row[1][9], second_row[1][9], third_row[1][9],
        fourth_row[1][9], fifth_row[1][9], sixth_row[1][9],
        seventh_row[1][9], eight_row[1][9], ninth_row[1][9];
    
    
    // Declarations of integer arrays to store values in the columns of the Sudoku.
    int first_column[9][1], second_column[9][1], third_column[9][1],
        fourth_column[9][1], fifth_column[9][1], sixth_column[9][1],
        seventh_column[9][1], eight_column[9][1], ninth_column[9][1];
    
    
    // Declarations of integer arrays to store values in the sub-grids (boxes) of the Sudoku.
    int first_box[1][9], second_box[1][9], third_box[1][9],
        fourth_box[1][9], fifth_box[1][9], sixth_box[1][9],
        seventh_box[1][9], eight_box[1][9], ninth_box[1][9];
    int sudoku[9][9]; 
    
    
    // The function 'flush_cells()' below prevents the integer array 'sudoku[9][9]' stated above from holding 
    // garbage values by initializing the elements in the array to zero(0).
    
    
    void flush_cells()
        {
            int i, j ;
    
    
            for (i = 0; i < 9; i++)
                {
                    for (j = 0; j < 9; j++)
                        {
                            sudoku[i][j] = 0;
                        }
                }
        }
    
    
    // This function sets the values of the 'exposed cells' of the Soduku puzzle in the integer array 'sudoku[9][9]'.
    void set_exposed_cells()
        {
            /***First Row***/
            sudoku[0][2] = 1;
            sudoku[0][6] = 8;
    
    
            /***Second Row****/
            sudoku[1][1] = 5;
            sudoku[1][4] = 1;
            sudoku[1][7] = 4;
    
    
            /***Third Row****/
            sudoku[2][3] = 2;
            sudoku[2][8] = 7;
    
    
            /***Fourth Row****/
            sudoku[3][2] = 7;
            sudoku[3][5] = 5;
            sudoku[3][7] = 8;
    
    
            /***Fifth Row****/
            sudoku[4][0] = 4;
            sudoku[4][4] = 6;
            sudoku[4][8] = 9;
    
    
            /***Sixth Row****/
            sudoku[5][1] = 2;
            sudoku[5][3] = 4;
            sudoku[5][6] = 5;
    
    
            /***Seventh Row****/
            sudoku[6][0] = 3;
            sudoku[6][5] = 7;
    
    
            /***Eight Row****/
            sudoku[7][1] = 7;
            sudoku[7][4] = 2;
            sudoku[7][7] = 9;
    
    
            /***Ninth Row****/
            sudoku[8][2] = 4;
            sudoku[8][6] = 1;
        }
    
    
    // This function tests to see if the suggested value from 'rand_number' is equal to any element in each of the boxes.
    boolean test_boxes(int rand_r, int rand_c, int rand_number)
        {
            set_all(); // This sets all rows, columns, and boxes
            
            // Check first box.
            if (((rand_r >= 0) && (rand_r < 3)) && ((rand_c >= 0) && (rand_c < 3)))
                {
                    return ((rand_number == first_box[0][0]) || (rand_number == first_box[0][1]) || (rand_number == first_box[0][2]) ||
                            (rand_number == first_box[0][3]) || (rand_number == first_box[0][4]) || (rand_number == first_box[0][5]) ||
                            (rand_number == first_box[0][6]) || (rand_number == first_box[0][7]) || (rand_number == first_box[0][8]));
                }
                
            // Check second box.            
            else if (((rand_r >= 0) && (rand_r < 3)) && ((rand_c >= 3) && (rand_c < 6)))
                  {
                    return((rand_number == second_box[0][0]) || (rand_number == second_box[0][1]) || (rand_number == second_box[0][2]) ||
                           (rand_number == second_box[0][3]) || (rand_number == second_box[0][4]) || (rand_number == second_box[0][5]) ||
                           (rand_number == second_box[0][6]) || (rand_number == second_box[0][7]) || (rand_number == second_box[0][8]));
                }
                
            // Check third box.    
            else if (((rand_r >= 0) && (rand_r < 3)) && ((rand_c >= 6) && (rand_c < 9)))
                {
                    return((rand_number == third_box[0][0]) || (rand_number == third_box[0][1]) || (rand_number == third_box[0][2]) ||
                           (rand_number == third_box[0][3]) || (rand_number == third_box[0][4]) || (rand_number == third_box[0][5]) ||
                            (rand_number == third_box[0][6]) || (rand_number == third_box[0][7]) || (rand_number == third_box[0][8])); 
                }
            
            // Check fourth box.
            else if (((rand_r >= 3) && (rand_r <6)) && ((rand_c >= 0) && (rand_c < 3)))
                {
                    return((rand_number == fourth_box[0][0]) || (rand_number == fourth_box[0][1]) || (rand_number == fourth_box[0][2]) ||
                            (rand_number == fourth_box[0][3]) || (rand_number == fourth_box[0][4]) || (rand_number == fourth_box[0][5]) ||
                            (rand_number == fourth_box[0][6]) || (rand_number == fourth_box[0][7]) || (rand_number == fourth_box[0][8]));
                }
            
            // Check fifth box.
            else if (((rand_r >= 3) && (rand_r < 6)) && ((rand_c >= 3) && (rand_c < 6)))
                {            
                    return((rand_number == fourth_box[0][0]) || (rand_number == fourth_box[0][1]) || (rand_number == fourth_box[0][2]) ||
                             (rand_number == fourth_box[0][3]) || (rand_number == fourth_box[0][4]) || (rand_number == fourth_box[0][5]) ||
                             (rand_number == fourth_box[0][6]) || (rand_number == fourth_box[0][7]) || (rand_number == fourth_box[0][8]));
                }
                    
            // Check sixth box.        
            else if (((rand_r >= 3) && (rand_r < 6)) && ((rand_c >= 6) && (rand_c < 9)))
                {
                    return((rand_number == sixth_box[0][0]) || (rand_number == sixth_box[0][1]) || (rand_number == sixth_box[0][2]) ||
                            (rand_number == sixth_box[0][3]) || (rand_number == sixth_box[0][4]) || (rand_number == sixth_box[0][5]) ||
                            (rand_number == sixth_box[0][6]) || (rand_number == sixth_box[0][7]) || (rand_number == sixth_box[0][8]));
                }
            
            // Check seventh box.    
            else if (((rand_r >= 6) && (rand_r < 9)) && ((rand_c >= 0) && (rand_c < 3)))
                {    
                    return((rand_number == seventh_box[0][0]) || (rand_number == seventh_box[0][1]) || (rand_number == seventh_box[0][2]) ||
                            (rand_number == seventh_box[0][3]) || (rand_number == seventh_box[0][4]) || (rand_number == seventh_box[0][5]) ||
                           (rand_number == seventh_box[0][6]) || (rand_number == seventh_box[0][7]) || (rand_number == seventh_box[0][8]));
                }
            
            // Check eight box.
            else if (((rand_r >= 6) && (rand_r < 9)) && ((rand_c >= 3) && (rand_c < 6)))
                {                
                    return((rand_number == eight_box[0][0]) || (rand_number == eight_box[0][1]) || (rand_number == eight_box[0][2]) ||
                            (rand_number == eight_box[0][3]) || (rand_number == eight_box[0][4]) || (rand_number == eight_box[0][5]) ||
                           (rand_number == eight_box[0][6]) || (rand_number == eight_box[0][7]) || (rand_number == eight_box[0][8]));
                }
                
            //Check ninth box.
            else if (((rand_r >= 6) && (rand_r < 9)) && ((rand_c >= 6) && (rand_c < 9)))
                {
                    return((rand_number == ninth_box[0][0]) || (rand_number == ninth_box[0][1]) || (rand_number == ninth_box[0][2]) ||
                            (rand_number == ninth_box[0][3]) || (rand_number == ninth_box[0][4]) || (rand_number == ninth_box[0][5]) ||
                           (rand_number == ninth_box[0][6]) || (rand_number == ninth_box[0][7]) || (rand_number == ninth_box[0][8]));
                }
        }
    
    
    // This function tries to solve the sudoku puzzle by suggesting numbers from 1 - 9, as long as those numbers 
    // ar not used by any row, column or box
    
    
    void try_for_number(int rand_r, int rand_c, int rand_number)
        {    
            int empty = 0;
        
            // This ensures that the random value we generate with 'rand()' are not signed (ie, they cannot be negative)
            // and it changes with time.
            
            srand((unsigned)time(0));    
            
            set_all();
        
                if (sudoku[rand_r][rand_c] == empty)
                    {
                        do
                            {    
                                set_exposed_cells();
                                set_all();
                                rand_r = (rand() % 9);
                                rand_c = (rand() % 9);
                                rand_number = (rand() % 9) + 1;
    
    
                            } while( // Test entire row for similar value with 'rand_number'.
                                    ((rand_number == sudoku[rand_r][0]) || (rand_number == sudoku[rand_r][1]) || (rand_number == sudoku[rand_r][2]) ||
                                        (rand_number == sudoku[rand_r][3]) || (rand_number == sudoku[rand_r][4]) || (rand_number == sudoku[rand_r][5]) ||
                                     (rand_number == sudoku[rand_r][6]) || (rand_number == sudoku[rand_r][7]) || (rand_number == sudoku[rand_r][8])) ||
                                     //Test entire columnrow for similar value with 'rand_number'.
                                    ((rand_number == sudoku[0][rand_c]) || (rand_number == sudoku[1][rand_c]) || (rand_number == sudoku[2][rand_c]) ||
                                     (rand_number == sudoku[3][rand_c]) || (rand_number == sudoku[4][rand_c]) || (rand_number == sudoku[5][rand_c]) ||
                                     (rand_number == sudoku[6][rand_c]) || (rand_number == sudoku[7][rand_c]) || (rand_number == sudoku[8][rand_c])) || (test_boxes(rand_r, rand_c, rand_number) == 1));
                    }
                    set_exposed_cells();
                    set_all();
                    
                    if( // Test entire row for similar value with 'rand_number'.
                        ((rand_number != sudoku[rand_r][0]) && (rand_number != sudoku[rand_r][1]) && (rand_number != sudoku[rand_r][2]) &&
                         (rand_number != sudoku[rand_r][3]) && (rand_number != sudoku[rand_r][4]) && (rand_number != sudoku[rand_r][5]) &&
                         (rand_number != sudoku[rand_r][6]) && (rand_number != sudoku[rand_r][7]) && (rand_number != sudoku[rand_r][8]))
                             &&
                        //Test entire columnrow for similar value with 'rand_number'.
                        ((rand_number != sudoku[0][rand_c]) && (rand_number != sudoku[1][rand_c]) && (rand_number != sudoku[2][rand_c]) &&
                         (rand_number != sudoku[3][rand_c]) && (rand_number != sudoku[4][rand_c]) && (rand_number != sudoku[5][rand_c]) &&
                         (rand_number != sudoku[6][rand_c]) && (rand_number != sudoku[7][rand_c]) && (rand_number != sudoku[8][rand_c])) && (test_boxes(rand_r, rand_c, rand_number) != 1))
                            {
                                // If no other cell has similar value with 'rand_number', then assign value of 'rand_number' to cell in question.
                                //sudoku[rand_r][rand_c] = rand_number;      
                                sudoku[rand_r][rand_c] = rand_number;
                                set_exposed_cells();
                                set_all(); // This calls 'set_all()' which updates all rows, columns and boxes of the Sudoku table. 
                            }
        }
    
    
    int put_number()
        {
            int j, k, l, count, tries = 0;
            int sum[9]= {0, 0, 0, 0, 0, 0, 0, 0, 0};
            long int i;
            int rand_r = 0; // To hold row number.
            int rand_c = 0;    // To hold column value.
            int rand_number = 0; // Arbitrary value from 1 to 9.
                    
            srand((unsigned)time(0));
            
            //reset();
            set_all();
    
    
            for (i = 0; i < (9 ^ 58); i++) // First for loop
                {
                    rand_r = (rand() % 9);
                    rand_c = (rand() % 9);
                    rand_number = (rand() % 9) + 1;
                    
                    set_all();
    
    
                    try_for_number(rand_r, rand_c, rand_number); // This calls 'try_for_number()'.                                          
                }
                
            //set_exposed_cells();
            set_all();
            set_to_value_or_space();
            
                
            for (count = 0; count < 9; count++)
                {
                    sum[0] += first_box[0][count];
                       sum[1] += second_box[0][count];
                       sum[2] += third_box[0][count];
                     sum[3] += fourth_box[0][count];
                       sum[4] += fourth_box[0][count];
                       sum[5] += sixth_box[0][count];
                       sum[6] += seventh_box[0][count];
                       sum[7] += eight_box[0][count];
                       sum[8] += ninth_box[0][count];
                }
    
    
                    if (sum[0] != 45 && sum[1] != 45 && sum[2] != 45 && sum[3] != 45 && sum[4] != 45 &&
                        sum[5] != 45 && sum[6] != 45 && sum[7] != 45 && sum[8] != 45)
                        {     
                               //reset();
                               set_all();
                            printf("....still solving...");
                            put_number();
                           }
                    else if (sum[0] == 45 && sum[1] == 45 && sum[2] == 45 && sum[3] == 45 && sum[4] == 45 &&
                              sum[5] == 45 && sum[6] == 45 && sum[7] == 45 && sum[8] == 45)
                           {    
                               printf("done!");
                               getchar();
                               return 0;
                        }
                    else
                        {    
                            printf("tried %d", ++tries);
                            printf("trying again...");
                            reset();
                            set_all();
                            put_number();
                            getchar();
                            return 0;
                        }
        }
    
    
    void set_all()
        {
            set_rows();
            set_columns();
            set_boxes();
        }
        
    //The function 'reset()' below, simply calls two other functions; 'flush_cells()' and 'set_exposed_cells()'.
    
    
    void reset()
        {
            flush_cells();
            set_exposed_cells();
        }
        
    // The function 'set_rows()' below, passes all values from the rows of the sudoku table to the array
    // variables below.
    
    
    void set_rows()
        {
                int i, j;
    
    
                for (i = 0; i < 9; i++)
                    {
                        for (j = 0; j < 9; j++)
                            {
                                if (i == 0)
                                    { first_row[i][j] = sudoku[i][j]; }
    
    
                                else if (i == 1)
                                    { second_row[i][j] = sudoku[i][j]; }
    
    
                                else if (i == 2)
                                    { third_row[i][j] = sudoku[i][j]; }
    
    
                                else if (i == 3)
                                    { fourth_row[i][j] = sudoku[i][j]; }
    
    
                                else if (i == 4)
                                    { fifth_row[i][j] = sudoku[i][j]; }
    
    
                                else if (i == 5)
                                    { sixth_row[i][j] = sudoku[i][j]; }
    
    
                                else if (i == 6)
                                    { seventh_row[i][j] = sudoku[i][j]; }
    
    
                                else if (i == 7)
                                    { eight_row[i][j] = sudoku[i][j]; }
    
    
                                else if (i == 8)
                                    { ninth_row[i][j] = sudoku[i][j]; }
                            }
                    }
        }
    
    
    // This function pass all values from the columns of the sudoku table to the array
    // variables below.
    
    
    void set_columns()
        {
                int i, j;
    
    
                for (j = 0; j < 9; j++)
                    {
                        for (i = 0; i < 9; i++)
                            {
                                if (i == 0)
                                    {  first_column[i][j] = sudoku[i][j]; }
    
    
                                else if (i == 1)
                                    { second_column[i][j] = sudoku[i][j]; }
    
    
                                else if (i == 2)
                                    { third_column[i][j] = sudoku[i][j]; }
    
    
                                else if (i == 3)
                                    { fourth_column[i][j] = sudoku[i][j]; }
    
    
                                else if (i == 4)
                                    { fifth_column[i][j] = sudoku[i][j]; }
    
    
                                else if (i == 5)
                                    { sixth_column[i][j] = sudoku[i][j]; }
    
    
                                else if (i == 6)
                                    { seventh_column[i][j] = sudoku[i][j]; }
    
    
                                else if (i == 7)
                                    { eight_column[i][j] = sudoku[i][j]; }
    
    
                                else if (i == 8)
                                    { ninth_column[i][j] = sudoku[i][j]; }
                            }
                    }
        }
    
    
    
    
    // This funtion passes values from the sub-grids(boxes) of the sudoku table to the elements of the array variables contained in it.
    void set_boxes()
        {
                    // These declarations and initializations pass all values from the sub-grids(boxes) of the
                    // sudoku table to the elements of the array variables below.
                    
                    first_box[0][0] = sudoku[0][0];
                    first_box[0][1] = sudoku[0][1];
                    first_box[0][2] = sudoku[0][2];
                    first_box[0][3] = sudoku[1][0];
                    first_box[0][4] = sudoku[1][1];
                    first_box[0][5] = sudoku[1][2];
                    first_box[0][6] = sudoku[2][0];
                    first_box[0][7] = sudoku[2][1];
                    first_box[0][8] = sudoku[2][2];
    
    
                    second_box[0][0] = sudoku[0][3];
                    second_box[0][1] = sudoku[0][4];
                    second_box[0][2] = sudoku[0][5];
                    second_box[0][3] = sudoku[1][3];
                    second_box[0][4] = sudoku[1][4];
                    second_box[0][5] = sudoku[1][5];
                    second_box[0][6] = sudoku[2][3];
                    second_box[0][7] = sudoku[2][4];
                    second_box[0][8] = sudoku[2][5];
    
    
                    third_box[0][0] = sudoku[0][6];
                    third_box[0][1] = sudoku[0][7];
                    third_box[0][2] = sudoku[0][8];
                    third_box[0][3] = sudoku[1][6];
                    third_box[0][4] = sudoku[1][7];
                    third_box[0][5] = sudoku[1][8];
                    third_box[0][6] = sudoku[2][6];
                    third_box[0][7] = sudoku[2][7];
                    third_box[0][8] = sudoku[2][8];
    
    
                    fourth_box[0][0] = sudoku[3][0];
                    fourth_box[0][1] = sudoku[3][1];
                    fourth_box[0][2] = sudoku[3][2];
                    fourth_box[0][3] = sudoku[4][0];
                    fourth_box[0][4] = sudoku[4][1];
                    fourth_box[0][5] = sudoku[4][2];
                    fourth_box[0][6] = sudoku[5][0];
                    fourth_box[0][7] = sudoku[5][1];
                    fourth_box[0][8] = sudoku[5][2];
    
    
                    fifth_box[0][0] = sudoku[3][3];
                    fifth_box[0][1] = sudoku[3][4];
                    fifth_box[0][2] = sudoku[3][5];
                    fifth_box[0][3] = sudoku[4][3];
                    fifth_box[0][4] = sudoku[4][4];
                    fifth_box[0][5] = sudoku[4][5];
                    fifth_box[0][6] = sudoku[5][3];
                    fifth_box[0][7] = sudoku[5][4];
                    fifth_box[0][8] = sudoku[5][5];
    
    
                    sixth_box[0][0] = sudoku[3][6];
                    sixth_box[0][1] = sudoku[3][7];
                    sixth_box[0][2] = sudoku[3][8];
                    sixth_box[0][3] = sudoku[4][6];
                    sixth_box[0][4] = sudoku[4][7];
                    sixth_box[0][5] = sudoku[4][8];
                    sixth_box[0][6] = sudoku[5][6];
                    sixth_box[0][7] = sudoku[5][7];
                    sixth_box[0][8] = sudoku[5][8];
    
    
                    seventh_box[0][0] = sudoku[6][0];
                    seventh_box[0][1] = sudoku[6][1];
                    seventh_box[0][2] = sudoku[6][2];
                    seventh_box[0][3] = sudoku[7][0];
                    seventh_box[0][4] = sudoku[7][1];
                    seventh_box[0][5] = sudoku[7][2];
                    seventh_box[0][6] = sudoku[8][0];
                    seventh_box[0][7] = sudoku[8][1];
                    seventh_box[0][8] = sudoku[8][2];
    
    
                    eight_box[0][0] = sudoku[6][3];
                    eight_box[0][1] = sudoku[6][4];
                    eight_box[0][2] = sudoku[6][5];
                    eight_box[0][3] = sudoku[7][3];
                    eight_box[0][4] = sudoku[7][4];
                    eight_box[0][5] = sudoku[7][5];
                    eight_box[0][6] = sudoku[8][3];
                    eight_box[0][7] = sudoku[8][4];
                    eight_box[0][8] = sudoku[8][5];
    
    
                    ninth_box[0][0] = sudoku[6][6];
                    ninth_box[0][1] = sudoku[6][7];
                    ninth_box[0][2] = sudoku[6][8];
                    ninth_box[0][3] = sudoku[7][6];
                    ninth_box[0][4] = sudoku[7][7];
                    ninth_box[0][5] = sudoku[7][8];
                    ninth_box[0][6] = sudoku[8][6];
                    ninth_box[0][7] = sudoku[8][7];
                    ninth_box[0][8] = sudoku[8][8];
        }
        
    // This function displays in grids, the Sudoku table and for 'non-exposed' cells, and prints a blank space
    // in the place of array values of zero.
    void set_to_value_or_space()
        {
            int i, j, k = 0, count = 0; // Declaratioin and Initialization of variables.
            char response;
            
            set_exposed_cells(); // This calls 'set_exposed_cells' which assigns the original values of the 'exposed cells'.
    
    
                    // This for loop finds the number of exposed cells
            for (i = 0; i < 9; i++)
                {
                    for (j = 0; j < 9; j++)
                        {
                            if (sudoku[i][j] != 0) // This checks to see if the cell in question does not contains zero(0) as its value.
                                {
                                    count++;
                                }
                        }
                }
                
            // The following printf() functions prints strings and escape sequences just like in any other c program.
            
            printf("\n\nSudoku sorter: The table below has %d", count);
            printf(" exposed cells:");
            printf("\n\n\n\t\t\t    ---Original Table---\n\n");
            printf("\t\t___________________________________________");
            printf("\n\t\t  ___________   ___________   ___________ ");printf("\n");
    
    
            for (i = 0; i < 9; i++)
                {
                    k = 0;
    
    
                    printf("\t\t ");
                    printf("|   ");printf("|   ");printf("|   ");printf("| ");printf("|   ");printf("|   ");printf("|   ");printf("| ");printf("|   ");printf("|   ");printf("|   ");printf("| ");printf("\n");
    
    
                    if (k == 0)
                        {
                            printf("\t\t ");
    
    
                            for (j = 0; j < 3; j++)
                                {
                                    if (sudoku[i][j] == 0)
                                        {
                                            printf("| ");printf(" ");printf(" ");
                                        }
                                    else
                                        {
                                            printf("| %d", sudoku[i][j]);printf(" ");
                                        }
                                }
                            printf("|");
                            k += 4;
                        }
    
    
                    if (k == 4)
                        {
                            printf(" ");
    
    
                            for (j = 3; j < 6; j++)
                                {
                                    if (sudoku[i][j] == 0)
                                        {
                                            printf("| ");printf(" ");printf(" ");
                                        }
                                    else
                                        {
                                            printf("| %d", sudoku[i][j]);printf(" ");
                                        }
                                }
                            printf("|");
                            k += 4;
                        }
    
    
                    if (k == 8)
                        {
                            printf(" ");
    
    
                            for (j = 6; j < 9; j++)
                                {
                                    if (sudoku[i][j] == 0)
                                        {
                                            printf("| ");printf(" ");printf(" ");
                                        }
                                    else
                                        {
                                            printf("| %d", sudoku[i][j]);printf(" ");
                                        }
                                }
                            printf("|");
                            printf("\n\t\t |___|___|___| |___|___|___| |___|___|___|\n");
                        }
    
    
                        if (i == 2 || i == 5)
                        {
                            printf("\n");
                            printf("\t\t  ___________   ___________   ___________\t\n");
                        }
                }
            printf("\t\t___________________________________________\n\n");
        }
    
    
    void my_sudoku_func()
        {
            reset(); // This calls 'reset()' which assigns the original values of the 'exposed cells'.
            set_to_value_or_space(); // This calls 'set_to_value_or_space()' which prints out the values of the Sudoku table on the screen.
            put_number(); // This calls 'put_number()' which tries to solve the sudoku table.
        }
        
    int main()
        {
            my_sudoku_func(); // This calls 'my_sudoku_func()' which is above.
            return 0;
        }

  7. #7
    Registered User
    Join Date
    Oct 2014
    Posts
    11
    I'm sorry for the way my last post turned out, please click the code area and use the left, up, down and right arrow keys to scroll correspondingly.

  8. #8
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    I think that this program is a really good effort!

    You don't need a function prototype for main().

    I suggest that you try using "for" loops in set boxes -> And if you are not expecting any input/s to a function, you should put "void" in the braces
    i.e.
    Code:
    void set_boxes(void)
    {
      ..
    }
    int main(void)
    {
      ..
    }
    I suggest that you look into a switch statement in set_columns function

    And as a future development, I think that you should save different sudokus in a text file and randomly get one at the start of the program -> This will introduce you to file IO and random numbers
    Fact - Beethoven wrote his first symphony in C

  9. #9
    Registered User
    Join Date
    Oct 2014
    Posts
    11
    Thank you, Click Here, I'm thinking of making it accept inputs

  10. #10
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Quote Originally Posted by Suigen View Post
    Code:
    /*            
            You may delete this comment if you feel you do not need it.
            
                This program is available for use under the General Public License and the GNU License.
            You may copy, edit, cut, use any part or all of this source file or rewrite the code
            contained therein, and republish it, as long as you do not use it for commercial purposes,
            so that you may give back to the community.
    If you want to attach licensing terms I recommend you read the license you are referencing (GNU General Public License?) and include the verbatim statement if you do actually want to use that license. For example the GNU GPL generally allows redistribution as well as commercial use. I could be wrong but I also don't think it allows one to delete the license text in the derivative versions.

  11. #11
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Sorry about the array initialization stuff. I had to finish in a hurry and forgot the [][] brackets for array dimensions. It should be like the following (obviously with all the ... replaced by the correct numbers for all rows/columns). What are you cross-compiling to? Why doesn't it like arrays?
    Code:
    #define GAME_SIZE 9
    ...
    int sudoku[GAME_SIZE][GAME_SIZE] = {
        {...},
        {...},
        ...
    };
    The post looks pretty good. A few things that would help:

    • Keep lines shorter. 80 characters is a common limit, but many people find anything up to 120 easy enough to read/work with. Beyond that, it gets unwieldy.
    • Minimize indentation. Your indent style is fairly clean and consistent (it looks mostly like GNU style), but if you're going to indent for curly braces, then indent more for the enclosed block of code, I would suggest using only two spaces for each indent level. And make sure you use spaces. If you use tabs, but your editor simply "displays them as two spaces", then it still will be hard to read on the forum, and on other people's systems.


    Your set_rows and set_columns functions are unnecessarily complex.


    I see a major problem with set_rows and set_columns. You declare first_row, second_row, etc to be 1x9 arrays. That means the left index can only have one value, 0. Thus, in set_rows, when you loop from i = 0 to 8, and assign to xxxx_row[i][j], you are going out of bounds for all your arrays other than first_row. Going out of bounds results in undefined behavior (see the FAQ link from my previous post #4) -- indeed, running your program for long enough produced a seg fault on my system . You have an identical problem with second row.


    This is why I suggested possibly doing something like sudoku_rows[GAME_SIZE][GAME_SIZE]. Then, you would have a simpler loop, like
    Code:
    for (i = 0; i < GAME_SOIZ; i++) {
        for (j = 0; j < GAME_SIZE; j++) {
            sudoku_rows[i][j] = sudoku[i][j];
        }
    }
    Really though, you probably can get away with a single 1-D array of GAME_SIZE elements for your functions to analyze/solve rows, columns and boxes. As Click_here and I mentioned, a loop and a little bit of basic math with the division operator / and the modulus (remainder) operator % will help you map box elements to your array.

  12. #12
    Registered User
    Join Date
    Oct 2014
    Posts
    11
    Thank you c99tutorial, I will go through the GNU and GPL license documentation properly. Thank you Anduril462, you have been very helpful and I knew you meant "sudoku[...][...]". With your suggesting of basic math skills like the integer division and modulus operator, I should be able to come up with a bethod method for filling the "boxes". I have acknowledged all your suggestions and shall come up with a more elegant but simpler design and consequently, source code. Thank you, Click_here, I am working on a front-end for the program which will receive numerous inputs at once. Thank you everyone!
    Last edited by Suigen; 10-02-2014 at 11:58 AM. Reason: Correction

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 08-19-2012, 06:15 AM
  2. Homework help: Sudoku and "explosive recursion"
    By green_ghoul in forum C Programming
    Replies: 13
    Last Post: 11-22-2011, 11:16 PM
  3. "itoa"-"_itoa" , "inp"-"_inp", Why some functions have "
    By L.O.K. in forum Windows Programming
    Replies: 5
    Last Post: 12-08-2002, 08:25 AM
  4. "CWnd"-"HWnd","CBitmap"-"HBitmap"...., What is mean by "
    By L.O.K. in forum Windows Programming
    Replies: 2
    Last Post: 12-04-2002, 07:59 AM