java用一个能产生[1,m]的随机函数, 实现一个能随机产生一个[1, n]的函数。
[java] view plaincopy在CODE上查看代码片派生到我的代码片
import java.util.Random;
public class MyRandom {
public static int random(int m,int n){
int c = (int) (Math.log(n-1)/Math.log(m))+1;
Random random = new Random();
int sum = 0;
while(true){
sum = random.nextInt(m);
for(int i=1; i<c; i++){
sum = sum*m + random.nextInt(m);
}
if(sum < n) break;
}
return sum+1;
}
public static void main(String [] args){
int [] count = new int [7];
for(int i=0; i<100000; i++){
count[random(3, 6)]++;
}
for(int i=1; i<7; i++){
System.out.println(“count["+i+"] = “+count[i]);
}
}
}