Prasanna
Prasanna

Reputation: 85

Shuffling an array using random numbers

My program runs sometimes, but other times it runs infinitely because the random number generator keeps generating the same number again and again.

public static String[] shuffleElements(final String[] elements) {
    String[] shuffledArray = new String[elements.length];
    Set<Integer> generatedIndices = new HashSet<Integer>();
    for(int i=0;i < elements.length; i++) {
        int index = -1;
        do{
            index = r.nextInt(elements.length);
            System.out.println(i + ", " + index);
        }while(index == i || generatedIndices.contains(index));
        generatedIndices.add(index);
        assignments[i] = elements[index];
    }
    return shuffledArray;
}

How do I fix this problem? Is there a better way of doing this?

Upvotes: 0

Views: 91

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136042

Try this

Collections.shuffle(Arrays.asList(elements));

Upvotes: 0

Rahul
Rahul

Reputation: 45070

You can do a very simple shuffling of elements using the Collections#shuffle(list) method.

public static String[] shuffleElements(final String[] elements) {
    List<String> list = Arrays.asList(elements);
    Collections.shuffle(list);
    return (String[]) list.toArray();
}

This method uses the default source of randomness. But if you want to specify your own source for the randomness, you can do so by using this overloaded Collections#shuffle(list, random) method.

Upvotes: 1

Related Questions