Multiple algorithms for sampling random numbers in Java _java

Source: Internet
Author: User
Tags stringbuffer

This chapter first explains several ways to generate Java random numbers, and then demonstrates them through an example.

Overview:

What's so hard about generating random numbers here? is not the direct use of Java encapsulated a good random on the line? Of course, for the general situation is OK, and this article to explain these algorithms are also based on this random library function.

This article is mainly about the behavior of sampling, and the sample itself has an implied rule is not to have duplicate data. Well, with these instructions. You can start by trying to generate random numbers without repeating yourself.

Algorithm attempts:

Some good algorithms appear, often accompanied by some not so good algorithm. But for the effect of the algorithm is not very good, they generally have a common, easy to understand and realize. Here is a step-by-step way to make a simple statement.

First attempt: Naïve stochastic algorithm

This algorithm is very good to understand, is random! Each time a random number is generated and the collection is added.

 private void Simplerandom (int start, int end, int count) { 
    System.out.println ("Naïve Random Algorithm:"); 
    StringBuffer buffer = new StringBuffer (); 
    for (int i = 0; i < count; i++) { 
      int random = Numberutils.randominteger (start, end); 
      Buffer.append (i = = 0?) ("[" + Random): ("," + Random)); 
    } 
    Buffer.append ("]"); 
    SYSTEM.OUT.PRINTLN (buffer); 
   

Second attempt: Checking for the existence of random algorithms

We know that there is a problem with the above method, that is, there may be duplicate data. So, we thought, when we generate a random number, we check if the number is already there, and regenerate it if it exists.

private void Checkrandom (int start, int end, int count) { 
    System.out.println ("Check for presence Random algorithm:"); 
    StringBuffer buffer = new StringBuffer (); 
    list<integer> save = new arraylist<> (); 
    for (int i = 0; i < count; i++) { 
      int random = Numberutils.randominteger (start, end); 
      if (Exits (save, Random)) { 
        i--; 
        Continue; 
      } 
       
      Save.add (random); 
      Buffer.append (i = = 0?) ("[" + Random): ("," + Random)); 
    } 
    Buffer.append ("]"); 
    SYSTEM.OUT.PRINTLN (buffer); 
   

Third attempt: element removal stochastic algorithm

The above algorithm has solved the problem of duplication of data. However, there is a very bad problem is that it may take us a long time to generate a random number of samples (this will look at the face ...). )。

However, here we have a new idea. That is to go to a random number in a set, when this is selected to remove, then the next time random again will not be random to this number? This solves the problem of repetition of random numbers well. The code is as follows:

 private void Removerandom (int start, int end, int count) { 
    System.out.println ("element remove random algorithm:"); 
    StringBuffer buffer = new StringBuffer (); 
    list<integer> numbers = initlist (start, end); 
    for (int i = 0; i < count; i++) { 
      int random = Numberutils.randominteger (count-i); 
      Buffer.append (i = = 0?) ("[" + Numbers.get (Random)): ("," + numbers.get (random))); 
      Numbers.remove (random); 
    } 
     
    Buffer.append ("]"); 
    SYSTEM.OUT.PRINTLN (buffer); 
   

Fourth attempt: state transition stochastic algorithm

In many of my previous blogs, there was a state transition process in the algorithm. And the transfer of state is one of my favorite algorithms. Figure 1 below shows the range of values for the random number, and the orange number in the sequence is the random sequence in the result. The bottom sequence has some dotted arrows that represent the transition of the state.

Fig. 1 Algorithm of sampling random number generation based on state transition

Implementation code:

 private void Statusrandom (int start, int end, int count) {System.out.println ("state-turn 
    Shift random algorithm: "); 
    StringBuffer buffer = new StringBuffer (); 
    int[] Status = new Int[end + 1]; 
      for (int i = 0; i < count; i++) {int random = Numberutils.randominteger (start, end); 
      SYSTEM.ERR.PRINTLN (random); if (status[random] = = 0) {Buffer.append (i = = 0?) 
        ("[" + Random): ("," + Random)); Status[random] = Random = = end? Start: (random + 1); 
        It is not possible to have the number before start} else {//state transfer int index = random; 
        do {index = Status[index]; 
         
        while (Status[index]!= 0); Buffer.append (i = = 0?) 
        ("[" + Index): ("," + Index)); Status[index] = index = = end? Start: (index + 1); 
    It is not possible to have the number before start} buffer.append ("]"); 
  SYSTEM.OUT.PRINTLN (buffer); } 

Fifth attempt: recursive Floyd stochastic algorithm

The Floyd algorithm is also a state transfer process in the final analysis. The algorithm would require a list or array to be entered to hold the determined random number. As the name suggests, here I will use the recursive solution. In the process of recursion, we transfer the state of the first random number to the first i-1 random body. The code is as follows:

Private list<integer> Simplefloyd (list<integer> List, int count, int start, int end) { 
    if (count = = 0) {
   return list; 
    } 
    List = Simplefloyd (list, count-1, start, end-1); 
    int random = Numberutils.randominteger (start, end); 
    if (List.contains (random)) { 
      list.add (end); 
    } else { 
      list.add (random); 
    } 
    return list; 
  } 

Sixth attempt: iterative Floyd stochastic algorithm

The idea is similar to the recursive Floyd stochastic algorithm above, but here we add a variable to do the optimization. There is no need for recursion. The code is as follows:

Private list<integer> Iterationfloyd (int start, int end, int count) { 
    System.out.println ("Iterative Floyd Random Algorithm:"); 
    list<integer> list = new arraylist<> (); 
    for (int i = End-count + 1; i < end; i++) { 
      int random = Numberutils.randominteger (start, i); 
      if (List.contains (random)) { 
        list.add (i); 
      } else { 
        list.add (random); 
     
    }} return list; 
  

Test results:

Fig. 2 Random number generation algorithm test results

In the above test results, we can clearly see that naïve random algorithms not only have duplicate data, but also the most time-consuming. Therefore, in the random number of samples generated, avoid the use of this algorithm. In the latter several algorithms, the optimal state-transfer stochastic algorithm is followed by the iterative Floyd stochastic algorithm. This can be done according to personal preference.

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.