对于我的作业,我需要使用随机(种子)生成一个包含不同 4 位数字的整数数组。请注意,generateSecretDigits 方法是在类里面开始的,但必须在家里完成(我不记得哪一部分是在类里面完成的)。
我的教授给了我们例子来检查我们的方法是否有效。尽管我的程序生成了 4 位数字的代码,但它并没有显示与提供的示例相同的整数数组。有人可以帮我找出错误吗?
提供的示例:
- generateSecretDigits(45) 返回数组 {9, 1, 0, 7}
- generateSecretDigits(987) 返回数组 {5, 8, 9, 7}
我的代码:
// Declare the required import statements
import java.util.Random;
public class BullsAndCows {
public static void main (String[] args) {
int[] y = generateSecretDigits(45);
for (int i = 0; i < y.length; i++) {
System.out.print(y[i] + " ");
}
System.out.println();
}
// A method that randomly generates a secret 4-digits number
public static int[] generateSecretDigits(int x) {
/* Declare and initialize an array
* Assign a default value that is not between 0 and 9 inclusively to each element of the array */
int[] secretDigits = new int[4];
secretDigits[0] = 10;
secretDigits[1] = 10;
secretDigits[2] = 10;
secretDigits[3] = 10;
// Generate a number between 0 and 9 inclusively with the provided seed
int seed = x;
Random digit = new Random(seed);
for (int i = 0; i < secretDigits.length; i++) {
int secret = digit.nextInt(9);
// Assign a value to each element of the array
/* The contains() method takes as input an array of integers and a
* specific integer. The method returns true or false depending if an
* element is contained within a given array. Note that I have tested
* the contains() method and it works perfectly */
if (contains(secretDigits, secret) == false) {
secretDigits[i] = secret;
}
else {
i--;
}
}
return secretDigits;
}
最佳答案
随机
是 pseudorandom number generator它使用种子、加法和乘法输出数列。查看 OpenJDK 11 Random
类,公式为:
nextseed = (oldseed * multiplier + addend) & mask;
其中乘数
、加数
和掩码
是常量:
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
除非您更改公式或常数:
要么问题描述有错误,要么你必须自己实现伪随机数生成器来输出特定数字。
关于java - 随机种子产生与预期不同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55105371/