Pseudo-random shuffle N-Puzzle?

I am working on an N-Puzzle game (also known as a 15-puzzle ...) where you split an image into a square grid, delete one part and mix it up. I'm not interested in solving the puzzle, as it depends on the user. But I would like to shuffle the board in a pseudo-random way.

I know that 1/2 of all possible tasses will make the board unsolvable. Is there an easy way psuedo-randomly generate a shuffled state, assuming I have a rand () function - esc, and I know the size of the board?

I have a game board in memory, a multidimensional array of integers. My method simply puts the images in the opposite order, switching the last from the second to the last image on even boards. My current function is below and I am working in Java.

private void shuffle()
{
    gameState = new int[difficulty][difficulty];
    int i = 0, N = (difficulty * difficulty) -1;

    while (i < N)
        gameState[(int)(i / difficulty)][i % difficulty] = N - ++i;
    gameState[difficulty-1][difficulty-1] = N;

    // N id even when the remainder of N/2 is 0
    if ((difficulty % 2) == 0)
    {
        // swap 2nd to last and 3rd to last element
        int tmpEl = gameState[difficulty-1][difficulty-2];
        if (difficulty == 2)
        {
            gameState[1][0] = gameState[0][1];
            gameState[0][1] = tmpEl;
        }
        else
        {
            gameState[difficulty-1][difficulty-2] = gameState[difficulty-1][difficulty-3];
            gameState[difficulty-1][difficulty-3] = tmpEl;
        }
    }
}
+3
3

, (, ).
( ) " . , .
( - , ), "" .

, , .

, : , .

+3

.

, , 15-, .

, . , Knuth shuffle:

Knuth shuffle ( Fisher-Yates shuffle) , , . swap ( 1 3), ( 1 2).

, , . , (1,3,5,... ). , .

+6

Just create random puzzles until you create one with even parity. http://heuristicswiki.wikispaces.com/N+-+Puzzle

+2
source

All Articles