Creating random numbers with no duplicates

后端 未结 18 2072
忘了有多久
忘了有多久 2020-11-21 12:00

In this case, the MAX is only 5, so I could check the duplicates one by one, but how could I do this in a simpler way? For example, what if the MAX has a value of 20? Thanks

18条回答
  •  我在风中等你
    2020-11-21 12:17

    Here's how I'd do it

    import java.util.ArrayList;
    import java.util.Random;
    
    public class Test {
        public static void main(String[] args) {
            int size = 20;
    
            ArrayList list = new ArrayList(size);
            for(int i = 1; i <= size; i++) {
                list.add(i);
            }
    
            Random rand = new Random();
            while(list.size() > 0) {
                int index = rand.nextInt(list.size());
                System.out.println("Selected: "+list.remove(index));
            }
        }
    }
    

    As the esteemed Mr Skeet has pointed out:
    If n is the number of randomly selected numbers you wish to choose and N is the total sample space of numbers available for selection:

    1. If n << N, you should just store the numbers that you have picked and check a list to see if the number selected is in it.
    2. If n ~= N, you should probably use my method, by populating a list containing the entire sample space and then removing numbers from it as you select them.

提交回复
热议问题