Two methods for generating random numbers without duplicates in Java

Source: Internet
Author: User

 

 

The first method is to randomly generate a number in an array to be selected, put it at the end of the array to be selected, and then randomly generate the next random number from length-1, and so on.

Public static int [] randoms ()
{
Random r = new random ();

Int temp1, temp2;
Int send [] = };
Int Len = Send. length;
Int returnvalue [] = new int [22];
For (INT I = 0; I <22; I ++)
{
Temp1 = math. Abs (R. nextint () % Len;
Returnvalue [I] = Send [temp1];
Temp2 = Send [temp1];
Send [temp1] = Send [len-1];
Send [len-1] = temp2;
Len --;
}
Return returnvalue;
}
}

Method 2: select a Fixed Array without duplicates and randomly change the positions of the array. After multiple times, the array is a random array without duplicates.

Public static int [] random2 ()
{
Int send [] = };
Int temp1, temp2, temp3;
Random r = new random ();
For (INT I = 0; I <send. length; I ++) // random exchange send. length times
{
Temp1 = math. Abs (R. nextint () % (send. Length-1); // randomly generate a location
Temp2 = math. Abs (R. nextint () % (send. Length-1); // randomly generate another location
If (temp1! = Temp2)
{
Temp3 = Send [temp1];
Send [temp1] = Send [temp2];
Send [temp2] = temp3;
}
}
Return send;
}
Related Article

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.