Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D int array shuffle

im new to this but im tring to do a hotel reservation program.

So i have a 2D int array with ALL rooms, when i start the program i want them to be randomly shuffle in to an array called RoomNotInUse or RoomInUse (so evertime i start the program the rooms are randomly generated.

Would be awesome if anyone know a way around this :)

// ARRAYS
protected static int[][] rooms = {
{1,1}, {1,2}, {1,3}, {1,4}, {1,5}, 
{2,1}, {2,2}, {2,3}, {2,4}, {2,5}, 
{3,1}, {3,2}, {3,3}, {3,4}, {3,5}, 
{4,1}, {4,2}, {4,3}, {4,4}, {4,5}, 
{5,1}, {5,2}, {5,3}, {5,4}, {5,5} 

};
//Declare all hotel rooms 5x5, the first number is the floor and the sec is the room
private char[][] ROIU = {

};
//Rooms not in use
private char[][] RIU = {

};
//Rooms in use


public class roomShuffle {

}
//Shuffle all rooms in 2 diffrent arrays, ROIN and RIU

public class RoomNotInUse {

}
//Displayes all the rooms thats not in use  

public class RoomInUse {

}
//Displayes all rooms in use

}

like image 259
Erazx Avatar asked May 19 '26 10:05

Erazx


2 Answers

You can use Fisher–Yates algorithm modified for two-dimensional arrays:

void shuffle(int[][] a) {
    Random random = new Random();

    for (int i = a.length - 1; i > 0; i--) {
        for (int j = a[i].length - 1; j > 0; j--) {
            int m = random.nextInt(i + 1);
            int n = random.nextInt(j + 1);

            int temp = a[i][j];
            a[i][j] = a[m][n];
            a[m][n] = temp;
        }
    }
}
like image 113
bvitaliyg Avatar answered May 22 '26 00:05

bvitaliyg


Assign all array into list. Than use Collections.shuffle().

    List<int[]> pair=new ArrayList<int[]>();
    pair.addAll(Arrays.asList(rooms));

    Collections.shuffle(pair);
like image 35
Masudul Avatar answered May 22 '26 00:05

Masudul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!