java - 2D int 数组洗牌

标签 java arrays multidimensional-array shuffle

我对此很陌生,但我正在尝试做一个酒店预订程序。

所以我有一个包含所有房间的 2D int 数组,当我启动程序时,我希望它们随机洗牌到一个名为 RoomNotInUse 或 RoomInUse 的数组中(所以每当我启动程序时,房间都是随机生成的。

如果有人知道解决这个问题的方法那就太棒了:)

// 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

}

最佳答案

您可以使用针对二维数组修改的 Fisher–Yates 算法:

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;
        }
    }
}

关于java - 2D int 数组洗牌,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20190110/

相关文章:

java - Java 中的数组和输出

python - 如何创建一个 numpy 数组,该数组对应于一个点是否位于 numpy 多边形数组内?

python - Numpy:如何按整数值缩放整数数组?

java - 如何使用我自己的生成 key 策略来实现@GenerateValue

java - ArrayList 中的不兼容类型错误,但两者都是 String

arrays - 如何使用where子句检查postgres数组中是否存在值

java多维数组声明1*3维?

java - 哪个是 Spring 4 支持的最低 Java 版本

java - Spring Boot 2.1.1 中带有 RANDOM_PORT 的 SpringBootTest 每次都使用 8080

c++ 模板队列类的嵌套初始化