给定一个能生成等概率1-5随机数的函数,请你写一个自定义函数生成等概率1-7的随机数
思路:我们要得到1-7,那么只要得到(0-6)+1即可,(1-5)转换为(0-4)
,那问题就是怎么把(0-4)转换为(0-6)的问题
思路一:
public class RandomFunction {
public static void main(String[] args) {
System.out.println(f3());
}
//生成1-5随机数
public static int f() {
return (int) (Math.random() * 5) + 1;
}
//随机生成0-4
public static int f1() {
return f() - 1;
}
//随机生成0-24
//分为三块等概率0-6,21,22,23,24
//0-6,7-13,14-20,21,22,23,24
public static int f2() {
return f1() + f1() * 5;
}
//随机生成1-7
public static int f3() {
int t = 0;
do {
t = f2();
} while (t > 20);
return t % 7 + 1;
}
}