2D int数组shuffle

时间:2013-11-25 10:43:14

标签: 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

}

5 个答案:

答案 0 :(得分:8)

您可以使用针对二维数组修改的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;
        }
    }
}

答案 1 :(得分:1)

将所有数组分配到列表中。而不是使用Collections.shuffle()

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

    Collections.shuffle(pair);

答案 2 :(得分:0)

您可以使用shuffle -

Collections.shuffle()

这是一个tutorial,用或不用收藏品来描述。

答案 3 :(得分:0)

Java中的通用shuffle方法应该与此类似

重要的是你必须在集合中使用随机元素交换项目;)

public void shuffle(Comparable [] a){
    for(int i=0;i,a.length;i++)
         swap(a,i,getRandom(i,a.length-1);
}

private int getRandom(int min, int max){
     Random rnd = new Random();
     return min + rnd.nextInt(max-min+1);
}

 private void swap(Comparable [] a, int i, int j){
      Comparable temp = a[i];
      a[i]=a[j];
      a[j]=temp;
 }

否则您可以使用Collection.shuffle方法。

答案 4 :(得分:0)

<script type="text/javascript">
   $('input[value="100"]').parent('li').addClass('selected');
</script>
相关问题