Calculates and returns a random integer array with Min as the upper limit of Max.

Source: Internet
Author: User

Import java. util. arrays;
Import java. util. Random;

/**
* <Code> randomutil </code>-random tool class.
* @ Author sagezk
* @ Version 1.0
*/
Public class randomutil {

Private randomutil (){}

Private Static random RND = NULL;

/**
* Initialize the random number generator.
*/
Private Static void initrnd (){
If (RND = NULL) RND = new random ();
}

/**
* Calculates and returns a random integer array with <code> min </code> as the lower <code> max </code> as the upper limit.
* @ Param min minimum random INTEGER (inclusive)
* @ Param Max random integer upper limit (inclusive)
* @ Param Len result array Length
* @ Return result Array
*/
Public static int [] getlotteryarray (INT min, int Max, int Len ){
// Parameter verification and performance optimization
If (LEN <0) return NULL; // The array with a length less than 0 does not exist.
If (LEN = 0) return New int [0]; // returns an array with a length of 0
If (min> MAX) {// calibration parameter min max
Int T = min;
Min = max;
Max = T;
}
Final int Len = max-min + 1; // Number of Seeds
If (LEN> Len) return NULL; // If 35 or 36 appears, null is returned.
// Calculate a random array without repeated values
Initrnd (); // initialize the random number generator
Int [] seed = new int [Len]; // seed Array
For (INT I = 0, n = min; I <Len;) seed [I ++] = n ++; // initialize the seed Array
For (INT I = 0, j = 0, T = 0; I <Len; ++ I ){
J = RND. nextint (LEN-I) + I;
T = seed [I];
Seed [I] = seed [J];
Seed [J] = T;
}
Return arrays. copyof (seed, Len); // Note: copyof requires jre1.6
}

// Unit Testing
Public static void main (string [] ARGs ){
Final int n = 10000; // number of tests
For (INT I = 0; I <n; ++ I ){
Int [] La = randomutil. getlotteryarray (1, 35, 7 );
If (La = NULL) continue;
For (int v: La) system. Out. printf ("% 0 $ 02d", V );
System. Out. println ();
}
}

}

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.