gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:31:54 24 4
gpt4 key购买 nike

我正在尝试填充一个 20x20 矩阵,其中每个条目都是结构类型。我的目标是在这个二维数组上随机分配 100 只 Ant 和 5 只涂鸦虫。尽管我让它工作了,但我并不总能在矩阵中得到我需要的 Ant 或涂鸦虫的数量。我添加了一个计数功能,每次运行程序时总是验证我有多少,但我总是略显不足。我试图通过在我的填充函数中使用 do/while 循环来强制这些数字起作用(100 只 Ant 和 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);
}

最佳答案

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

其次,没有任何东西可以保证在对 rand() 的 NxN 次调用之后,您将获得所需数量的 1 和 2。因此外环是必要的。您还应该保留从一个迭代到下一个迭代的已经填充的方 block ,因为可能需要很长时间才能达到产生足够多的一个和两个的迭代。

第三,这种方法偏向于网格开头的方 block 。它不会以相同的概率在 400 个正方形上给出 100 只 Ant 和 5 只涂鸦虫的所有可能分布中的一种。

正确的做法是:

将网格视为一维数组。首先按顺序用 100 只 Ant 、5 只涂鸦虫和空白空间填充它。然后执行 random shuffle数组的。

此过程将以相等的概率返回网格上 Ant 和涂鸦的每个可能分布。

关于c - 在 C 中随机填充结构类型的二维数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33726022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com