This article describes how to implement the random and non-repeated numbers function in JAVA. If you are a beginner, you need to take a look at this article, because this feature is generally encountered during the interview. I also like to ask this question when recruiting people. I mainly want to take a look at the problem model and basic knowledge.
I hope this article will help some of my first friends, because I have never been able to write this article or use a very tiled way of thinking to implement it.
Generally, developers with some development experience can achieve this function, but it is only a matter of efficiency. In general, when we are faced with such a problem, we will always think of it in a straight order. Mr will form an array and then add random numbers to the array in a loop, when adding a number, first check whether the number exists in the array. If the number does not exist, add it to the array. If the number exists, no. We generally think about the problem in this way, so we can also implement the function. I just mentioned that it is just a matter of efficiency.
To better understand this question, let's first look at the specific content: generate a random array of 1-, but the numbers in the array cannot be repeated, that is, the positions are random, but the array elements cannot be repeated.
Here, we have not specified the length of the array. We can make it any length between 1 and.
Next let's take a look at several implementation methods and compare them.
We usually use ArrayList or array to implement it. First, let's look at the implementation process of ArrayList, as shown in the following code:
Import java. util. arrayList; import java. util. random;/*** use ArrayList to implement * @ Description: * @ File: Demo. java * @ Package None * @ Author Hanyonglu * @ Date 06:16:55 * @ Version V1.0 */public class Demo {public static void main (String [] args) {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 (100) + 1; if (! List. contains (number) {list. add (number) ;}} values = list. toArray (); // traverse the array and print the data for (int I = 0; I <values. length; I ++) {System. out. print (values [I] + "\ t"); if (I + 1) % 10 = 0) {System. out. println ("\ n ");}}}}
The process of using arrays is as follows:
Import java. util. random;/*** use arrays to implement * @ Description: * @ File: demo4.java * @ Package None * @ Author Hanyonglu * @ Date 06:27:38 * @ 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 ;}}// print the array and print the data for (int I = 0; I <values. length; I ++) {System. out. print (values [I] + "\ t"); if (I + 1) % 10 = 0) {System. out. println ("\ n ");}}}}
The above two implementation processes are relatively inefficient. The time complexity is O (N ^ 2 ). We can think about the functions of HashSet and HashMap in this way. HashSet implements the Set interface. In mathematics, a Set is defined as a Set without repetition or order. HashMap implements Map, and duplicate keys are not allowed. In this way, we can use HashMap or HashSet.
When using HashMap, you only need to convert its key into an array. The code below is as follows:
Import java. util. hashMap; import java. util. iterator; import java. util. random; import java. util. map. entry;/*** use HashMap to implement * @ Description: * @ File: Demo. java * @ Package None * @ Author Hanyonglu * @ Date 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 store them in HashMap for (int I = 0; I <values. length; I ++) {int number = random. nextInt (100) + 1; hashMap. put (number, I);} // import the array values = HashMap from hashMap. keySet (). toArray (); // traverse the array and print the data for (int I = 0; I <values. length; I ++) {System. out. print (values [I] + "\ t"); if (I + 1) % 10 = 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 % 10 = 0) {// System. out. println ("\ n ");//}//}}}
Because the relationship between HashSet and HashMap is too close, HashSet is implemented by HashMap at the underlying layer, except that there is no set of values and there is only one set of keys, so HashSet can also be implemented, the following code:
Import java. util. hashSet; import java. util. random;/*** use HashSet to implement * @ Description: * @ File: Test. java * @ Package None * @ Author Hanyonglu * @ Date 06:11:41 * @ Version V1.0 */public class Test {public static void main (String [] args) {Random random = new Random (); Object [] values = new Object [20]; HashSet <Integer> hashSet = new HashSet <Integer> (); // generate random numbers and store them in HashSet for (int I = 0; I <values. length; I ++) {int number = random. nextInt (100) + 1; hashSet. add (number);} values = hashSet. toArray (); // traverse the array and print the data for (int I = 0; I <values. length; I ++) {System. out. print (values [I] + "\ t"); if (I + 1) % 10 = 0) {System. out. println ("\ n ");}}}}
This is more efficient. If we limit the length of the array, we only need to change the for loop and set it to a whlie loop. As follows:
Import java. util. hashSet; import java. util. random;/*** use HashSet to implement * @ Description: * @ File: Test. java * @ Package None * @ Author Hanyonglu * @ Date 05:11:41 * @ Version V1.0 */public class Test {public static void main (String [] args) {Random random = new Random (); Object [] values = new Object [20]; HashSet <Integer> hashSet = new HashSet <Integer> (); // generate random numbers and store them in HashSet while (hashSet. size () <values. length) {hashSet. add (random. nextInt (100) + 1);} values = hashSet. toArray (); // traverse the array and print the data for (int I = 0; I <values. length; I ++) {System. out. print (values [I] + "\ t"); if (I + 1) % 10 = 0) {System. out. println ("\ n ");}}}}
We can set the length of the array to 100 to verify the running effect, as shown in:
In comparison, the efficiency of using HashMap is relatively high. It is actually HashSet, array again, And ArrayList. If we generate 10000 pieces of data, we will find that the HashMap takes 0.05 s, the HashSet is 0.07 s, the array is 0.20 s, and the ArrayList is 0.25 s. If you are interested, you can set the time to view it.
Of course, there are other efficient methods besides HashMap implementation. For example, we can store numbers 1-in an array, and then randomly generate two subscripts in the for loop. If the two subscripts are not equal, we can swap the elements in the array, the implementation process is as follows:
Import java. util. random;/*** Random placement * @ Description: * @ File: demo4.java * @ Package None * @ Author Hanyonglu * @ Date 06:54: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 exchange values. length for (int I = 0; I <value S. length; I ++) {temp1 = Math. abs (r. nextInt () % (values. length-1); // randomly generate a location temp2 = Math. abs (r. nextInt () % (values. length-1); // randomly generate another location 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) % 10 = 0) {System. out. println ("\ n ");}}}}
This method is also relatively efficient. If 10000 pieces of data are generated, the time it takes is 0.054 s.
Based on the Implementation of coordinates in the array, you can change more related solutions. For details, refer to relevant materials.
The above describes how to implement random and non-repeated numbers in JAVA. Of course, the methods are not limited to these methods. There are other implementation methods. I hope it will be helpful for friends who have been in touch with me for a long time, and I hope it will be helpful.
Download the example:/Files/hanyonglu/JAVA/MyTestDemo.rar
Finally, I hope to reprint friends can respect the author's labor results, plus reprint address: http://www.cnblogs.com/hanyonglu/archive/2012/10/18/2730007.html thank you.
Complete. Pai_^