代码为已知随机数生成方法 random(),能够生成1-7的随机数,求能够生成1-10随机数的方法
random1参考链接
random2参考链接
package com.company.random;
public class Random {
//根据1-7的随机数方法,给出1-10的随机数方法
public static void main(String[] args) {
for (int i = 0; i < 50; i++) {
System.out.println(random1());
System.out.println(random2());
}
}
//生成1-7的随机数
static int random() {
return (int) (Math.random() * 7) + 1;
}
static int random1() {
int x = 0;
do {
x = (random() - 1) *7 + random();
} while (x > 40);
return x % 10 + 1;
}
static int random2() {
int num;
int result;
do {
result = 0;
num = 0;
while (num < 4) {
result = result | random21();
result = result << 1;
num++;
}
} while (result > 10);
return result;
}
static int random21() {
int x = 0;
do {
x = random();
} while (x > 6);
return x & 1;
}
}