在C中随机填充结构类型的二维数组的问题

时间:2015-11-15 22:48:03

标签: c function multidimensional-array count structure

我尝试填充20x20矩阵,其中每个条目都是结构类型。我的目标是在这个2d阵列上随机分配100只蚂蚁和5只doodlebug。即使我开始工作,我也不会总是得到矩阵中需要的蚂蚁或粪便。我添加了一个计数功能,以便在每次运行程序时总是验证它们有多少,但我总是略微缩短。我试图通过在我的填充函数中使用do while循环来强制执行这些数字(100个蚂蚁和5个doodlebug),尽管它不起作用。有人能发现我的逻辑在哪里失败了吗?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>

#define N 20

struct cellState
{
int emptyInt;
int antInt;
int dBInt;

char emptyChar;
char antChar;
char dBChar;
};
struct cellState gridState[N][N];


// function to populate world
void pop_mtx(struct cellState gridState[N][N],int antsNeeded, int dBNeeded) {
int i,j;

do {
for (i=0; i<N; i++){    
    for (j=0; j<N; j++){
            if ((gridState[i][j].emptyInt = rand()%3)== 0){
                gridState[i][j].emptyChar = '.';
            }
            else if (((gridState[i][j].antInt = rand()%3 == 1) && antsNeeded!=0)){
                gridState[i][j].antChar = 'a';
                antsNeeded--;
            }
            else if (((gridState[i][j].dBInt = rand()%3 == 2) && dBNeeded!=0))
            {
                gridState[i][j].dBChar = 'D';
                dBNeeded--;
            }
    }
}
} while (dBNeeded!=0 && antsNeeded!=0);
}

//function to display current state of the world
void display_mtx(struct cellState gridState[N][N]) {
int i, j;
char charToDisplay;

for (i=0; i<N; i++){

    for(j=0; j<N; j++){

        if (gridState[i][j].antChar=='a')
            charToDisplay = 'a';

        else if (gridState[i][j].dBChar=='D')
            charToDisplay = 'D';

        else
            charToDisplay = '.';

        printf("%c  ", charToDisplay);
    }
    printf("\n");
}
printf("\n\n");
}

//function to count ants and doodlebugs
void count_mtx(struct cellState gridState[N][N]) {
int i, j, antCount=0,dBcount=0;

for (i=0; i<N; i++){

    for(j=0; j<N; j++){

        if (gridState[i][j].antChar=='a')
            antCount++;

        else if (gridState[i][j].dBChar=='D')
            dBcount++;
    }
}
printf("ant count: %i, doodlebug count: %i\n",antCount,dBcount);
}

int main(void) {

srand((unsigned int)time(NULL));

//populate grid state with 5 doodlebugs and 100 ants
int antsNeeded=100,dBNeeded=5;
pop_mtx(gridState,antsNeeded,dBNeeded);

count_mtx(gridState);
display_mtx(gridState);

}

1 个答案:

答案 0 :(得分:1)

有几个问题。首先,每次调用rand()时,都会得到一个不同的值,因此三个测试都没有通过。你应该调用rand()一次并保存值。

其次,没有什么可以保证在NxN调用rand()时你会得到你需要的那么多和两个。因此外循环是必要的,并且在到达产生足够的两个迭代的迭代之前可能需要永远。即使您将已填充的方块从一次迭代保留到下一次迭代,您的运行时间也是无限制的。

第三,这种方法偏向网格开头的方块。它不会给你100个蚂蚁和5个doodlebugs中的一个,超过400个方格,概率相等。

这样做的正确方法是为400只蚂蚁选择100个方格,为300只蚂蚁选择5个方格。然后相应地填充矩阵。

如果选择400个中的100个方格,则为第一个选择1到400之间的随机数,第二个选择1到399之间的数字,等等。然后跳过已分配的方块进行转换这个序列到一个正方形列表。

相关问题