我正在尝试编写C代码,从10x10的网格中随机选择10个站点。我正在考虑的方法是为每个单元格分配一个介于0和RAND_MAX之间的随机数,然后挑选出10个最小/最大的值。但我几乎不知道如何实际编写这样的代码:/
我以前使用过伪随机数生成器,所以我可以完成这一部分。
发布于 2012-03-13 09:44:09
只需生成2个介于0和9之间的随机数,然后从数组中选择随机元素,如下所示:
arr[rand1][rand2];在一个循环中重复10次。没有必要让它变得更复杂。
发布于 2012-03-13 10:57:20
为了稍微简化,可以将10x10数组视为100个元素的等效线性数组。现在问题变成了从一组100个不同的数字中挑选10个不同的数字。要获得第一个索引,只需在0到99之间选择一个随机数即可。
int hits[10]; /* stow randomly selected indexes here */
hits[0] = random1(100); /* random1(n) returns a random int in range 0..n-1 */第二个数字几乎同样简单。从剩下的99个可能性中选择另一个数字。Random1返回一个连续范围为0..99的数字;然后必须将其映射到虚线范围0..hits-1,hits+1..99中。
hits[1] = random1(99);
if (hits[1] == hits[0]) hits[1]++;现在,对于第二个数字,映射开始变得有趣起来,因为它需要一些额外的工作来确保新的数字与现有的两个选择都不同。
hits[2] = random1(98);
if (hits[2] == hits[0]) hits[2]++;
if (hits[2] == hits[1]) hits[2]++;
if (hits[2] == hits[0]) hits[2]++; /* re-check, in case hits[1] == hits[0]+1 */如果按顺序对命中数组进行排序,则可以避免重新检查元素的唯一性。把所有东西放在一起:
int hits[10];
int i, n;
for (n = 0; n < 10; n++) {
int choice = random1( 100 - n ); /* pick a remaining index at random */
for (i = 0; i < n; i++) {
if (choice < hits[i]) /* find where it belongs in sorted hits */
break;
choice++; /* and make sure it is distinct *
/* need ++ to preserve uniform random distribution! */
}
insert1( hits, n, choice, i );
/* insert1(...) inserts choice at i in growing array hits */
}您可以使用hits从10x10数组中获取元素,如下所示:
array[hits[0]/10][hits[0]%10]发布于 2012-03-13 10:11:54
for (int i = 0; i < 10; i++) {
// ith random entry in the matrix
arr[rand() % 10][rand() % 10];
}https://stackoverflow.com/questions/9677254
复制相似问题