首页 > 解决方案 > Implentation of a Selection Shuffle in Java

问题描述

public static void selectionShuffle(int[] values) {
    Random rand = new Random();
    for(int i = values.length; i > 0; i--) {
         int r = rand.nextInt(i); 
         swap(values, r, i);
    }
//updated answer to include below method
public static void swap(int[]a, int i, int j){
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

I am writing a card game and need to randomly sort the cards in place, I got an ArrayOutOfBoundsException when I ran the above code, with the compiler complaining particularly about the reassignment from values[i] = values[r] . To be clear, this is , not intended to be a selection sort but instead a selection shuffle. Any help is appreciated!

标签: javashuffle

解决方案


Integer或者,您可以尝试 Collections.shuffle() 但如果您必须首先使用包装类而不是原始类型,它会更方便int

整数 [] 版本

public static void selectionShuffle(Integer[] values) {
    Collections.shuffle(Arrays.asList(values));
}

int[] 版本:

public static void selectionShuffle(int[] values) {
     Integer[] boxedArr = Arrays.stream(values).boxed().toArray( Integer[]::new );
     Collections.shuffle(Arrays.asList(boxedArr));
     for(int i=0 ; i<values.length ; i++){
         values[i] = boxedArr[i];
     }
 }

推荐阅读