Summary of methods for generating non-repeating random numbers in java
This article will introduce to you how to implement the function of random non-repeating numbers in JAVA. (Related video course recommendations: java video tutorial)
In order to better understand the meaning of this question, let’s first look at the specific content: Generate a random array of 1-100, but the array The numbers in cannot be repeated, that is, the positions are random, but the array elements cannot be repeated.
Here, the length of the array is not specified for us, we can make it any length between 1-100.
Next let us look at several implementation methods and compare these methods.
Usually we will use ArrayList or array to implement it. Let’s first look at the ArrayList implementation process, as shown in the following code:
import java.util.ArrayList; import java.util.Random; /** * 使用ArrayList实现 * @Description: * @File: Demo.java * @Date 2012-10-18 下午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(); // 遍历数组并打印数据 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 array implementation is as follows:
import java.util.Random; /** * 使用数组实现 * @Description: * @File: Demo4.java * @Package None * @Author Hanyonglu * @Date 2012-10-18 下午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; } } } // 遍历数组并打印数据 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. Because every time you add it, you have to traverse whether the number exists in the current list, and the time complexity is O(N^2). We can think about it this way: Since it involves no duplication, we can think about the functions of HashSet and HashMap.
HashSet implements the Set interface. The mathematical definition of Set is a collection without duplication and order. HashMap implements Map and does not allow duplicate Keys. In this way we can use HashMap or HashSet to achieve it.
When using HashMap to implement, you only need to convert its key into an array, as shown in the following code:
import java.util.HashMap; import java.util.Iterator; import java.util.Random; import java.util.Map.Entry; /** * 使用HashMap实现 * @Description: * @File: Demo.java * @Package None * @Author Hanyonglu * @Date 2012-10-18 下午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>(); // 生成随机数字并存入HashMap for(int i = 0;i < values.length;i++){ int number = random.nextInt(100) + 1; hashMap.put(number, i); } // 从HashMap导入数组 values = hashMap.keySet().toArray(); // 遍历数组并打印数据 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(); // // 遍历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"); // } // } } }
Since the relationship between HashSet and HashMap is too close, HashSet is used at the bottom layer HashMap is implemented, but there is no Value collection, only a Key collection, so it can also be implemented using HashSet, as shown in the following code:
import java.util.HashSet; import java.util.Random; /** * 使用HashSet实现 * @Description: * @File: Test.java * @Package None * @Author Hanyonglu * @Date 2012-10-18 下午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>(); // 生成随机数字并存入HashSet for(int i = 0;i < values.length;i++){ int number = random.nextInt(100) + 1; hashSet.add(number); } values = hashSet.toArray(); // 遍历数组并打印数据 for(int i = 0;i < values.length;i++){ System.out.print(values[i] + "\t"); if(( i + 1 ) % 10 == 0){ System.out.println("\n"); } } } }
This implementation is slightly 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 shown below:
import java.util.HashSet; import java.util.Random; /** * 使用HashSet实现 * @Description: * @File: Test.java * @Package None * @Author Hanyonglu * @Date 2012-10-18 下午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>(); // 生成随机数字并存入HashSet while(hashSet.size() < values.length){ hashSet.add(random.nextInt(100) + 1); } values = hashSet.toArray(); // 遍历数组并打印数据 for(int i = 0;i < values.length;i++){ System.out.print(values[i] + "\t"); if(( i + 1 ) % 10 == 0){ System.out.println("\n"); } } } }
Compared with the above, the efficiency of using HashMap is relatively high. In fact, it is HashSet, then array, and finally ArrayList. If we generate 10,000 pieces of data, we will find that the time spent using HashMap is: 0.05s, HashSet is 0.07s, array is: 0.20s, and ArrayList is 0.25s. If you are interested, you can set a time to check it out.
Of course, in addition to using HashMap, there are other efficient methods. For example, we can store the numbers 1-100 in an array, and then randomly generate two subscripts in the for loop. If the two subscripts are not equal, we can exchange the elements in the array. The implementation process is as follows :
import java.util.Random; /** * 随机调换位置实现 * @Description: * @File: Demo4.java * @Package None * @Author Hanyonglu * @Date 2012-10-18 下午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; } //随机交换values.length次 for(int i = 0;i < values.length;i++){ temp1 = Math.abs(r.nextInt()) % (values.length-1); //随机产生一个位置 temp2 = Math.abs(r.nextInt()) % (values.length-1); //随机产生另一个位置 if(temp1 != temp2){ temp3 = values[temp1]; values[temp1] = values[temp2]; values[temp2] = temp3; } } // 遍历数组并打印数据 for(int i = 0;i < 20;i++){ System.out.print(values[i] + "\t"); if(( i + 1 ) % 10 == 0){ System.out.println("\n"); } } } }
For more java related articles, please pay attention to java basic tutorial.
The above is the detailed content of Summary of methods for generating non-repeating random numbers in java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
