This site requires JavaScript, please enable it in your browser!
Greenfoot back
fejfo
fejfo wrote ...

2016/2/20

Sudoku generation (speed and bugs)

fejfo fejfo

2016/2/20

#
I made a sudoku generator but it doesn't work and beacause it is so slow (on my pc) it is very painfull to bug test (10 min per sudoku) My plan was to convert the 2d array into actors after generation but since the generation didn't work I didn't see a reason to do that It's is all in a single class the world class
import greenfoot.*;
import java.util.Random;
import java.awt.Point;
import java.util.ArrayList;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Arrays;

public class Sudoku extends World
{
    int removals = -1; // -1 for infinite

    int[][] sudoku = new int[9][9];

    static final int cellSize = 50;

    int index = 0;
    /**
     * Constructor for objects of class Sudoku.
     * 
     */
    public Sudoku()
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(9, 9, cellSize); 

        //init the randomNumbers
        long seed = random.nextLong();
        random.setSeed(seed);
        print("seed = " + seed);

        //init the out
        try {
            FileOutputStream f = new FileOutputStream("C:/Users/Jef/Desktop/console.txt");
            System.setOut(new PrintStream(f));
        }catch(Exception e) {
            System.out.println("ERROR:" + e);
            System.err.println(e);
            e.printStackTrace();
        }

        //fill the board with -1 for checking if the cell was filled or not 
        // without getting a nullpointer exception

        print("preparing the board");
        for(int x = 0; x < 9; x++) {
            for(int y = 0; y < 9; y++) {
                sudoku[x][y] = -1;                
            }
        }
        print("prepared board :");
        printBoard();

