4

我正在尝试生成一个大于和小于前一个随机数的随机数,但无法弄清楚如何。

到目前为止我有这个:

number = (int)( max * Math.random() ) + min;
guess = (int)( max * Math.random() ) + min;
if (guess<number)
   {
      guess = (int)( max * Math.random() ) + min;
      System.out.println(guess);
    }
else if (guess>number)
 {
      guess = (int)( max * Math.random() ) + min;
     System.out.println(guess);
 }

更新:我如何确保它不会生成它已经生成的随机数?计算机有 10 次尝试猜测生成的数字,但我想让它变得合乎逻辑,因为它不会生成它已经知道是错误的数字。

4

4 回答 4

3

订购随机数列表怎么样...

public static void method2() throws Exception {
    Random rng = new SecureRandom();
    Set<Integer> numbers = new HashSet<>();
    while (numbers.size() < 3) {
        // number only added if not already present in Set, set values are unique
        numbers.add(rng.nextInt(MAX));
    }
    List<Integer> numberList = new ArrayList<>(numbers);
    Collections.sort(numberList);
    // lower random at index 0, mid at index 1
    // you can guess where the other one is hiding 
    System.out.println(numberList);
}

我先把它们放在一组中,以确保没有重复。当然,如果MAX值为 1,这可能需要一段时间。

这种方法的一个优点是数字应该很好地分布在 0 到 MAX 之间。如果您直接使用范围,那么您必须处理上限和下限。

当然,这种方法也可以很容易地扩展到在范围内工作,只要值的最大值(显着)高于列表中的数字数量(在本例中仅为 3)。

于 2014-10-31T00:46:30.797 回答
0

If the computer player receives information that its guess is either too low or too high (or correct), you need to keep track of the range of possible values that the correct value could be. Initially, this is the entire range, min..max. Once you guess a value that is incorrect, you move either min or max:

if (guess<number)
{
   min = guess + 1; // Don't guess any more number <= guess
}
else if (guess>number)
{
   max = guess - 1; // Don't guess any more number >= guess
}
else
{
   // I WIN!!
}

Now you you always have the correct range for valid guesses between min and max.

Now, your logic to generate random numbers within the range seems to be a bit off. This answer to the question linked in @Solver's answer has the correct logic:

guess = (int)( (max - min) * Math.random() + 1) + min;
于 2014-10-31T21:27:27.153 回答
-1

您可以在获取随机数时指定最小值和最大值,如下所示:如何在 Java 中生成特定范围内的随机整数?

于 2014-10-31T00:44:19.023 回答
-1

这将始终返回如下数字:less <= number <= more

  number = (max * Math.random()) + min;
  less = (number * Math.random()) + min;
  more = ((max - number) * Math.random()) + number;

编辑:误解了这个问题。

于 2014-10-31T00:42:21.650 回答