Creating random numbers with no duplicates

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

    You could use one of the classes implementing the Set interface (API), and then each number you generate, use Set.add() to insert it.

    If the return value is false, you know the number has already been generated before.

提交回复
热议问题