如何创建奇数范围数随机函数?

nul*_*ull 4 java random algorithm

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

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
}
Run Code Online (Sandbox Code Playgroud)

我想创建算法函数,用于在 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 之间的数字。

有人知道算法吗?

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

izo*_*ica 6

使用算法:

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);
}
Run Code Online (Sandbox Code Playgroud)

这应该可以解决问题。

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

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);
}
Run Code Online (Sandbox Code Playgroud)