Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating a Sudoku in Java
    primarykey
    data
    text
    <p>I'm creating a program that invents a new Sudoku puzzle. The way I initially planned on doing this is by inventing a new puzzle and then removing random numbers. However, the algorithm I use (seen below) to create a new puzzle can take up to 5 minutes to make one. Does anyone have any faster solutions?</p> <h2>Creation Algorithm</h2> <hr> <pre><code> for (int x = 0; x &lt; boardWidth; x++) //boardWidth is the number of fillable squares wide and high the board is. (9 for a standard Sudoku board) { for (int y = 0; y &lt; boardWidth; y++) { int errorCount = 0; do { boardVals[y][x] = (byte)(rand.nextInt(boardWidth) + 1); errorCount++; if (errorCount &gt; Math.pow(boardWidth, 4)) //If the square has been tried to be filled up to boardWidth^4 times (6,561 for a standard Sudoku board), it clears the board and starts again. { resetBoard(); x = 0; y = 0; break; } }while (!boardIsOK()); //boardIsOK() is a method that checks to see if the board is solvable, ignoring unfilled squares. } } </code></pre> <h2>Methods:</h2> <hr> <pre><code> private boolean boardIsOK() { for (int i=0; i &lt; boardWidth; i++) { if (!setIsOK(getRow(i))) { return false; } if (!setIsOK(getCol(i))) { return false; } } for (int x=0; x &lt; boardSegs; x++) { for (int y=0; y &lt; boardSegs; y++) { if (!areaIsOK(getSquare(x,y))) { return false; } } } return true; } private byte[] getRow(int index) { return boardVals[index]; } private byte[] getCol(int index) { byte[] b = new byte[boardWidth]; for (int i=0; i &lt; boardWidth; i++) b[i] = boardVals[i][index]; return b; } private byte[][] getSquare(int xIndex, int yIndex) { byte w = (byte)(boardWidth / boardSegs), b[][] = new byte[w][w]; for (int x=0; x &lt; b.length; x++) { for (int y=0; y &lt; b[x].length; y++) { b[y][x] = boardVals[y + (yIndex * w)][x + (xIndex * w)]; } } return b; } private boolean setIsOK(byte[] set) { for (int i=0; i &lt; set.length - 1; i++) { for (int j=i + 1; j &lt; set.length; j++) { if (set[i] == set[j] &amp;&amp; set[i] != NULL_VAL &amp;&amp; set[j] != NULL_VAL) { return false; } } } return true; } private boolean areaIsOK(byte[][] area) { int size = 0; for (int i=0; i &lt; area.length; i++) { size += area[i].length; } byte[] b = new byte[size]; for (int x=0, i=0; x &lt; area.length; x++) { for (int y=0; y &lt; area[x].length; y++, i++) { b[i] = area[x][y]; } } return setIsOK(b); } </code></pre> <p>resetBoard() simply fills the board with NULL_VAL.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload