import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RandNFromRand5 {
/**
题目:给定能随机生成整数1到5的函数,写出能随机生成整数1到7的函数。
解法1:
f(k) = (x0-1)*5^0+(x1-1)*5^1+(x2-1)*5^2+(x3-1)*5^3+…+(Xk-1-1)*5^(k-1)
f(k)是一个随机数,一个5进制的随机数,取值范围U=[0,(5^k)-1],这里考虑将U等分成7等分
(能否达到等分?只要k足够大,误差就可以足够小),那么每次产生的数位于哪个等分里,参生的随机数就为几。
解法2:
只要我们可以从 n 个数中随机选出 1 到 n 个数,反复进行这种运算,直到剩下最后一个数即可。
我们可以调用 n 次给定函数,生成 n 个 1 到 5 之间的随机数,选取最大数所在位置即可满足以上要求。
例如
初始的 7 个数 [1,2,3,4,5,6,7].
7 个 1 到 5 的随机数 [5, 3,1,4,2,5,5]
那么我们保留下[1,6,7],
3 个1 到 5 的随机数[2,4,1]
那么我们保留下[6]
6 就是我们这次生成的随机数。
*/
public static void main(String[] args) {
RandNFromRand5 r=new RandNFromRand5();
for(int i=0;i<100;i++){
int result1=r.nextInt(7);
int result2=r.rand7();
System.out.println(result1+","+result2);
}
}
/*solution 1:
*return 1~n randomly.Now we assume n=7
*/
public int nextInt(int n){
if(n<=5){
return -1;
}
int result=0;
int k=0;
int max=1;
while(max<n){//now max=25,k=2
max*=5;
k++;
}
int item=0;
int range=(max/n)*n;//range=21,so 21~25 are eliminated.
boolean done=false;
while(!done){
for(int i=0;i<k;i++){
int x=rand5()-1;
//item+=x*(5^i),,"very wrong"! "^" means "xor"!
item=item*5+x;
}
if(item<range){
done=true;
}else{
item=0;
}
}
int mode=max/n;//mode=3,there are 3 items in each part,like (0,1,2)->1,(1,2,3)->2...(18,19,20)->7
result=(item/mode)+1;
return result;
}
/* solution 2:
* return 1~7 randomly
*/
public int rand7(){
List<Integer> list=new ArrayList<Integer>();
for(int i=1;i<=7;i++){
list.add(i);
}
return rand7Help(list);
}
public int rand7Help(List<Integer> list){
if(list==null || list.size()==0){
return -1;
}
if(list.size()==1){
return list.get(0);
}
int n=list.size();
int[] nRand5=new int[n];
int max=0;
for(int i=0;i<n;i++){
int x=rand5();
if(x>max){
max=x;
}
nRand5[i]=x;
}
List<Integer> newList=new ArrayList<Integer>();
for(int i=0;i<n;i++){
if(nRand5[i]==max){
newList.add(list.get(i));
}
}
return rand7Help(newList);
}
public int rand5(){
return new Random().nextInt(5)+1;
}
}
给定能随机生成整数1到5的函数,写出能随机生成整数1到7的函数
最新推荐文章于 2018-10-28 18:52:30 发布
本文介绍两种由给定的生成1到5随机数的方法来实现生成1到7随机数的算法。第一种方法通过构造五进制随机数并将其等分为七个区间;第二种方法通过不断筛选直至仅剩一个数来确定随机数。
5806

被折叠的 条评论
为什么被折叠?



