Search code examples
javaarraysswap

2D Array item swap randomly


I have an enum:

public enum Player
{
   X, O, NOBODY
}

And I have this array filled with player items randomly:

Player [size][size] p;

Example matrix:

[ X, NOBODY, NOBODY ]
[ NOBODY, O, O ]
[ X, X, NOBODY ] 

I would like to swap an X or O element with a NOBODY element randomly, how can I do that?

Example:

[ NOBODY, NOBODY, NOBODY ]
[ NOBODY, O, O ]
[ X, X, X ] 







Solution

  • One straightforward approach would be to select a random X/O cell as well as a random NOBODY cell, and then swap their values:

    // method inside class containing the array
    public void swapValues() {
        Random rand = new Random();
        int xoPos;
        int nobodyPos;
    
        do {
            xoPos = rand.nextInt(size*size);
            Player p = p[xoPos / size][xoPos % size];
        } while (Player.NOBODY.equals(p));
    
        do {
            nobodyPos = rand.nextInt(size*size);
            Player p = p[nobodyPos / size][nobodyPos % size];
        } while (!Player.NOBODY.equals(p));
    
        p[nobodyPos / size][nobodyPos % size] = p[xoPos / size][xoPos % size];
        p[xoPos / size][xoPos % size] = Player.NOBODY;
    }
    

    The strategy here is to generate a single random number between 0 and one minus the total number of cells in the 2D board. Then, we use integer division and modulus to figure out to what 2D coordinates that single value corresponds.