gpt4 book ai didi

c - 如何在 map 上随机放置元素?

转载 作者:太空宇宙 更新时间:2023-11-04 04:54:20 26 4
gpt4 key购买 nike

在网上搜索后,我没有找到可以帮助我的答案。我的程序是用 C 语言编写的。

我有一个项目列表(例如:37 a、22 b、29 c、13 d、19 e、2 f 和 0 g),我必须将所有这些项目随机放置在 map 上(在我的例子中, 一个整数[高度][长度][7])。我想用 rand 来放置元素并循环直到放置整个元素,但它使用了太多时间和资源。

有没有一种方法可以轻松正确地放置它们?

这是我的代码:

/* allocates the tab in order to place the ressources/items */
void create_map(t_world *world)
{
unsigned int x;
unsigned int y;

x = 0;
world->map = xmalloc(world->height * sizeof(int**));
while (x < world->height)
{
y = 0;
world->map[x] = xmalloc(world->lenght * sizeof(int*));
while (y < world->lenght)
{
world->map[x][y] = xmalloc(7 * sizeof(int));
bzero(world->map[x][y], 7);
++y;
}
++x;
}
}

/* base defining the number of required item */
t_elevation elevation_tab[] =
{
{1, {0, 1, 0, 0, 0, 0, 0} },
{2, {0, 1, 1, 1, 0, 0, 0} },
{2, {0, 2, 0, 1, 0, 2, 0} },
{4, {0, 1, 1, 2, 0, 1, 0} },
{4, {0, 1, 2, 1, 3, 0, 0} },
{6, {0, 1, 2, 3, 0, 1, 0} },
{6, {0, 2, 2, 2, 2, 2, 1} }
};

/* calculates the number of item required */
unsigned int *calc_elevation(t_world *world)
{
unsigned int i;
unsigned int pos;
unsigned int *tab;

i = 0;
tab = xmalloc(7 * sizeof(int));
bzero(tab, 7);
while (i < 7)
{
pos = 0;
while (pos < 7)
{
tab[pos] += (world->population /
elevation_tab[i].required_players +
world->population %
elevation_tab[i].required_players) *
(elevation_tab[i].required_ressources[pos]);
++pos;
}
++i;
}
return (tab);
}
void place_ressources(t_world *world, unsigned int *ressources)
{
//here is my missing code
}

/*First called function*/
void create_world(t_param *params, t_world *world)
{
unsigned int *ressources_needed;

world->lenght = params->lenght;
world->height = params->height;
world->population = params->team_size * 2;
create_map(world);
ressources_needed = calc_elevation(world);
place_ressources(world, ressources_needed);
show_map(world);
world->players = NULL;
free(ressources_needed);
}

世界是一个特定大小的网格,由用户决定高度和长度。网格的每个案例都有一个 int[7] 传递每个项目的数量。所以我可以在同一个箱子上放置多个项目。

最佳答案

我可以想到 2 种可能的方法来解决这个问题,但这取决于需要处理多少项目。

我首先想到的是类似于如何在计算机程序中洗牌的解决方案。取第一个元素,随机生成 x, y 坐标。获取下一个元素并生成 x、y 坐标。如果那里没有项目,则将项目放在该位置,否则生成新的 x、y 坐标。继续此操作以放置所有元素。

我能想到的另一件事是,如果您能以某种方式跟踪使用了哪些世界图 block ,那么随机生成的坐标就不会重复。

您的世界对象是一个 3 维数组这一事实使计算量呈指数增长。绝对有必要吗?当然,我真的不知道你的程序是为什么环境设计的

关于c - 如何在 map 上随机放置元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10984459/

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