Creating random numbers with no duplicates

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

    //random numbers are 0,1,2,3 
    ArrayList numbers = new ArrayList();   
    Random randomGenerator = new Random();
    while (numbers.size() < 4) {
    
        int random = randomGenerator .nextInt(4);
        if (!numbers.contains(random)) {
            numbers.add(random);
        }
    }
    

提交回复
热议问题