java randomly selects the number of n not repeated in the specified range

  • 2020-05-05 11:18:34
  • OfStack

1.
for generating random Numbers in JAVA
1. Use Math.random () in j2se to make the system randomly select a decimal of double type between 0 and 1 and multiply it by a number, such as 25, to get a random number within the range of 0 to 25, which is not found in j2me.      


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

2. In the System class, there is an currentTimeMillis() method, which returns the number of milliseconds from January 1, 1970, 0 minutes, 0 seconds to the current long type. This method in the loop at the same time to generate a number of random Numbers, will be the same value, there is a certain limitation!  


long randomNum = System.currentTimeMillis(); 
int randomNumber = (int) randomNum%(max-min)+min; 

3. Use java.util.Random class to generate a random number generator, which is also a method we often use to pick random Numbers in j2me programs. It has two forms of constructors, Random() and Random(long seed). Random() USES the current time System.currentTimeMillis () as the generator seed, and Random(long seed) USES the specified seed as the generator seed. After the random number generator (Random) object is generated, different types of random Numbers are obtained by calling different method: nextInt(), nextLong(), nextFloat(), nextDouble(), etc. If two Random objects use the same seed (say, both 25) and call the same functions in the same order, they return exactly the same value.      


Random random = new Random(); 
int randomNumber = random.nextInt(max)%(max-min+1) + min; 

2. N non-repeating Numbers
in a randomly given range Method 1: the simplest and easiest to understand double cycle to deweight  


/** 
 *  Randomly assigned range N A number that doesn't repeat  
 *  The simplest and most basic way  
 * @param min  Specifies the range minimum  
 * @param max  Specified range maximum  
 * @param n  Random number  
 */ 
public static int[] randomCommon(int min, int max, int n){ 
  if (n > (max - min + 1) || max < min) { 
      return 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; 
} 

Method 2: use the characteristics of HashSet to store only different values  


/** 
 *  Randomly assigned range N A number that doesn't repeat  
 *  using HashSet Can only store different values  
 * @param min  Specifies the range minimum  
 * @param max  Specified range maximum  
 * @param n  Random 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() methods  
      int num = (int) (Math.random() * (max - min)) + min; 
      set.add(num);//  I'm going to put different Numbers in HashSet In the  
    } 
    int setSize = set.size(); 
    //  If the number stored is smaller than the specified number generated, the call recursively generates a random number of the remaining Numbers, and so on, until the specified size is reached  
    if (setSize < n) { 
    randomSet(min, max, n - setSize, set);//  recursive  
    } 
  }

Method 3: exclude the number  
that has arrived randomly


/** 
 *  Randomly assigned range N A number that doesn't repeat  
 *  A random number is generated in the initialized unrepeatable array and put into the result,  
 *  The number to which the pending array is randomly assigned. Use the pending array (len-1) I'm going to replace the subscript  
 *  Then from len-2 Generate the next random number at random, and so on  
 * @param max  Specified range maximum  
 * @param min  Specifies the 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 a candidate array for a 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++) { 
    // To choose an array 0 to (len-2) A random index  
      index = Math.abs(rd.nextInt() % len--); 
      // Put random Numbers into the result set  
      result[i] = source[index]; 
      // Take the number that is randomly selected from the pending array and use the pending array (len-1) I'm going to replace the subscript  
      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); 
  } 
} 

3. Sample code


package test;



import java.util.HashSet;

import java.util.Random;



public class Snippet {

 /**

 *  Randomly assigned range N A number that doesn't repeat 

 *  A random number is generated in the initialized unrepeatable array and put into the result, 

 *  The number to which the pending array is randomly assigned. Use the pending array (len-1) I'm going to replace the subscript 

 *  Then from len-2 Generate the next random number at random, and so on 

 * @param max  Specified range maximum 

 * @param min  Specifies the 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 a candidate array for a 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++) {

     // To choose an array 0 to (len-2) A random index 

     int s=rd.nextInt()%len;

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

       index = Math.abs(rd.nextInt()%len--);

//       System.out.println(index);

       // Put random Numbers into the result set 

       result[i] = source[index];

       // Take the number that is randomly selected from the pending array and use the pending array (len-1) I'm going to replace the subscript 

       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 help you learn java programming.


Related articles: