Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random unique sequences in Java

Tags:

java

random

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.

like image 789
David Weng Avatar asked May 02 '26 13:05

David Weng


1 Answers

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);
}

:-)

like image 156
Chris Jester-Young Avatar answered May 05 '26 04:05

Chris Jester-Young



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!