Java randomly extracts a specified range of digital _java

Source: Internet
Author: User
Tags abs repetition

This article introduces how to implement the function of random no repetition number in Java. If you are a beginner, it is necessary to take a look at this article, because this feature is usually encountered in the interview. including myself in the recruitment of people also like to take this question to ask others, mainly to see the model and the basic knowledge of the problem.

I hope this article will give some help to the first-time friends, because I have contacted some friends either can't write, or use a very tiled way of thinking to achieve it.
It is only a matter of efficiency that a friend who has developed experience can achieve such a function. We generally in the face of such problems, always tile the direct sequence of association, mister into an array, and then add a random number to the array in a loop, and in the process of adding a number, look for the number in the array and add it directly to the array if it doesn't exist, if that number is not added. We generally consider the problem in this way, so that consideration can also realize the function, as I said just now, it is only a matter of efficiency.

To better understand this, let's take a look at the details: generate a random array of 1-100, but the numbers in the array cannot be repeated, that is, the position is random, but the array elements cannot be duplicated.

Here, without giving us the length of the array, we can let it be any length between 1-100.
Next, let's look at several implementations and compare these methods .
Usually we use ArrayList or arrays to see the ArrayList implementation process, as shown in the following code:

Import java.util.ArrayList;
Import Java.util.Random;

