May 10, 2021 Java
Random number is one of the most basic characteristics of any programming language and is widely used in technology development because sometimes we need to randomly generate a fixed-length number, string, or randomly generate an indefinite-length number, or make a simulated random selection. J ava provides us with the most basic tools to help developers generate random numbers that are required under different conditions. ilar to c, and there are generally two random numbers, one is the randomdom() method in Math and the other is the Random class. H owever, whether c or java, to produce random numbers need to set random number seeds, if set is the same, each time you get the same random number. H ere's a summary of how common different types of java random numbers are generated.
(Data type)
(Min. Math.random() (Max- Min.1))
Example 1:
Int-type number from 1 to 10
(int)(1+Math.random()*(10-1+1))
Example 2:
Randomly generate one of the numbers from 0 to 100
Above we already know that Math.random() returns only a few numbers from 0 to 1, if you want 50 to 100, you zoom in 50 times, that is, between 0 and 50, here is still a small number, if you want an integer, cast int, and then add 50 is 50 to 100.
Final code:
(int)(Math.random()*50) + 50
Random random = new Random();//默认构造方法
Random random = new Random(1000);//指定种子数字
When random is performed, the origin number of the random algorithm is called the seed number, which transforms on the basis of the number of seeds to produce the random number required.
The Random object with the same number of seeds, the random number generated the same number of times is exactly the same. That is, two Random objects with the same number of seeds, the first generation of random numbers are exactly the same, the second generation of random numbers are exactly the same.
Example: Get the integer between the 0, 100.
int i2 = random.nextInt(100);
Random's function interface:
// 构造函数(一): 创建一个新的随机数生成器。
Random()
// 构造函数(二): 使用单个 long 种子创建一个新随机数生成器: public Random(long seed) { setSeed(seed); } next 方法使用它来保存随机数生成器的状态。
Random(long seed)
boolean nextBoolean() // 返回下一个“boolean类型”伪随机数。
void nextBytes(byte[] buf) // 生成随机字节并将其置于字节数组buf中。
double nextDouble() // 返回一个“[0.0, 1.0) 之间的double类型”的随机数。
float nextFloat() // 返回一个“[0.0, 1.0) 之间的float类型”的随机数。
int nextInt() // 返回下一个“int类型”随机数。
int nextInt(int n) // 返回一个“[0, n) 之间的int类型”的随机数。
long nextLong() // 返回下一个“long类型”随机数。
synchronized double nextGaussian() // 返回下一个“double类型”的随机数,它是呈高斯(“正常地”)分布的 double 值,其平均值是 0.0,标准偏差是 1.0。
synchronized void setSeed(long seed) // 使用单个 long 种子设置此随机数生成器的种子。
Common methods in random classes:
The methods in the Random class are simpler, and the functionality of each method is easy to understand. I t should be noted that the random numbers generated by the methods in the Random class are evenly distributed, which means that the chances of the numbers generated within the interval are equal. Here's a basic introduction to these methods:
a 、public boolean nextBoolean()
The effect of this method is to generate a random boolean value, which has an equal chance of generating values for true and false, i.e. both have a 50% chance.
b 、public double nextDouble()
The function of this method is to generate a random double value, the value is between 0, 1.0, where the parenthesis represents the containing interval endpoint, and the parenthesis represents the interval endpoint, i.e. a random number of dilubles between 0 and 1, containing 0 instead of 1.0.
c 、public int nextInt()
The function of this method is to generate a random int value, which is between the interval of int, that is, between the 31st square of -2 and the 31st square-1 of 2.
If you need to generate an int value for a specified interval, you need to make some mathematical transformations, as you can see in the code in the use example below.
d 、public int nextInt(int n)
The effect of this method is to generate a random int value, which is in the interval of 0,n, that is, a random int value between 0 and n, containing 0 without n.
If you want to generate an int value for a specified interval, you also need to make some mathematical transformations, as you can see in the code in the use example below.
e 、public void setSeed(long seed)
The effect of this method is to reset the number of seeds in the Random object.
The Random object after the number of seeds is set is the same as the Random object created using the new keyword for the same number of seeds.
Get it directly using the nextDouble method.
b. To generate a small number of the interval of 0,5.0
double d2 = r.nextDouble() * 5;
Because the nextDouble method generates a numeric interval of 0,1.0, it is the required interval to expand the interval five times.
Similarly, to generate a random number of dixes in the interval of 0,d, d is any positive number, you only need to multiply the return value of the nextDouble method by d.
c, the number of sdes in the interval of 1,2.5 is generated.
double d3 = r.nextDouble() * 1.5 + 1;
i.e. r.nextDouble () s (n2-n1) sn1
To generate a random number of the interval of 1,2.5, you only need to generate a random number of the interval of 0,1.5 first, and then add 1 to the resulting random number interval.
Similarly, to generate any random number that is not in the range of the scale from 0 (where d1 is not equal to 0), you only need to generate a random number of the interval of 0, d2-d1, and then add the resulting random number interval to d1.
d, generate any integer
int n1 = r.nextInt();
Use the nextInt method directly.
e. Generates an integer for the interval of 0,10
int n2 = r.nextInt(10);
n2 = Math.abs(r.nextInt() % 10);
Both lines of code can generate an integer for the interval of 0,10.
The first implementation is implemented directly using the nextInt (int n) method in the Random class.
In the second implementation, the nextInt() method is first called to generate an arbitrary int number, which and 10 after the resulting numeric interval is (-10, 10), because according to the mathematical provisions of the absolute value of the remaining number is less than the divide, and then the absolute value of the interval, the resulting interval is .
Similarly, you can use the following code to generate random integers for any interval of 0,n:
int n2 = r.nextInt(n);
n2 = Math.abs(r.nextInt() % n);
f, generating an integer for the interval of 0,10
int n3 = r.nextInt(11);
n3 = Math.abs(r.nextInt() % 11);
Relative to the integer interval, the interval of 0,10 is equivalent to the interval of 0,11, so the integer of the interval of 0,11 is generated.
g, the integer that generates the interval of .-3,15
int n4 = r.nextInt(18) - 3;
That is, r.nextInt() . . . (n2-n1) . . . n1. n1 is a negative number
n4 = Math.abs(r.nextInt() % 18) - 3;
To generate a random integer that does not start at 0, you can refer to the above description of the principle of implementation of a non-0-started desicad interval.
Method 3: Get a long number of milliseconds of the current time by System.currentTimeMillis().
Get random numbers through System.currentTimeMillis(). I
t's actually getting the current time milliseconds, and it's the long type.
Here's how to use it:
final long l = System.currentTimeMillis();
final long l = System.currentTimeMillis();
final int i = (int)( l % 100 );
Here's an example of how to get random numbers.
The source code is as follows (RandomTest.java):
import java.util.Random;
import java.lang.Math;
/**
* java 的随机数测试程序。共3种获取随机数的方法:
* (01)、通过System.currentTimeMillis()来获取一个当前时间毫秒数的long型数字。
* (02)、通过Math.random()返回一个0到1之间的double值。
* (03)、通过Random类来产生一个随机数,这个是专业的Random工具类,功能强大。
*
* @author skywang
* @email [email protected]
*/
public class RandomTest{
public static void main(String args[]){
// 通过System的currentTimeMillis()返回随机数
testSystemTimeMillis();
// 通过Math的random()返回随机数
testMathRandom();
// 新建“种子为1000”的Random对象,并通过该种子去测试Random的API
testRandomAPIs(new Random(1000), " 1st Random(1000)");
testRandomAPIs(new Random(1000), " 2nd Random(1000)");
// 新建“默认种子”的Random对象,并通过该种子去测试Random的API
testRandomAPIs(new Random(), " 1st Random()");
testRandomAPIs(new Random(), " 2nd Random()");
}
/**
* 返回随机数-01:测试System的currentTimeMillis()
*/
private static void testSystemTimeMillis() {
// 通过
final long l = System.currentTimeMillis();
// 通过l获取一个[0, 100)之间的整数
final int i = (int)( l % 100 );
System.out.printf("\n---- System.currentTimeMillis() ----\n l=%s i=%s\n", l, i);
}
/**
* 返回随机数-02:测试Math的random()
*/
private static void testMathRandom() {
// 通过Math的random()函数返回一个double类型随机数,范围[0.0, 1.0)
final double d = Math.random();
// 通过d获取一个[0, 100)之间的整数
final int i = (int)(d*100);
System.out.printf("\n---- Math.random() ----\n d=%s i=%s\n", d, i);
}
/**
* 返回随机数-03:测试Random的API
*/
private static void testRandomAPIs(Random random, String title) {
final int BUFFER_LEN = 5;
// 获取随机的boolean值
boolean b = random.nextBoolean();
// 获取随机的数组buf[]
byte[] buf = new byte[BUFFER_LEN];
random.nextBytes(buf);
// 获取随机的Double值,范围[0.0, 1.0)
double d = random.nextDouble();
// 获取随机的float值,范围[0.0, 1.0)
float f = random.nextFloat();
// 获取随机的int值
int i1 = random.nextInt();
// 获取随机的[0,100)之间的int值
int i2 = random.nextInt(100);
// 获取随机的高斯分布的double值
double g = random.nextGaussian();
// 获取随机的long值
long l = random.nextLong();
System.out.printf("\n---- %s ----\nb=%s, d=%s, f=%s, i1=%s, i2=%s, g=%s, l=%s, buf=[",
title, b, d, f, i1, i2, g, l);
for (byte bt:buf)
System.out.printf("%s, ", bt);
System.out.println("]");
}
Example 2:
Problem: A random number of two digits after the reserved scale between (-10, 10) is generated.
Solution:
1.java random number generator Random r s new Random (); r
.nextFloat(); // Generated (0, 1) between floating-point random numbers.
Multiply the above random number by 10 to get the random number between the generations (0,10).
2. Generate a Random Number of The Boolean type to control the positive or negative number: r.nextBoolean();
3. Method of keeping the scale in two digits: Math.floor (n*100 plus 0.5)/100;
The resulting number is double type.
The code is as follows:
import java.util.*;
public class CreateRandom {
public float numRandom(){
float num;
Random r=new Random();
float value = (float) (Math.floor(r.nextFloat()*1000+0.5)/100);
Boolean b = r.nextBoolean();
if(b){
num = value;
}
else{
num=0-value;
}
return num;
}
public static void main(String[] args) {
CreateRandom cr = new CreateRandom();
float num = cr.numRandom();
System.out.print(num);
}
}
Example 3:
Java generates random, no repeat random numbers, implemented using ArayList
import java.util.ArrayList;
import java.util.Random;
/**
* 生成随机无重复随机数,使用ArrayList实现
*
* 算法:加入随机数时检测列表中是否已存在此随机数,有则重来,无则加入。
*
*/
public class Demo {
public static void main(String[] args) {
int length = 50; // 50个随机数
Random random = new Random();
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < length; i++) {
int number = random.nextInt(100) + 1; // 1-100的随机数(此处100必须比length大,否则会死循环)
if (!list.contains(number)) {
list.add(number);
} else {
i--; // 保证生成的随机数个数足够,防止有重复随机数时造成空位
}
}
for (int i = 0; i < length; i++) {
System.out.print(list.get(i) + "\t");
if ((i + 1) % 10 == 0) {
System.out.println("");
}
}
}
}
Example 4:
java generates a fixed-digit password random number code
public class RandomPassword {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(genRandomNum(10));
}
/**
* 生成随即密码
*
* @param pwd_len
* 生成的密码的总长度
* @return 密码的字符串
*/
public static String genRandomNum(int pwd_len) {
// 35是因为数组是从0开始的,26个字母+10个数字
final int maxNum = 36;
int i; // 生成的随机数
int count = 0; // 生成的密码的长度
char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9' };
StringBuffer pwd = new StringBuffer("");
Random r = new Random();
while (count < pwd_len) {
// 生成随机数,取绝对值,防止生成负数,
i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1
if (i >= 0 && i < str.length) {
pwd.append(str[i]);
count++;
}
}
return pwd.toString();
}
}
Example 5:
Java generates random numbers with weights
package test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
//带权重的随机数
//面试的时候面试官问道一个这样的问题
//A、B、C三个字符分别出现的概率是30%,40%,30%
//分析:首先1-100随机产生一个数,判断这个数,1-30出现的概率是30%, 31—70出现的概率是40%, 71-100出现的概率是30%
public class WeightRandom {
public static void main(String[] args) {
Random ran = new Random();
String str=getWanfei(ran.nextInt(100));
Map<String,Object> map = new HashMap<String,Object>();
map.put("key","A");
map.put("value","30");
Map<String,Object> map1 = new HashMap<String,Object>();
map.put("key","B");
map.put("value","70");
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
list.add(map);
list.add(map1);
System.out.println( getWeight(list,ran.nextInt(100)));
}
//知道权重的情况下
public static String getWanfei(int num){
if(num>=1 && num<=30){
return "A";
}else if(num>=31 && num<70){
return "B";
}else{
return "C";
}
}
//如果A、B、C的个数不确定 ,权重的总数也也不确定
public static String getWeight(List<Map<String,Object>> list,int ran){
//map里放的是a,b,c 值,和每个a、b、c对应的权重
int sum=0;
int total = list.size();
for(int i=0;i<total;i++){
sum+=Integer.parseInt(list.get(i).get("value").toString());
if(ran<=sum){
return list.get(i).get("key").toString();
}
}
return null;
}
}