        print("filling the board.............");
        index++;
        fill();
        index--;
        print("done filling the board");
        print("completed board :");
        printBoard();
        print("filtering the board .............");
        index++;
        filter();
        index--;
        print("done filtering the board");
        print("incompleted board :");
        printBoard();
    }

    public void printBoard() {
        for(int i = 0; i < 9; i++)        {
            for(int j = 0; j < 9; j++)            {
                System.out.print(sudoku[i][j]+" ");
            }
            System.out.println();
        }
    }

    public void print(String text) {
        if(index > 0) for(int i = 0; i < index; i++) System.out.print("\t");
        System.out.println(text);
    }

    public void filter() {
        ArrayList<Point> filtereables = new ArrayList();

        for(int x = 0; x < 9; x++) {
            for(int y = 0; y < 9; y++) {
                filtereables.add(new Point(x,y));
            }
        }
        print("prepared filter");
        print("filtering.............");
        index++;
        while(filtereables.size() > 0) {
            Point filtereable = filtereables.get(rNum(filtereables.size())); 
            int forced = forced((int) filtereable.getX(), (int) filtereable.getY());
            if(forced != -1) { //if the cell has a forced containment
                sudoku[(int) filtereable.getX()][(int) filtereable.getY()] = -1;      

            }   
            filtereables.remove(filtereable);          
            print("filterd a number " + filtereables.size() + " to go");
        }
        index--;
    }

    //fill the board with a random valid layout
    public void fill() {
        int nNumbers = 0;
        while(isFull() == false) {
            //add a random number to a random cell

            boolean changed = false;
            while(changed == false) {
                int x = rNum();
                int y = rNum();
                if(sudoku[x][y] == -1) {
                    sudoku[x][y] = rNum()+1;
                    nNumbers++;
                    print("adding a random number " + (81-nNumbers) + " to go");
                    changed = true;
                }               
            }

            //print("checking for forced numbers ..............");

            // check if this forced an other cell to contain a certain number
            boolean loopedFully = false;
            while(loopedFully == false) {
                //every time a new cell is found restart
                cellLoop:
                for(int x = 0; x < 9; x++) {
                    //print("row:" + x);

                    for(int y = 0; y < 9; y++) {
                        //index++;
                        //print("colum:" + y);
                        //for eath cell
                        if(sudoku[x][y] != -1) {
                            try {
                                sudoku[x][y] = forced(x,y);
                            }catch(Exception e) {
                                System.out.println("ERROR:" + e);
                                System.err.println(e);
                                e.printStackTrace();
                            }

                            if(sudoku[x][y] != -1) {            
                                index++;
                                print("added a forced number at " + x +"," +y + " " + (81-nNumbers) + " to go");
                                print("rechecking for forced numbers ...........");
                                index--;
                                break cellLoop;
                            }                            
                        }
                        //index--;
                        if(x == 8 && y == 8) {
                            loopedFully = true;
                        }
                    }
                }
            }

            if(nNumbers > 81) printBoard();
        }
    }

    Random random = new Random();
    public int rNum() {        
        return random.nextInt(9);
    }

    public int rNum(int max) {        
        return random.nextInt(max);
    }

    public boolean isFull() {
        for(int[] row : sudoku) {
            for(int cell : row) {
                if(cell == -1) {
                    return false;
                }
            }
        }
        return true;
    }

    //returns the forced containment of a cell if it can be forced
    //if it can't be forced returns -1
    // throws an exception if nothing fits
    public int forced(int x, int y) throws IllegalStateException {
        int validNumber = -2;        
        for(int n = 1; n < 10; n++) {
            //for eath possible numer in the cell 
            //check if the cell can contain that number
            boolean valid = true;
            // 1 check the row
            for(int rowX = 0; rowX < 9; rowX++) {
                if(sudoku[rowX][y] == n && rowX != x) valid = false; //if the row already contains this number it can't be put in
            }
            // 2 check the colum
            if(valid == true) {
                for(int colY = 0; colY < 9; colY++) {
                    if(sudoku[x][colY] == n && colY != y) valid = false; //if the colum already contains this number it can't be put in
                }

                if(valid == true) {
                    // 3 check the cell
                    // 3.1 determent the cell
                    int cellX = (int) Math.floor(x/3.0);
                    int cellY = (int) Math.floor(y/3.0);
                    // 3.2 loop throug all the number in the same cell 
                    for(int checkX = cellX*3; checkX < (cellX+1)*3; cellX++) {
                        for(int checkY = cellY*3; checkY < (cellY+1)*3; cellY++) {
                            if(sudoku[checkX][checkY] == n && (checkX != x && checkY != y)) valid = false; //if the cell already contains this number it can't be put in
                        }
                    }
                }
            }

            //if this is the first valid cell found keep looping
            //if there was already found one don't fill anthing in
            if(valid == true) {
                if(validNumber != -2) {
                    //a valid number was already found
                    validNumber = -1;
                    break;
                }else validNumber = n;
            }
        }

        if(validNumber == -2) {
            throw new IllegalStateException("an imposible chalange was created please fix bugs or retry");
        }

        return validNumber;
    }
}
this code prints :
preparing the board
prepared board :
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
filling the board.............
	adding a random number 80 to go
	adding a random number 79 to go
	adding a random number 78 to go
	adding a random number 77 to go
	adding a random number 76 to go
	adding a random number 75 to go
	adding a random number 74 to go
	adding a random number 73 to go
	adding a random number 72 to go
	adding a random number 71 to go
	adding a random number 70 to go
	adding a random number 69 to go
	adding a random number 68 to go
	adding a random number 67 to go
	adding a random number 66 to go
	adding a random number 65 to go
	adding a random number 64 to go
	adding a random number 63 to go
	adding a random number 62 to go
	adding a random number 61 to go
	adding a random number 60 to go
	adding a random number 59 to go
	adding a random number 58 to go
	adding a random number 57 to go
	adding a random number 56 to go
	adding a random number 55 to go
	adding a random number 54 to go
	adding a random number 53 to go
	adding a random number 52 to go
	adding a random number 51 to go
	adding a random number 50 to go
	adding a random number 49 to go
	adding a random number 48 to go
	adding a random number 47 to go
	adding a random number 46 to go
	adding a random number 45 to go
	adding a random number 44 to go
	adding a random number 43 to go
	adding a random number 42 to go
	adding a random number 41 to go
	adding a random number 40 to go
	adding a random number 39 to go
	adding a random number 38 to go
	adding a random number 37 to go
	adding a random number 36 to go
	adding a random number 35 to go
	adding a random number 34 to go
	adding a random number 33 to go
	adding a random number 32 to go
	adding a random number 31 to go
	adding a random number 30 to go
	adding a random number 29 to go
	adding a random number 28 to go
	adding a random number 27 to go
	adding a random number 26 to go
	adding a random number 25 to go
	adding a random number 24 to go
	adding a random number 23 to go
	adding a random number 22 to go
	adding a random number 21 to go
	adding a random number 20 to go
	adding a random number 19 to go
	adding a random number 18 to go
	adding a random number 17 to go
	adding a random number 16 to go
	adding a random number 15 to go
	adding a random number 14 to go
	adding a random number 13 to go
	adding a random number 12 to go
	adding a random number 11 to go
	adding a random number 10 to go
	adding a random number 9 to go
	adding a random number 8 to go
	adding a random number 7 to go
	adding a random number 6 to go
	adding a random number 5 to go
	adding a random number 4 to go
	adding a random number 3 to go
	adding a random number 2 to go
	adding a random number 1 to go
	adding a random number 0 to go
	adding a random number -1 to go
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
	adding a random number -2 to go
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
	adding a random number -3 to go
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 
I you have any idea why this only prints -1 's or how to inprove the speed please answer
danpost danpost

