Как сгенерировать случайное значение из входа? - PullRequest
0 голосов
/ 12 марта 2020

Я ищу способ генерирования случайного значения из заданного ввода на основе начального числа. Я приведу пример кода для того, чего я пытаюсь достичь:

public class Seed {

  public double generateRandom(double input) {
    // What goes in here?
  }

}

Вот как может выглядеть пример программы:

public static void main(String[] args) {
  Seed seed1 = new Seed(), seed2 = new Seed();

  System.out.println("Result of seed 1 with 69: " + seed1.generateRandom(69));
  System.out.println("Result of seed 2 with 69: " + seed2.generateRandom(69));
  System.out.println("Result of seed 1 with 420: " + seed1.generateRandom(420));
  System.out.println("Result of seed 2 with 420: " + seed2.generateRandom(420));

  System.out.println("Result of seed 1 with 69 is still: " + seed1.generateRandom(69));
  System.out.println("Result of seed 2 with 69 is still: " + seed2.generateRandom(69));
}

Вывод:

Result of seed 1 with 69: 0.5
Result of seed 2 with 69: 0.65
Result of seed 1 with 420: 0.2
Result of seed 2 with 420: 0.34
Result of seed 1 with 69 is still: 0.5
Result of seed 2 with 69 is still: 0.65

Как будет выглядеть класс Seed?

Ответы [ 2 ]

3 голосов
/ 12 марта 2020

Ну, пример реализации может выглядеть примерно так:

public class Seed {

  private long seed = new Random().nextLong();

  public double generateRandom(long input) {
      return new Random(seed + input).nextDouble();
  }
}

Обратите внимание, что параметр generateRandom в этой реализации равен long.

0 голосов
/ 12 марта 2020

Можем ли мы использовать что-то вроде этого:

class Demo {

    public double generateRandom(double input) {
        return ThreadLocalRandom.current().nextDouble(input);
    }

    /**
     *
     * @param input start of the random random number generated
     * @param bound upper bound of the random number generated
     * @return
     */
    public double generateRandom(double input, double bound) {
        return ThreadLocalRandom.current().nextDouble(input);
    }

    public static void main(String[] args) {
        System.out.println( new Demo().generateRandom(10));
        System.out.println( new Demo().generateRandom(10,15));
    }

}

Ссылка https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadLocalRandom.html#nextDouble (double,% 20double)

...