Java random decimation N number _java in specified range

Source: Internet
Author: User
Tags abs current time generator

How to generate random numbers in Java
1, in the J2SE using Math.random () to randomly select a 0~1 between a double decimal, multiply it by a number, such as 25, you can get a 0~25 range of random numbers, this in the J2ME did not;

int randomnumber = (int) math.round (Math.random () * (max-min) +min); 

2. In the system class, there is a Currenttimemillis () method that returns the number of milliseconds from January 1, 1970 0:0 0 to the current one long, as a random number, and it can be modeled on some numbers to limit the range of random numbers In this way, when multiple random numbers are generated at the same time in the loop, they are the same value and have certain limitations!

Long randomnum = System.currenttimemillis (); 
int randomnumber = (int) randomnum% (max-min) +min; 

3, the use of java.util.Random class to produce a random number generator, this is also our program in the J2ME often used in a random number of methods. It has two forms of constructors, namely random () and random (long Seed). Random () uses the current time, System.currenttimemillis () as the seed of the generator, and Random (long Seed) uses the specified seed as the seed of the generator. After the random number generator (Random) object is produced, different types of random numbers are obtained by calling different Method:nextint (), Nextlong (), Nextfloat () and nextdouble (). If two random objects use the same seed (for example, all 25) and call the same function in the same order, they return exactly the same value.

Random Random = new Random (); 

n A number of non-duplicates within a given range of random
1, method one: The simplest and easiest to understand the double cycle to weight

/** 
 * The 
 simplest and most basic method * 
 @param min Specified range minimum 
 * @param max specified range maximum 
 * @param n random number of values 
 */
   public Static int[] Randomcommon (int min, int max, int n) { 
  if (n > (max-min + 1) | | Max < min) { 
      Retu RN null; 
    } 
  Int[] result = new Int[n]; 
  int count = 0; 
  while (Count < n) { 
    int num = (int) (Math.random () * (max-min)) + min; 
    Boolean flag = true; 
    for (int j = 0; J < N; j +) { 
      if (num = Result[j]) { 
        flag = false; 
        break; 
      } 
    } 
    if (flag) { 
      result[count] = num; 
      count++ 
    } 
  } 
  return result; 

2, method Two: Use HashSet characteristics, can only hold different values

/** 
 * A random number of n not repeated in the range 
 * Use hashset characteristics, can only hold a different value 
 * @param min specified range minimum 
 * @param max specified range maximum 
 * @param n random number Number 
 * @param hashset<integer> set random number result set 
 * 
  /public static void Randomset (int min, int max, int n, hashset <Integer> set) { 
    if (n > (max-min + 1) | | Max < min) {return 
      ; 
    } 
    for (int i = 0; i < n; i++) { 
      //Call Math.random () method 
      int num = (int) (Math.random () * (max-min)) + min; 
      Set.add (num);//The different number is deposited in HashSet 
    } 
    int setSize = Set.size (); 
    If the number of deposits is less than the number of specified builds, then the call recursively generates the remaining number of random numbers so that it loops until the specified size is reached 
    if (SetSize < n) { 
    randomset (min, Max, n-setsize, set) ;//Recursive 
    } 
  }

3, method Three: Excluding the number of random to

/** 
 * Random number of n not repeated in a specified range * Randomly generating a number in the initialization of an array to be selected in the 
 result, 
 * Replaces the number of the array to be randomly selected, substituting the number corresponding to the subscript for the selected array (len-1) 
 * And then randomly generate the next random number from the len-2. 
 * @param max Specify range maximum 
 * @param min specified range minimum 
 * @param n random number 
 * @return int[] Random number result set 
 * 
/public static int[] Randomarray (int min,int max,int n) { 
  int len = max-min+1; 
   
  if (Max < min | | | n > Len) {return 
    null; 
  } 
   
  Initializes the selected array of the given range 
  int[] Source = new Int[len]; 
    for (int i = min; i < Min+len; i++) { 
    source[i-min] = i; 
    } 
     
    Int[] result = new Int[n]; 
    Random rd = new Random (); 
    int index = 0; 
    for (int i = 0; i < result.length i++) { 
    //array 0 to (len-2) random one subscript 
      index = Math.Abs (rd.nextint ()% len--); 
      Put the random number into the result set 
      result[i] = Source[index]; 
      Replaces the number of random numbers in the selected array with the number corresponding to the subscript of the selected array (len-1) 
      source[index] = Source[len]; 
    } 
    return result; 

Invoke instance:

  public static void Main (string[] args) { 
  int[] reult1 = Randomcommon (20,50,10); 
  for (int i:reult1) { 
    System.out.println (i); 
  } 
   
  int[] Reult2 = Randomarray (20,50,10); 
  for (int i:reult2) { 
    System.out.println (i); 
  } 
   
  hashset<integer> set = new Hashset<integer> (); 
  Randomset (20,50,10,set); 
    for (int j:set) { 
    System.out.println (j); 
  } 

Third, sample code

Package test;

Import Java.util.HashSet;



Import Java.util.Random; public class Snippet {/** * random number of n repeats in a randomly specified range * A number is randomly generated into the result in the initialization-free array. * Replaces the number of the array to be randomly selected with the number corresponding to the subscript of the selected array (len-1) * and then Randomly generating the next random number from the len-2, so the * @param max Specifies the range maximum * @param min specified range minimum * @param n random number * @return int[] Random number Result set */PU

 

 Blic static int[] Randomarray (int min,int max,int n) {int len = max-min+1;

 if (Max < min | | | n > len) {return null;

     }//Initialize the array int[of the given range] Source = new Int[len];

     for (int i = min; i < Min+len; i++) {source[i-min] = i;

     } int[] result = new Int[n];

     Random rd = new Random ();

     int index = 0;

  for (int i = 0; i < result.length i++) {//To be selected array 0 to (len-2) random one subscript int s=rd.nextint ()%len;

       System.out.print (s--+ ",");

index = Math.Abs (Rd.nextint ()%len--);

       SYSTEM.OUT.PRINTLN (index);

       Put the random number into the result set result[i] = Source[index]; The number that is randomly arrived in the array to be selected, and the number that corresponds to the subscript of the selected array (len-1)Change Source[index] = Source[len];

 return result;

public static void Main (string[] args) {//int[] Reult1 = Randomcommon (20,50,10);

for (int i:reult1) {//System.out.println (i);

  } int[] Reult2 = Randomarray (0,4,5);

  for (int i:reult2) {System.out.print (i);

}//Hashset<integer> set = new hashset<integer> ();

Randomset (20,50,10,set);

for (int j:set) {//System.out.println (j);
 //  }

  }

}

The above is the entire content of this article, I hope to learn Java program to help you.

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.