Creating random numbers with no duplicates

后端 未结 18 1788
忘了有多久
忘了有多久 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:11

    Another approach which allows you to specify how many numbers you want with size and the min and max values of the returned numbers

    public static int getRandomInt(int min, int max) {
        Random random = new Random();
    
        return random.nextInt((max - min) + 1) + min;
    }
    
    public static ArrayList getRandomNonRepeatingIntegers(int size, int min,
            int max) {
        ArrayList numbers = new ArrayList();
    
        while (numbers.size() < size) {
            int random = getRandomInt(min, max);
    
            if (!numbers.contains(random)) {
                numbers.add(random);
            }
        }
    
        return numbers;
    }
    

    To use it returning 7 numbers between 0 and 25.

        ArrayList list = getRandomNonRepeatingIntegers(7, 0, 25);
        for (int i = 0; i < list.size(); i++) {
            System.out.println("" + list.get(i));
        }
    

提交回复
热议问题