如何才能使用无法使用的xy坐标?假设我不想要使用xy(5,5)和(7,9)。我怎么能这样做?
x = random.Next(0, 20);
y = random.Next(0, 20);
// if xy coordinate is (5,5) or (7,9), keep trying the above to obtain a different xy value
创建xy坐标时,如何才能使某些坐标无法使用?
答案 0 :(得分:1)
不是要求从0到(最大插槽)的随机数,而是可以要求一个数字来填充第n个空闲时隙并跟踪空闲时隙(例如使用布尔值每个插槽)。
在开始free time lots = max slots
时,每次分配后free time slots
都会减少。穿过插槽 - O(n) - 并填充第n个空闲插槽,n是Random.Next(0, freeSlots)
返回的数字
答案 1 :(得分:0)
只需循环创建,直到满足您的条件:
var forbidden = new List<Tuple<int, int>>();
forbidden.Add(new Tuple<int, int>(5, 5));
forbidden.Add(new Tuple<int, int>(7, 9));
while(true)
{
x = random.Next(0, 20);
y = random.Next(0, 20);
if(forbidden.All(t => x != t.Item1 || y != t.Item2)) break;
}
这样,只有当你的坐标是“允许的”时,循环才会终止,即达到break
语句。