Java from basic to Advanced learning----Sudoku Mini-game Production (ii)

Source: Internet
Author: User
Tags shuffle

Detailed design

game data structure design

Obviously, the only place where you need to store data is the nine map section.

For maps, it is obvious that we can use two-dimensional array int [] [] game; To store the data in the map. However, although the two-dimensional array of int is straightforward, there are some inconveniences, such as the rich built-in processing method without the set. So, obviously, in the game map generation process, some auxiliary data we can adopt the Java collection.

Map Generation Algorithm

For Sudoku, the most fundamental guarantee of a game's success is that the current map has an existing solution. This is like solving the equation, and if there is no solution, then the game itself is a failure.

So, the focus is on how to produce a map that has a solution and a unique solution. If we are just randomly generating numbers, it is obviously not possible, although in our opinion, the numbers on the map do seem to be randomly generated: each time there is a variable position, the size is different.


However, random generation does not guarantee that the results of the game must have a solution!

So How do we create a map that we can play?

This requires us to reverse the thinking, since the premise is to have a workable solution, then we directly produce a solution, called the final disk, and then the numbers of these solutions are randomly rejected, forming the initial disk, the remaining display on the map is not OK ?

Then there is a new problem, How do we produce a workable solution?

First, we need to clarify the requirements for a workable solution:

    • The solution must conform to the rules of the game
    • Each generated solution is not the same.
    • Solution Unique

With these two requirements, we have a goal.

The first consideration is how to produce a solution that matches the rules of the game. The rules of the game are:

    • No duplicate numbers can appear in each row
    • No duplicate numbers can appear in each column
    • No duplicate numbers can appear in each small Gongge area (3x3)

Actually did the ACM topic should all be able to see that this is a simple ACM topic.

That is: now define a nine-Gongge, which allows you to randomly generate a complete final map of nine Gongge in accordance with the nine Gongge rules.

Do more experienced people, it is obvious that a glance can come out, this topic, obviously with the search to do the most suitable.

I used Dfs, a depth-first search for processing. The process is as follows, first we now define the coordinates of the Gongge as follows:


There are 9*9=81, so you can define a variable index so that it starts from 0 to 80, divides it by 9 until the line coordinates, and the column coordinates for the 9 remainder. That is:

X = INDEX/9

Y = index% 9

The code for DFS is as follows:

    /** * generates Sudoku game solution.     * * @param game game to fill, user should pass ' new int[9][9] '.     * @param index Current index, user should pass 0.     * @return Sudoku Game solution.        */Private int[][] Generatesolution (int[][] game, int index) {if (Index >) return game;        Gets the coordinate int x = index% 9;        int y = INDEX/9;        Generates 1-9 of the number of ArrayList, and disrupts the order list<integer> numbers = new arraylist<integer> ();        for (int i = 1; I <= 9; i++) Numbers.add (i); Collections.shuffle (numbers); Disturb the list order//try to determine the numeric value of the coordinate while (numbers.size () > 0) {int number = Getnextpossiblenumber (g Ame, x, y, numbers);            Gets the possible value of the coordinate if (number = =-1) return null;            GAME[Y][X] = number; int[][] Tmpgame = generatesolution (game, index + 1);     Recursive invocation, next possible value if (tmpgame! = null) return tmpgame;       Game[y][x] = 0;    } return null; }

That is, from left to right, from top to bottom, a coordinate of the number of a coordinate to determine, is to try to get the possible value, because, in such a step-by-phase search determines that the value of a coordinate may exist without solution, that is, the coordinates can not be filled with any number, otherwise violate the rules, this time, will be recursive , returns to the previous coordinate and resets the value of the previously-solvable coordinates to 0, re-determines the other possible values of the previous coordinate (that is, removing the previous value that has been taken), and if it is not, continues out of the stack, returns to a more coordinate, re-determines if there are other desirable values, and then recursively searches from this coordinate. This completes until the complete map is successfully searched.

The above is only the final disk generation algorithm, then how to generate initial disk?

As we said above, to take out the numbers on the final plate, this can also be said to be an image of "digging holes", that is, on the final disk randomly dug holes, the rules are:

Dig a hole, and then determine if the current face solution exists and is unique, and if not, stop digging. Otherwise you can continue digging until you meet the requirements.

The implementation code is as follows:

    Private int[][] Generategame (int[][] game) {list<integer> positions = new arraylist<integer> ();        for (int i = 0; i < Bayi; i++) Positions.add (i);        Collections.shuffle (positions);    Return Generategame (game, positions); }/** * Generates Sudoku game from solution, user should with the other * Generategame method.     This method is simple removes a number at a position.     * If the game isn ' t anymore valid after this action, the game would be * brought back to previous state.     * * @param game game to be generated.     * @param positions List of remaining positions to clear.     * @return Generated Sudoku game.             */Private int[][] Generategame (int[][] game, list<integer> positions) {while (positions.size () > 0) {            int position = positions.remove (0);            int x = position% 9;            int y = POSITION/9;            int temp = game[y][x]; GaMe[y][x] = 0;        if (!isvalid (game)) game[y][x] = temp;    } return game;     }/** * Checks whether given game is valid.     * * @param game game to check.     * @return True If game is valid, false otherwise.    */Private Boolean isValid (int[][] game) {return isValid (game, 0, new int[] {0}); }/** * Checks whether given game is valid, user should with the other IsValid * method.     There may is only one solution.     * * @param game game to check.     * @param index current index to check. * @param numberofsolutions number of found solutions.     Int[] instead of * int because of pass by reference.     * @return True If game is valid, false otherwise. */Private Boolean isValid (int[][] game, int index, int[] numberofsolutions) {if (Index >) ret  Urn ++numberofsolutions[0] = = 1;      int x = index% 9;        int y = INDEX/9;            if (game[y][x] = = 0) {list<integer> numbers = new arraylist<integer> ();            for (int i = 1; I <= 9; i++) Numbers.add (i);                while (Numbers.size () > 0) {int number = Getnextpossiblenumber (game, x, y, numbers);                if (number = =-1) break;                GAME[Y][X] = number;                    if (!isvalid (game, index + 1, numberofsolutions)) {game[y][x] = 0;                return false;            } Game[y][x] = 0;        }} else if (!isvalid (game, index + 1, numberofsolutions)) return false;    return true; }

It is not very well understood to say this algorithm for the time being. The initial disk generation algorithm based on "burrowing" can be searched for relevant documents to understand.


Reference:

The Mystery of Sudoku

Http://www.shs.edu.tw/works/essay/2008/10/2008103010094624.pdf

Discussion on the method of Sudoku generation

http://www.sudoku.org.tw/phpBB/viewtopic.php?f=6&t=36

The literature on digging holes

Http://wenku.baidu.com/view/f9e3f17101f69e31433294e1.html

Java from basic to Advanced learning----Sudoku Mini-game Production (ii)

Related Article

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.