The problem of random number generation in Java

Source: Internet
Author: User
Tags array length

"Generate random number sequence"

We can only use the Math.random () method to generate only a double type floating-point number between [0,1].

But what if we want to generate a random integer between [min, Max]?

At this point you can use:

int rdmnum = (int) (Math.random () * (max + 1-min) + min);

"Random number generator (duplicate random number Present)"

 public  static  int  [] Createrandomarray (int  arrlength, int  Rdmmin, int   Rdmmax) {
//based on the given array length, generate the desired array int [] arr = new int [arrlength";
Assigns a random value to an array for (int i = 0; i < Arr.le Ngth; I++) {Arr[i] = (int ) (Math.random () * (RDM Max + 1-rdmmin) + rdmmin);
//returns this array return arr;

"No repetition of the random number generator (more than 100,000 elements, the more strenuous.) This production device is relatively dead, the range is [0,length] between the number of) "

 Public Static int[] Createrandomnorepeatarray (intlength) {Random RDM=NewRandom (); //Random number Array    int[] arr =New int[length]; //storing an ordered set of numberslist<integer> list =NewArraylist<integer>(); //Random Index    intindex = 0;  for(inti = 0; i < length; i++) {list.add (i); }     for(inti = 0; i < length; i++) {Index= Rdm.nextint (Length-i); Arr[i]=List.get (index);    List.remove (index); }    returnarr;}

The problem of random number generation in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.