【发布时间】:2011-07-26 19:16:12
【问题描述】:
我需要在a 和b 之间生成n 随机数,但是任何两个数的差不能小于c。除了n 之外的所有变量都是浮点数(n 是一个整数)。
java 中首选解决方案,但 C/C++ 也可以。
这是我目前拥有的代码:
static float getRandomNumberInRange(float min, float max) {
return (float) (min + (Math.random() * (max - min)));
}
static float[] randomNums(float a, float b, float c, int n) {
float minDistance = c;
float maxDistance = (b - a) - (n - 1) * c;
float[] randomNumArray = new float[n];
float random = getRandomNumberInRange(minDistance, maxDistance);
randomNumArray[0] = a + random;
for (int x = 1; x < n; x++) {
maxDistance = (b - a) - (randomNumArray[x - 1]) - (n - x - 1) * c;
random = getRandomNumberInRange(minDistance, maxDistance);
randomNumArray[x] = randomNumArray[x - 1] + random;
}
return randomNumArray;
}
如果我这样运行函数(10 次),我会得到以下输出:
输入:randomNums(-1f, 1f, 0.1f, 10)
[-0.88, 0.85, 1.23, 1.3784, 1.49, 1.59, 1.69, 1.79, 1.89, 1.99]
[-0.73, -0.40, 0.17, 0.98, 1.47, 1.58, 1.69, 1.79, 1.89, 1.99]
[-0.49, 0.29, 0.54, 0.77, 1.09, 1.56, 1.69, 1.79, 1.89, 1.99]
【问题讨论】:
-
你有什么问题吗?另外,你没有问任何问题。
-
你的代码有什么问题,你对它不满意?
-
@retrodone 它实际上是在我的游戏中随机生成平台,因为两个平台不能靠得太近,不是功课。
-
已编辑问题以显示不正确的输出。
-
正如你所说的那样,你真的是在自找麻烦。您是否需要生成一个具有最少平台数量的解决方案,尽管如果选择不当,它们可能不会都适合 a 和 b?我只是放置一个平台,走一个大于 c 的随机距离,然后放置另一个平台。