3

I have an array of numbers, let's say for example it's

[1, 3, 5, 7, 9] 

It is possible to generate 5! that is 120 unique sequences of these numbers. For example

1 3 5 7 9 5 1 3 9 7 7 3 9 5 1 1 7 9 5 3 ... and so forth 

I need to generate 10 of these sequences randomly, with no duplicates. Any suggestions would be much appreciated.

6
  • Do the 10 have to be unique? Or is the possibility of repeats okay? Commented Sep 13, 2011 at 15:44
  • @Jokada yes, I need them to be unique. Commented Sep 13, 2011 at 15:47
  • 2
    If you must ensure that it's unique, you can't ensure that it's truly random... Commented Sep 13, 2011 at 15:47
  • 1
    What's your real world starting array length? Commented Sep 13, 2011 at 15:48
  • @jball that sounds like a real cool quote, but a basic algorithm would be generating random sequences and throwing away the duplicate ones until you have the 10 unique ones. You still think this can't be considered random? Commented Sep 13, 2011 at 16:16

2 Answers 2

4
List<Integer> template = Arrays.asList(1, 3, 5, 7, 9); Set<List<Integer>> seen = new HashSet<List<Integer>>(); for (int i = 0; i < 10; ++i) { List<Integer> items = new ArrayList<Integer>(template); do { Collections.shuffle(items); } while (!seen.add(items)); System.out.println(items); } 

:-)

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

5 Comments

@Amir: This answer is too "enterprisey" to be able to submit as a homework entry. ;-)
Of course the problem with algorithm is that it will always be the same 10 sequences! So if you want a different set of numbers on every run, you may want to do the recursion.
@Amir someone tagged it as homework, but not the OP, and no one has mentioned homework apart from that, so while it may well be, it could also just be a question generated by a curious programmer :)
@Amir: No, it won't. Java will auto-seed your RNG as necessary. :-P
Yep. I stand corrected. Shuffle will be different on each run. That's good to know.
3

What you want is to generate n random permutations of a given array. There is a simple algorithm for generating one random permutation, which is well explained on wikipedia. You still have to check for uniqueness, though.

In Java :

Random rand = new Random(); int[] generateRandomPermutation(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { int d = rand.nextInt(i+1); res[i] = res[d]; res[d] = i; } return res; } 

Another solution is to use a permutation numbering scheme (presented here), and generate the corresponding permutation of n random distinct integers (from 0 to s!-1, where s is the size of the array).

1 Comment

Simple, portable and efficient!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.