简体   繁体   English

如何使用mod运算符在输入范围之间生成随机数?

[英]How do I generate a random number between an inputted range using the mod operator?

I'm trying to figure out how to generate a number between a range predefined by the user using the mod operator. 我试图弄清楚如何使用mod运算符在用户预定义的范围之间生成数字。

What I do not want 我不想要的

int min = input.nextInt();
int max = input.nextInt();

Random r = new Random();
int X = r.nextInt(max - min + 1) + min;

What I want, something akin to a traditional int X = gen.nextInt() % 100 + 1; 我想要什么,类似于传统的int X = gen.nextInt()%100 + 1; but instead using values for Max and Min. 而是使用Max和Min的值。

Here is what I have so far 这是我到目前为止所拥有的

import java.util.*;

public class Modulus
{// begin class
    public static void main(String[] args)
    {// begin  main
    Scanner input;
    int max, min, range;
    Random gen;

    gen = new Random();


    input = new Scanner(System.in);

    System.out.println("Please enter a max value: ");
    max = input.nextInt();
    // Ask user to input max value

    System.out.println(" Please enter a minimum value: ");
    min = input.nextInt();
    // Ask user to input min value

     range = gen.nextInt() % (Unknown) 
    // Get random integer between min and max values using %


    System.out.println(" Your generated number is: " + range );






    } 
//end main
}
//end class

Can anyone explain how I might be able to accomplish this using the mod operator? 任何人都可以解释我如何使用mod运算符完成此操作?

You can use the Math.abs() function. 您可以使用Math.abs()函数。

ie

public static int genRandom(int mod){
  Random r = new Random();
  return Math.abs(r.nextInt()) % mod + 1;
}

and plug your high number as a parameter. 并将您的高号作为参数插入。 The caveat to this is it works only with non-negative values. 需要注意的是,它只适用于非负值。

This 这个

 range = Math.abs(gen.nextInt() % (max - min + 1)) + min 

will get what you want. 会得到你想要的。 The % operator returns a value from 0 to max-min if nextInt returns a positive number or 0, or from 0 to -(max-min) if nextInt returns a negative. 如果nextInt返回正数或0,则%运算符返回0max-min的值,如果nextInt返回负数,则返回0-(max-min) So abs will return a number in the range 0 to max-min , and adding min gets you a number in the range min to max . 所以abs将返回0max-min范围内的数字,并且添加min会得到一个minmax范围内的数字。

I don't recommend doing it this way, though. 不过,我不建议这样做。 When you generate a random integer from a set of M integers, and then use % to reduce it to a set of N integers, the resulting distribution will not be uniform if M is not divisible by N. Some results will show up more often than others. 当您从一组M个整数生成随机整数,然后使用%将其减少为一组N个整数时,如果M不能被N整除,则得到的分布将不均匀。某些结果将比其他。 I'm not sure why you don't want to use gen.nextInt(max - min + 1) , but it's the right tool for the job. 我不确定你为什么不想使用gen.nextInt(max - min + 1) ,但它是适合这项工作的工具。

EDIT: The right way to do something like this would be: if you have a way to generate a random number in the range 0 to M-1 inclusive, and you need one in the range 0 to N-1 inclusive, then you need to pick only numbers in the range 0 to N*(M/N)-1 [where M/N is an integer division that truncates], and if the generator picks a number in the range N*(M/N) to M-1, loop back and try again. 编辑:做这样的事情的正确方法是:如果你有办法生成0到M-1范围内的随机数,你需要一个0到N-1范围内的随机数,那么你需要仅选择0到N *(M / N)-1范围内的数字[其中M / N是截断的整数除法],如果生成器选择范围为N *(M / N)到M的数字-1,循环返回并重试。 Then when you use the % N operator on the result you will get a uniform distribution. 然后,当您在结果上使用% N运算符时,您将获得均匀分布。 (This algorithm has to be adjusted if the generator can generate negative values.) The code for Random.nextInt(int n) does exactly this; (如果生成器可以生成负值,则必须调整此算法。) Random.nextInt(int n)的代码正是这样做的; here's a comment from the JRE source: 这是来自JRE来源的评论:

 * The algorithm is slightly tricky. It rejects values that would result * in an uneven distribution (due to the fact that 2^31 is not divisible * by n). The probability of a value being rejected depends on n. The * worst case is n=2^30+1, for which the probability of a reject is 1/2, * and the expected number of iterations before the loop terminates is 2. 

So since nextInt(n) does the necessary work, the only reason not to use it would be if it's homework and you're not allowed to. 因此,由于nextInt(n)做了必要的工作,所以不使用它的唯一原因就是如果它是家庭作业并且你不被允许。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM