Random construction of N solved Sudoku Chessboard by program

Source: Internet
Author: User
Tags random seed shuffle how to use git

I. PSP (personal software process)

PSP1.1 Personal software Process Stages Estimated time-consuming (minutes) actual time-consuming (minutes)

Planning

Plan 30 45

· Analysis · Demand analysis (including learning new technologies) 120 140
· Code Review · Code review 20 25
· Coding · Specific code 210 230
· Coding Standard · Code specification 20 10
· Design · Specific design 30 30
· Design Review · Design Review 5 5
· Design Spec · Creating a design Document 10 15
· Estimate · Estimating the time required for a task 10 5
· Postmortem & Process Improvement Plan · Summarize 30 20
· Size Measurement · Computational effort 10 10
· Test · Testing (self-test, Debug, commit modification) 110 125
· Test Report · Test report 20 30
Total 625 690

Second, the project requirements

1. Objective: Randomly generate n solved Sudoku checkerboard matrices, and output the matrix to the ' sudoku.txt ' file under the current path after typing "xxxx.exe-c N" in the console.

2. Restrictions: N value is 0~1000000, matrix is not duplicated.

Three, the algorithm idea

1. Use backtracking to determine the fill of each number in the matrix (write the Sudomatrixgenerator function): First determine the number of the first row in the Sudoku matrix (using the random header file containing the shuffle function to 1~9 the stochastic arrangement), starting with the first digit in the second row, Try to fill in the numbers in succession, after filling in according to the rules of Sudoku feasibility judgment. If the number can be filled in, the same judgment is made on the next grid. If a lattice is in violation of the Sudoku rule for any number, then backtrack and refill the number in a block.
When a workable result is obtained, the algorithm terminates.

2. In the main function, call the Sudomatrixgenerator function as many times as you type in the parameter values, write the generated Sudoku matrix to the text file, and set the exception capture.

iv. Specific source code

#include <iostream>#include<chrono>//a sub-namespace under STD for the Duration class service Chrono::system_clock#include <random>//Shuffle random permutation function Default_random_engine#include <algorithm>//using the For_each loop#include <functional>//multiple class templates are defined#include <fstream>using namespacestd;voidSudomatrixgenerator (intNum//The generation function of the Sudoku matrix{        intfield[9][9] = {0};//randomly generates a row 1~9Auto init = [] (int* list)//automatic matching of variable types using auto{for_each (list, list+9, [=](int&i)//used to traverse the list for operation =for (int i=0;i<9;i++){i= &i-list +1;        }        ); Unsigned seed= Chrono::system_clock::now (). Time_since_epoch (). Count ();//call the current system time as the initial value of the random seed seedsShuffle (list, List +9, Default_random_engine (Seed));//generates random sequences, randomly arranging values in the list to list+9 interval    }; Init (field[0]);//initializes the first row of elements    inttrylist[9]; Init (trylist); //sequence of attempts to determine numbersAuto Judge = [&field] (intIintJintNUM)BOOL //determine if the number entered is legal    {          for(intK0); K < J; k++)//determine if duplicate elements are in the same row            if(Field[i][k] = =num)return false;  for(intK0); K < I; k++)//determine if duplicate elements are the same in the same column            if(Field[k][j] = =num)return false; intCount = j%3+ i%3*3;//determine if there are duplicate elements in the entire 3*3 area         while(count--)            if(! (Field[i-i%3+ Count/3][j-j%3+ Count%3] -num)) return false; return true;     }; function<BOOL(int,int,int*) >//class TemplateFill = [&trylist, &fill, &field, Judge] (intYintXint* Numloc)BOOL //fill in numbers with a simple backtracking method     {        if(Y >8)            return true; if(Judge (y, X, *Numloc)) {Field[y][x]= *Numloc; if(Fill (y + (x +1) /9, (x +1) %9, Trylist)) return true; } Field[y][x]=0; if(Numloc-trylist >=8)            return false; if(Fill (Y, x, Numloc +1))            return true;     }; Fill (1,0, trylist);//determine the number to fill in a position//output the corresponding Sudoku matrix according to the parameters     for(intK =0; K <= num;k++) {         for(intI0); I <9; i++) {              for(intJ:field[i]) cout<< J <<" "; cout<<Endl; } cout<< Endl;//each matrix is separated by one row    }    return;}//entrance to the main procedureintMainintargcChar*argv[]) {    intN//number of matrices to output    BOOLCheckChar*C)//used to determine if the third argument entered on the command line is a number     {                intLen = strlen (c);//Get string length         for(inti =0; i < Len; i++) {            if(!isdigit (C[i]))return false; }        return true; }    if(! (ARGC = =3&&!strcmp (argv[1],"- C") && Check (argv[2]))) {//determine if the input command format conforms to the specificationcout <<"parameter input Error! "<<Endl; return 1; } N= Atoi (argv[2]);//converts the third character obtained from the command line to a numberOfstream out;//defining a file stream object    Try    {         out. Open ("Sudotiku.txt", Ios::trunc);//The file does not exist, it is created, the file exists, the data is emptied and the data is entered    }    Catch(Conststd::exception&)//Exception Capture{cout<<"Open File: Sudoku.txt failed!! "; } sudomatrixgenerator (N);//generating n sudoku checkerboard matrices     out. Close ();//Close Sudotiku.txt file    return 0;} 

Five, test run

cmd window, type the command:

Output to Sudotiku.txt:

The test results are basic and error-not generating a repeating matrix.

vi.. Performance Analysis

N=20 CPU time: 12.541 seconds

CPU consumption:

each function occupies:

Seven, Experience

1. The duration of this study is roughly 11hours, In the process of compiling Sudoku chessboard, the application of backtracking is undoubtedly a key point, in fact, backtracking can be regarded as a special form of recursive invocation. But for CS students, it is rare to have never used backtracking to solve problems (such as maze problems and the eight Queens problem), but often it is "the remedy" for a specific problem. These days look at the "Algorithm Design and Analysis" backtracking method related content, think the backtracking method is very good. If the algorithm is to solve the problem of the abstraction of the procedure, then the framework of the backtracking method is the abstraction of a large number of backtracking algorithms, and then combined with the previous data structure in the course of the depth-first search strategy, the use of backtracking method coefficient alone is more logically acceptable, but also the C + + 11 features have a more in-depth understanding of the object and the basic methods of the class, learned how to use Git to submit the source code to the coding server.

2. Problems encountered: How to quickly determine the number of the first row in the Sudoku matrix the corresponding solution is to consult C + + related books (such as C + + primer) and read a csdn blogger's blog after the attempt to use the Shuffle method (with the blogger's blog address 50397618)

Another problem is the use of C + + function library, in the program debugging phase error is "Unable to open a source file xxxx", after the confirmation (with VS2017 example) can be in the compiler in the project properties column of the platform toolset set its version of VS2010 or below, again build can be resolved.

Random construction of N solved Sudoku Chessboard by program

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.