2016/2/20

#
I think you are going about creating your puzzles in the wrong way. Instead of trying to create the puzzle itself, first create the answer. This is fairly easy as all you need to do is check that no number is duplicated in any row, column or 3x3 box. Once the answer is created, you can produce a puzzle by removing numbers (or pairs of numbers, for symmetry). You only then need to check that only one solution is possible each time you increase the number of blank cells (or, as you remove the numbers). This method can be fairly quick, especially if you decide to limit the number of checks for removal of numbers rather than setting a specific number of blank cells in the puzzle.
fejfo fejfo

2016/2/21

#
Are you saying that I should first fill each cell with a random content and keep retrying until it works ? or should I take every row and put all the 9 different numbers in there and to that for all the rows ? I really don't understand how you can generate the solution And I know I didn't mention this before but I want only one solution to be possible for each puzzle.
danpost danpost

2016/2/21

#
fejfo wrote...
Are you saying that I should first fill each cell with a random content and keep retrying until it works ? or should I take every row and put all the 9 different numbers in there and to that for all the rows ?
I am saying to work across each row from top to bottom and randomly place one of the untried possibilities in each cell. If you run out of possibilities in any cell, try another possibility of a previous cell. I did mine something like this:
// instance field to hold answer
private String answer;

// method to create answer
private void createAnswer()
{
    // clear answer cells (char elements of the 'answer' string)
    answer = "";
    for (int i=0; i<81; i++) answer += " ";
    // create array for possibilities of each cell
    String[] posies = new String[81];
    // set up variable for current cell working on
    int cell = 0;
    // the main process
    while (cell < 81) // until completed
    {
        if (posies[cell] == null) // new cell (or revisited after changing an earlier one)
        {
            posies[cell] = "123456789"; // start with all possibles
            // eliminate possibles taken among row, column and box
            for (int n=0; n<cell%9; n++) posies[cell] = removeChar(posies[cell], answer.charAt(9*(cell/9)+n)); // row eliminations
            for (int n=0; n<cell/9; n++) posies[cell] = removeChar(posies[cell], answer.charAt((cell%9)+9*n)); // column eliminations
            for (int r=0; r<3; r++) for (int c=0; c<3; c++) // box eliminations
            {
                int loc = (cell/27)*27+3*((cell%9)/3)+r*9+c;
                if (loc < cell) posies[cell] = removeChar(posies[cell], answer.charAt(loc));
            }
        }

        /** processing of cell */
        // check for no possibilities remaining
        if ("".equals(posies[cell]))
        {
            posies[cell] = null; // cell needs reset (answer impossible at this point)
            cell--; // go back to previous cell (try a different possible)
            continue;
        }
        // choose a random possibility
        int index = Greenfoot.getRandomNumber(posies[cell].length()); 
        answer = setCharAt(cell, posies[cell].charAt(index), answer); // change character in answer
        posies[cell] = removeChar(posies[cell], posies[cell].charAt(index)); // remove possibility for cell
        cell++; // proceed to next cell
    }
}

/** helper methods */

// returns the given string with the character at the given position within a string changed to the given character
private String setCharAt(int position, char element, String array)
{
    if (position == 0) return element+array.substring(1);
    return array.substring(0, position)+element+array.substring(position+1);
}

// returns the given string with the given character removed from it
private String removeChar(String array, char element)
{
    int index = array.indexOf(element);
    if (index == -1) return array;
    if (index == 0) return array.substring(1);
    return array.substring(0, index)+array.substring(index+1);
}
I used a string for representing the grid values because most of the processes needed are already supplied within the String class (using an int array, one would have to code all the different look-up/altering methods). Also, you can easily replace String object references with different sized String objects, while changing the size of an array is much more difficult.
You need to login to post a reply.