/** *
 using ArrayList to implement
 * @Description:

 * @File: Demo.java

 * @Package None

 * @Author Hanyonglu

 * Date 2012-10-18 pm 06:16:55

 * @Version V1.0
 *
/public class Demo {public
  static void Main (string[] Arg s) {
    object[] values = new OBJECT[20];
    Random Random = new Random ();
    arraylist<integer> list = new arraylist<integer> ();

    for (int i = 0; i < values.length;i++) {
      int number = Random.nextint (m) + 1;
      
      if (!list.contains (number)) {
        list.add (number);
      }
    }
    
    Values = List.toarray ();
    
    Iterate through the array and print the data for
    (int i = 0;i < values.length;i++) {
      System.out.print (Values[i] + "T");
      
      if ((i + 1)% = = 0) {
        System.out.println ("\ n");}}}


The procedure for using an array implementation is the following code:

 import java.util.Random; /** * @Description Using array *: * @File: Demo4.java * @Package None * @Author Hanyonglu * @Date 2012-10-18 06:27:
    @Version V1.0/public class Demo4 {public static void main (string[] args) {int[] values = new INT[20];
    
    Random Random = new Random ();
      
      for (int i = 0;i < values.length;i++) {int number = Random.nextint (100) + 1;
        for (int j = 0;j <= i;j++) {if (number!= values[j]) {values[i]=number; }///traverse array and print data for (int i = 0;i < values.length;i++) {System.out.print (v
      
      Alues[i] + "T");
      if ((i + 1)% = = 0) {System.out.println ("\ n"); }
    }
  }
}

The above two implementation processes are less efficient. Because every time you add it, go through the current list to see if this number exists, and the time complexity is O (n^2). We can think about this: since there is no duplication involved, we can think about the functions of HashSet and HashMap. HashSet implements the set interface, and set is mathematically defined as a collection of no repetition, no order. and HASHMAP implementation of map, is not allowed to duplicate key. This enables us to use HashMap or hashset.
When using the HashMap implementation, simply convert its key to an array of OK, the following code:

Import Java.util.HashMap;
Import Java.util.Iterator;
Import Java.util.Random;

Import Java.util.Map.Entry; /** * @Description using HashMap: * @File: Demo.java * @Package None * @Author Hanyonglu * @Date 2012-10-18 pm 06
    : 12:50 * @Version V1.0/public class Demo {public static void main (string[] args) {int n = 0;
    
    Object[] values = new OBJECT[20];
    Random Random = new Random ();
    
    Hashmap<object, object> HashMap = new Hashmap<object, object> ();
      Generate random numbers and deposit hashmap for (int i = 0;i < values.length;i++) {int number = Random.nextint (100) + 1;
    Hashmap.put (number, i);
    
    ///import array from HashMap values = Hashmap.keyset (). ToArray ();
      
      Iterate through the array and print the data for (int i = 0;i < values.length;i++) {System.out.print (Values[i] + "T");
      if ((i + 1)% = = 0) {System.out.println ("\ n");
}//Iterator ITER = Hashmap.entryset (). iterator (); Traverse HashMap//while (Iter.hasnext ()) {//Entry<integer, integer> Entry = (Entry) iter.next ();//int key = Entry.getkey ();//
n++;
System.out.print (key + "T");

 if (n% = 0) {//System.out.println ("\ n");//}//}}

Because the relationship between HashSet and HashMap is too close, hashset at the bottom is to use hashmap to achieve, but there is no set of value, only a set of key, so you can also use HashSet to implement, the following code:

Import Java.util.HashSet;
Import Java.util.Random;

/** *
 using HashSet to implement
 * @Description:

 * @File: Test.java

 * @Package None

 * @Author Hanyonglu

 * Date 2012-10-18 pm 06:11:41

 * @Version V1.0
 *
/public class Test {public
  static void Main (string[] Arg s) {
    Random Random = new Random ();
    Object[] values = new OBJECT[20];
    hashset<integer> hashset = new hashset<integer> ();
    
    Generate random numbers and deposit hashset for
    (int i = 0;i < values.length;i++) {
      int number = Random.nextint (m) + 1;
      Hashset.add (number);
    }
    
    Values = Hashset.toarray ();
    
    Iterate through the array and print the data for
    (int i = 0;i < values.length;i++) {
      System.out.print (Values[i] + "T");
      
      if ((i + 1)% = = 0) {
        System.out.println ("\ n");}}}


This is a little more efficient. If we limit the length of the array, we just need to transform the for loop and set it to the Whlie loop. As shown below:

Import Java.util.HashSet;
Import Java.util.Random;

/** *
 using HashSet to implement
 * @Description:

 * @File: Test.java

 * @Package None

 * @Author Hanyonglu

 * Date 2012-10-18 pm 05:11:41

 * @Version V1.0
 *
/public class Test {public
  static void Main (string[] Arg s) {
    Random Random = new Random ();
    Object[] values = new OBJECT[20];
    hashset<integer> hashset = new hashset<integer> ();
    
    Generates a random number and deposits hashset while
    (Hashset.size () < values.length) {
      Hashset.add (Random.nextint (1));
    
    values = Hashset.toarray ();
    
    Iterate through the array and print the data for
    (int i = 0;i < values.length;i++) {
      System.out.print (Values[i] + "T");
      
      if ((i + 1)% = = 0) {
        System.out.println ("\ n");}}}


We can set the length of the array to 100 to verify the effect of the operation, as shown in the following figure:

The above several comparisons, the use of HASHMAP efficiency is relatively high, is actually hashset, again is an array, and finally ArrayList. If we generate 10,000 data, we will find that the time spent using HashMap is: 0.05s,hashset is 0.07s, the array is: 0.20s, and ArrayList is 0.25s. Interested can set the time to check.
Of course, there are other efficient ways in addition to using HASHMAP implementations. For example, we can store 1-100 of these numbers in an array and then randomly generate two subscripts in the For loop, and if the two subscripts are not equal, you can swap the elements in the array, and the implementation process looks like this:

Import Java.util.Random; /** * @Description: * @File: Demo4.java * @Package None * @Author Hanyonglu * @Date 2012-10-18 PM 06:5 4:06 * @Version V1.0 */public class Demo4 {public static void main (string[] args) {int values[] = new INT[100]  
    ;  
    int Temp1,temp2,temp3;  
    
    Random r = new Random ();
    for (int i = 0;i < values.length;i++) {Values[i] = i + 1; }///random switch values.length for (int i = 0;i < values.length;i++) {Temp1 = Math.Abs (R.nextint ())% (VA LUES.LENGTH-1); Randomly generated a position temp2 = Math.Abs (R.nextint ())% (values.length-1);  
        Randomly generating another position if (Temp1!= temp2) {Temp3 = Values[temp1];  
        VALUES[TEMP1] = VALUES[TEMP2];
      VALUES[TEMP2] = Temp3;
      
      }///traverse the array and print the data for (int i = 0;i < 20;i++) {System.out.print (Values[i] + "T");
      if ((i + 1)% = = 0) {System.out.println ("\ n");

 }
    }
  }
}

This method is also more efficient and, if 10,000 data is generated, it takes 0.054s of time. The
can transform more relevant solutions on the basis of coordinates in an array, and can refer to relevant data in detail.
The above is about implementing the function of random and no repetition in Java, of course, the method is not limited to so many, there are other implementation methods. Hope to be able to contact the friends of the near future help, also hope to be able to play a role.
Original URL: http://www.cnblogs.com/hanyonglu/archive/2012/10/18/2730007.html
The above is the entire content of this article, I hope to help you learn, We also hope that we can support the cloud-dwelling community.

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.