gpt4 book ai didi

java - 用Java制作一个13位随机数生成器

转载 作者:行者123 更新时间:2023-11-29 09:53:42 44 4
gpt4 key购买 nike

我在 Uni 的一个 friend 想要生成一组 13 位数字,这样他就可以测试他的排序算法,但是这样做的时间很长,所以我尝试使用以下代码来生成一个可设置的 13 位数字。

public class random {

public static void main(String[] args) {

long intArray[] = new long[20]; // to generate more than 20 random numbers increase this and the 'i < 20' to the same number ie. 75

for(int i = 0; i < 20; i++) { // here
intArray[i] = numbGen();
}

for(int j = 0; j < intArray.length; j++) {
System.out.println(intArray[j]);
}

}

public static long numbGen() {

long numb = (long)(Math.random() * 10000000 * 1000000); // had to use this as int's are to small for a 13 digit number.

return numb;
}
}

我现在的问题是有时它会在 20 组中生成几个 12 位数字,我想找到一种方法,如果它不是 13 位数字,则不将其添加到数组中。我试过 if 语句,但无法确定 Long 的长度(单个字符)。

提前致谢。

最佳答案

一个简单的解决方案:

    while(test < 10000) {
long num = (long) (Math.random() * 100000000 * 1000000);
if(Long.toString(num).length() == 13) {
return num;
}
test++;
}

但是,更好的解决方案是:

long number = (long) Math.floor(Math.random() * 9000000000000L) + 1000000000000L;

这只会生成随机的 13 位数字,您无需检查是否有更多或更少的数字。

请注意,此解决方案可能无法扩展到更多位数,并且可能无法返回完美分布的随机数。

关于java - 用Java制作一个13位随机数生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24037692/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com