不重复的随机数字

作为我的项目的一部分,我需要通过给出一组数字来创build不重复的2或3位数的随机数。 我不想实现一个列表或数组,因为我应该为每个函数调用得到一个随机数。

我试图用Java的SecureRandom类来做到这一点。 我也得到了一些网站的帮助,但是我陷入了困境,我们可以洗牌VALUES并完成它吗? 但我不知道如何做到这一点。 任何人都可以帮我吗?

import java.security.SecureRandom; public class RandomNumber { private static final RandomNumber rnd= new RandomNumber(); private static final char[] VALUES = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; private static final SecureRandom srn= new SecureRandom(); public String createID() { byte[] bytes = new byte[3]; srn.nextBytes(bytes); } 

Fisher-yates shufflealgorithm是要走的路。 它有效的洗牌。 它在线性时间工作。

这里是algorithm

 To shuffle an array a of n elements: for i from n − 1 downto 1 do j ← random integer with 0 ≤ j ≤ i exchange a[j] and a[i] 

和代码

 for(int i=VALUES.length-1; i>0; i--){ int rand = (int) (Math.random()*i); char temp = VALUES[i]; VALUES[i] = VALUES[rand]; VALUES[rand] = temp; } 

当Manoj的代码迭代时,更有可能交换VALUES []中较低的元素,而不是较高的元素。 例如:对于i = 9,有十分之一的机会与arrays中的任何成员(包括自己)交换。 那么对于i = 8,我们再也不能用VALUES [9]交换,因为Math.random()* i只能跨越0到8.这意味着VALUES [9]会比任何时候更经常地等于原来的VALUES [9]其他元素将等于其各自的元素(等等越来越可能被交换,因为我越来越小)。

我只是想更正上面的答案,而不是权重元素的数组:

 for(int i=0; i <= VALUES.length - 1; i++){ int rand = (int) (Math.random()*(VALUES.length-1)); char temp = VALUES[i]; VALUES[i] = VALUES[rand]; VALUES[rand] = temp; 

现在,shuffle执行VALUES.length次(或者你喜欢的次数),并且不偏向数组中的任何特定元素。