对于我的作业,我需要使用Random(seed)生成一个包含不同4位数字的整数数组。请注意,generateSecretDigits
方法是在课堂上开始的,但必须在家里完成(我不记得在课堂上完成了哪一部分)。
我的教授给了我们一些例子来检查我们的方法是否有效。尽管我的程序生成的是4位数字的代码,但是它没有显示与提供的示例相同的整数数组。有人可以帮我找到错误吗?
提供的示例:
我的代码:
// 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;
}
答案 0 :(得分:0)
Random
是pseudorandom number generator,它使用种子,加法和乘法输出数字序列。查看OpenJDK 11 Random
类的公式是:
nextseed = (oldseed * multiplier + addend) & mask;
其中multiplier
,addend
和mask
是常量:
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
除非您更改公式或常量:
问题描述有误,或者您必须自己实现伪随机数生成器以输出特定数字。