Creating random numbers with no duplicates

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

    This would be a lot simpler in java-8:

    Stream.generate(new Random()::ints)
                .distinct()
                .limit(16) // whatever limit you might need
                .toArray(Integer[]::new);
    

提交回复
热议问题