随机种子产生预期的不同数量

时间:2019-03-11 15:33:45

标签: java random-seed

对于我的作业,我需要使用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;
  }

1 个答案:

答案 0 :(得分:0)

Randompseudorandom number generator,它使用种子,加法和乘法输出数字序列。查看OpenJDK 11 Random类的公式是:

nextseed = (oldseed * multiplier + addend) & mask;

其中multiplieraddendmask是常量:

private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;

除非您更改公式或常量:

问题描述有误,或者您必须自己实现伪随机数生成器以输出特定数字。

相关问题