【发布时间】:2015-11-15 22:48:02
【问题描述】:
我正在尝试填充一个 20x20 矩阵,其中每个条目都是结构类型。我的目标是在这个二维数组上随机分配 100 只蚂蚁和 5 只涂鸦虫。即使我让它工作,我并不总是在矩阵中得到我需要的蚂蚁或涂鸦虫的数量。我添加了一个计数功能,以在每次运行程序时始终验证我有多少个,但我总是有点短。我试图通过在我的填充函数中使用do/while 循环来强制这些数字工作(100 只蚂蚁和 5 只涂鸦虫),尽管它不起作用。有人能发现我的逻辑在哪里失败了吗?
#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);
}
【问题讨论】:
-
您的人口逻辑看起来不正确。有几个问题,但主要的一个是一旦一个条目被 Ant 或 DB 填充,代码中没有任何内容可以防止它稍后被其他东西覆盖(由于外部
do循环)。从理论上讲,外循环可以是无限的,因为由于算法的随机性,无法保证退出条件会得到满足(实际上它会结束但仍然不是一个好的算法恕我直言)。 -
所以在满足条件 (dBNeeded!=0 || antsNeeded!=0) 的情况下,我取出了 do while 并使用了 if 语句。我还使用 (continue;) 在 else-if 循环中添加了一个 else。这似乎解决了问题
标签: c multidimensional-array random