Generate set of unique random numbers in Java

前端 未结 4 982
萌比男神i
萌比男神i 2020-12-03 19:19

I want to create 10 random numbers in the range 0-500. But the problem is that I want those numbers to be unique. For 2 random numbers i could create something as the follow

相关标签:
4条回答
  • 2020-12-03 19:47

    Java Collections has a shuffle method. You can put your numbers into an ArrayList and then shuffle its content. If the ArrayList contains n numbers, calling the shuffle method, would give you the same ArrayList containing n numbers but arranged randomly.

    for(int i=0;i<10;i++){
    list.add(i);  // list contains: [0,1,2,3,4,5,6,7,8,9]
    }
    Collections.shuffle(list);// list now contains: [0, 9, 3, 1, 5, 8, 7, 2, 6, 4]
    
    0 讨论(0)
  • 2020-12-03 19:47

    I would use an array, and store the numbers as they're generated into that array. You would generate a new random, then need to iterate through your array up to your number count, checking to see if it matched any you have previously created.

    0 讨论(0)
  • 2020-12-03 19:52

    Looks like you are storing these in individual variables. The "normal" place to store groups of items like this would usually be in a list or array.

    In this case, store them in a "set" data structure instead. It will not allow duplicates.

    Set documentation: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Set.html

    Set set = new HashSet();
    
    while (set.size() < 10) {
        set.add(r.nextInt(500));
    }
    
    0 讨论(0)
  • 2020-12-03 19:59

    Make a LinkedList of the numbers from 1-500 and shuffle one out of them each time you use a number using The Fisher-Yates shuffle.

    This will give you guaranteed sane (constant time) performance for each number pulled.

    0 讨论(0)
提交回复
热议问题