2016-10-10 102 views
0

那里我有在Java中的方法随机化数组中的整数。但它花了太长时间,我正在试图找到更快的方法来做到这一点,我认为fisher Yates算法是解决方案,但我不知道如何用我的代码实现这一点。实现Fisher Yates算法

protected void randomise() { 
    int[] copy = new int[getArray().length]; 
    // used to indicate if elements have been used 
    boolean[] used = new boolean[getArray().length]; 
    Arrays.fill(used,false); 
    for (int index = 0; index < getArray().length; index++) { 
     int randomIndex; 
     do { 
      randomIndex = getRandomIndex(); 
     } while (used[randomIndex]); 
     copy[index] = getArray()[randomIndex]; 
     used[randomIndex] = true; 
    } 
    for (int index = 0; index < getArray().length; index++) { 
     getArray()[index] = copy[index]; 
    } 
} 
/* 
* A method which prints out the list of nubers 
*/ 

public static void main(String[] args) { 
    RandomListing count = new SimpleRandomListing(1000000); 
    System.out.println(Arrays.toString(count.getArray())); 
} 
+0

我以前见过这个。它是功课吗? – vz0

+0

你最终使用任何答案?因为如果你这样做了,请标记你使用的答案是正确的。 – Gikkman

回答

0
N = array.length; 
for i in [0, 1, 2, ..., N - 1]: 
    random_index = random(i, N - 1); 
    swap(array[i], array[random_index]); 
+0

这不符合'Java'作为一种语言:-) – lospejos

+0

是的,它是伪东西。我自己的个人酿造。这个问题看起来像家庭作业,而对于作业而言,通常比编写作为9到5工作的代码更容易理解伪代码。 – vz0

0

这里的费雪耶茨

public static <T> void fyShuffle(T[] elem, Random rng){ 
    int index = 0; 
    T temp = null; 

    //Fisher–Yates shuffle the 'elem' array 
    for (int i = elem.length - 1; i > 0; i--) { 
     index = rng.nextInt(i + 1); 
     temp = elem[index]; 
     elem[index] = elem[i]; 
     elem[i] = temp; 
    } 
} 

的实现也可以使用Collections.shuffle(collection)洗牌集合(如List<>