如何创建不均匀的范围数随机函数? [英] How to create uneven range number random function?

查看:157
本文介绍了如何创建不均匀的范围数随机函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道经典范围随机函数是这样的:

  public static final int random(final int min,final int max){
Random rand = new Random();
返回min + rand.nextInt(max - min + 1); // +1包含最多
}

我想创建用于生成的算法函数在1..10之间的范围内随机编号,但不一致的可能性如下:

1)1,2,3 - > 3/6(1/2)

2 )4,5,6,7 - > 1/6

3)8,9,10 - > 2/6(1/3)



上述意味着该函数有1/2的机会返回1到3之间的数字,1/6的机会返回4到7之间的数字,以及1/3的机会返回8到10之间的数字。 / p>

任何人都知道算法吗?



更新:

实际上,1..10之间的范围仅作为示例。我想要创建的函数适用于任何数字范围,例如:1..10000,但规则仍然相同:顶部范围为3/6(30%部分),中间范围为1/6(下一个) 40%部分),底部范围2/6(最后30%部分)。

解决方案

使用上述算法:

  int temp = random(0,5); 
if(temp< = 2){
return random(1,3);
}否则if(temp< = 3){
return random(4,7);
} else {
return random(8,10);
}

这应该可以解决问题。



编辑:根据您的评论中的要求:

  int first_lo = 1,first_hi = 3000; // 1/2在[first_lo,first_hi]中选择数字的机会
int second_lo = 3001,second_hi = 7000; // 1/6机会在[second_lo,second_hi]中选择一个数字
int third_lo = 7001,third_hi = 10000; // 1/3机会在[third_lo,third_hi]中选择一个数字
int第二个
int temp = random(0,5);
if(temp< = 2){
return random(first_lo,first_hi);
}否则if(temp< = 3){
return random(second_lo,second_hi);
} else {
return random(third_lo,third_hi);
}


We know that the classic range random function is like this:

public static final int random(final int min, final int max) {
    Random rand = new Random();
    return min + rand.nextInt(max - min + 1);  // +1 for including the max
}

I want to create algorithm function for generating number randomly at range between 1..10, but with uneven possibilities like:
1) 1,2,3 -> 3/6 (1/2)
2) 4,5,6,7 -> 1/6
3) 8,9,10 -> 2/6 (1/3)

Above means the function has 1/2 chance to return number between 1 and 3, 1/6 chance to return number between 4 and 7, and 1/3 chance to return number between 8 and 10.

Anyone know the algorithm?

UPDATE:
Actually the range between 1..10 is just served as an example. The function that I want to create would apply for any range of numbers, such as: 1..10000, but the rule is still same: 3/6 for top range (30% portion), 1/6 for middle range (next 40% portion), and 2/6 for bottom range (last 30% portion).

解决方案

Use the above algorithm:

int temp = random(0,5);
if (temp <= 2) {
  return random(1,3);
} else if (temp <= 3) {
 return random(4,7);
} else  {
 return random(8,10);
}

This should do the trick.

EDIT: As requested in your comment:

int first_lo = 1, first_hi = 3000; // 1/2 chance to choose a number in [first_lo, first_hi]
int second_lo = 3001, second_hi = 7000; // 1/6 chance to choose a number in [second_lo, second_hi] 
int third_lo = 7001, third_hi = 10000;// 1/3 chance to choose a number in [third_lo, third_hi] 
int second
int temp = random(0,5);
if (temp <= 2) {
  return random(first_lo,first_hi);
} else if (temp <= 3) {
 return random(second_lo,second_hi);
} else  {
 return random(third_lo,third_hi);
}

这篇关于如何创建不均匀的范围数随机函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