我正在尝试生成1到10之间的3个数字。任何两个数字之间的差值必须小于/等于2。例如:2、6、9可以,但是2、4、7不能(因为4-2 = 2)。
private int GetGoodNumber()
{
int lastIndex = 0;
int x = 3;
int randomNumber = 0;
for (int i = 0; i < 3; i++)
{
int interval = UnityEngine.Random.Range(2, 7);
do
{
randomNumber = interval + (UnityEngine.Random.Range(0, 10));
} while (randomNumber > 10 || x <= 2);
x = (lastIndex > randomNumber) ? lastIndex - randomNumber : randomNumber - lastIndex;
lastIndex = randomNumber;
Debug.Log(randomNumber);
}
return randomNumber;
}
不幸的是,我的方法不起作用,有人知道这个问题吗?
答案 0 :(得分:3)
根据该规则,组合不会太多。
firstNumber
必须为1
,2
,3
或4
。
基于此生成firstNumber + 3
和7
之间的下一个。
最后一个逻辑相同。
代码:
var random = new Random();
var first = random.Next(1, 4 + 1);
var second = random.Next(first + 3, 7 + 1);
var third = random.Next(second + 3, 10 + 1);
答案 1 :(得分:1)
我想我会对其进行硬编码以获得正确的分发。
var x = new [,]
{
{1, 4, 7},
{1, 4, 8},
{1, 4, 9},
{1, 4, 10},
{1, 5, 8},
{1, 5, 9},
{1, 5, 10},
{1, 6, 9},
{1, 6, 10},
{1, 7, 10},
{2, 5, 8},
{2, 5, 9},
{2, 5, 10},
{2, 6, 9},
{2, 6, 10},
{2, 7, 10},
{3, 6, 9},
{3, 6, 10},
{3, 7, 10},
{4, 7, 10}
};
答案 2 :(得分:0)
也许是这样的:
public static List<int> GetRandomNumbers()
{
List<int> result = new List<int>();
for (int i = 0; i < 3; i++)
{
bool numberFit = false;
int number = 0;
do
{
number = random.Next(0, 10);
numberFit = !result.Any(x => x == number || x == number + 1 || x == number + 2 || x == number - 1 || x == number -2);
} while (!numberFit);
result.Add(number);
}
return result;
}