0

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?

6
  • 1
    Why not use Collections.shuffle? Commented Aug 25, 2014 at 6:33
  • 1
    Coding is fun, but research is often more productive. Assuming this is an academic exercise, I'd recommend reading about the Fisher–Yates shuffle which has been around for ~50 years. Commented Aug 25, 2014 at 6:39
  • Thank you, Chris. Yes, I've been reading about the Fisher-Yates shuffle, but I just wanted to see if I could come up with something myself. Can you please point out why my program doesn't work? Is there a way to fix it? Commented Aug 25, 2014 at 6:43
  • If you want to improve this algorithm with a minimum of changes, you could try to keep a list of unassigned indices and generate each index like this: "index = r.nextInt(elements.length - generatedIndices.size())" Commented Aug 25, 2014 at 6:58
  • Thank you sstendal. I will try that. Do you know why the program goes on an infinite loop? Commented Aug 25, 2014 at 20:19

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.