java - 随机种子产生与预期不同的数字

标签 java random-seed

对于我的作业,我需要使用随机(种子)生成一个包含不同 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/

相关文章:

java - 如何使用 IntegerProperty 在 JavaFX 中编辑单元格?

Java Apache IOUtils : how to delete a file after read it into a byte array?

python - 如何为 np.random.uniform 生成种子?

r - R 中的种子限制

python - 使用 tf.set_random_seed 在 Tensorflow 中可重现结果

python - 读取 jupyter 笔记本的随机种子

java - 在 Canvas 中居中 public void onDraw(Canvas canvas) 内的缩放位图

Java-Spring反射带来了类中不存在的方法

java - 如何在没有正则表达式的情况下从字符串中提取数字

c++ - 是否需要为每个线程或每个进程调用 srand() C 函数来为随机发生器设置种子?