Generating Unique Random Numbers in Java

后端 未结 21 2604
不思量自难忘°
不思量自难忘° 2020-11-21 07:45

I\'m trying to get random numbers between 0 and 100. But I want them to be unique, not repeated in a sequence. For example if I got 5 numbers, they should be 82,12,53,64,32

21条回答
  •  自闭症患者
    2020-11-21 07:58

    I have come here from another question, which has been duplicate of this question (Generating unique random number in java)

    1. Store 1 to 100 numbers in an Array.

    2. Generate random number between 1 to 100 as position and return array[position-1] to get the value

    3. Once you use a number in array, mark the value as -1 ( No need to maintain another array to check if this number is already used)

    4. If value in array is -1, get the random number again to fetch new location in array.

提交回复
热议问题