作为我项目的一部分,我需要通过给出一组数字来创建非重复的2或3位随机数.我不想为此实现列表或数组,因为每个函数调用我应该得到1个随机数.
我尝试使用SecureRandom类的Java来做到这一点.我也得到了一些网站的帮助,但是我被困在中间,我们可以洗掉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);
}
Run Code Online (Sandbox Code Playgroud)
Man*_*noj 12
Fisher-yates shuffle算法是要走的路.它有效地改组.它在线性时间内工作.
这是算法
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]
Run Code Online (Sandbox Code Playgroud)
和代码
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7427 次 |
| 最近记录: |