java - 我正在尝试生成一个随机的不同 3 或 4 位数字

标签 java random

我试图在 Java 中生成一个随机的不同的 3 或 4 位数字,而不使用循环、数组或方法(除了用于生成随机数的内置数学随机方法),只是基本的东西,如 if 语句。

我试过了

(int)(Math.random()*9899+100);

但它只返回 4 位模糊数字。 我所说的不同是指任何数字都不应重复。不允许使用 232、7277、889、191 等数字。但是像 1234、3456、8976、435 这样的数字是不同的并且是允许的

最佳答案

以下不会公平地生成数字,但可以生成任何 4 位数字,3 位数字中不会有 0。

// first digit between 0 and 9, if it's 0 we will have a 3 digit number
int first = (int)(Math.random() * 10);  

int second = (int)(Math.random() * 10);
// if it's the same as the first add one to it, use modulo to wrap around
if (first == second)
    second = (second + 1) % 10;

// the same as with second digit just with more checks
int third = (int)(Math.random() * 10);
if (third == first || third == second)
    third = (third + 1) % 10;
// if it's still the same, add one once more, after doing it a second time new digit is guaranteed 
if (third == first || third == second)
    third = (third + 1) % 10;

// the same as with second digit just with more checks
int fourth = (int)(Math.random() * 10);
if (fourth == first || fourth == second || fourth == third)
    fourth = (fourth + 1) % 10;
if (fourth == first || fourth == second || fourth == third)
    fourth = (fourth + 1) % 10;
if (fourth == first || fourth == second || fourth == third)
    fourth = (fourth + 1) % 10;

System.out.println(1000 * first + 100 * second + 10 * third + fourth);

您可以将新数字添加到自身而不是添加一个以获得更均匀的分布,它需要处理一些极端情况。

关于java - 我正在尝试生成一个随机的不同 3 或 4 位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61259755/

相关文章:

java - HTML 中的代码和问号转换

java - 马文 : Does project inheritance or aggregation better support this scenario?

java - 动态调用实现方法

java - JFrame 和 Nimbus 的外观和感觉

c++ - C++中的顺序随机数?

iphone - 在 Objective-C 中随机化 NSArray 的规范方法

c# - While 循环与 || 一起使用但不是&&,不明白为什么?

java - 在 Java 之间传递 Oracle clob

c++ - 如何在 C++ 中生成由负值和正值组成的范围内的随机数?

python - Pandas :将给定范围内的随机数分配给相等的列值