我有以下代码,我随机创建7个房间名称,并给它们一个类型(开始,中间,结束)。我现在需要随机连接这些房间,每个房间有3到6个连接。我无所适从。我找到了一个如何使用bitcode做的例子,但在我的其他帖子中,我仍然不明白那个版本。如果有人可以提供帮助,那将非常感激。以下是房间的相关代码:
这是我宣布房间的地方:
void createRooms(char *dir) {
//Name of rooms
char *roomNames[] = {
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j"
};
//Filenames for each room
char *filenames[] = {
"a.txt",
"b.txt",
"c.txt",
"d.txt",
"e.txt",
"f.txt",
"g.txt",
"h.txt",
"i.txt",
"j.txt"
};
int rooms[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//Call function to write files for rooms
writeRoomFiles(rooms, dir, filenames, roomNames);
//Call function to randomly connect rooms
//Call function to categorize rooms
categorizeRooms(rooms, dir, filenames, roomNames);
}
然后我希望有一个连接这些房间的功能,并将它们的连接放入目录中创建的.txt文件中。我还需要稍后向用户提供连接,但我相信我知道如何做到这一点,因为我能够提供roomName和类型。
答案 0 :(得分:0)
您并没有真正描述您如何代表您的联系。你似乎通过将所有内容写入各种文件来组织你的世界,这看起来非常笨拙。
假设您有7个房间,您可以通过0到6的索引来识别。然后您可以将连接表示为7×7矩阵conn
,其中conn[a][b] != 0
表示之间存在连接客房a
和b
。如果您想要双向连接,则必须建立conn[a][b] == conn[b][a]
。另一方面,您可以表示与矩阵的单向连接。
提供一个连接房间的好方法,以便每个房间有三个或更多连接到其他房间,同时确保所有房间都连接起来并非易事。
我建议如下:
这似乎工作得很好,除了你可能最终得到没有连接的房间。您可以通过在洗牌后将未访问的房间移动到前面来解决这个问题,以便在后期阶段或多或少强制执行剩余的未访问的房间。
下面的示例程序将此策略付诸实践:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define MAX_ROOM 7
int conn[MAX_ROOM][MAX_ROOM] = {{0}};
/*
* Return a non-negative random value less than n.
*/
int uniform(int n)
{
return n * (rand() / (double) RAND_MAX);
}
/*
* Recursively connect the two rooms
*/
void connect(int visited[], int there, int here)
{
conn[here][there] = 1;
conn[there][here] = 1;
if (visited[here] == 0) {
int room[MAX_ROOM - 1]; // connection candidate
int next[MAX_ROOM - 1]; // ditto, orderd to [unvisited, visited]
int i, j;
visited[here] = 1;
// build list of rooms
for (i = 0; i < MAX_ROOM; i++) room[i] = i;
room[here] = MAX_ROOM - 1;
// shuffle rooms
i = MAX_ROOM - 1;
while (i) {
int swap;
j = uniform(i--);
swap = room[i];
room[i] = room[j];
room[j] = swap;
}
// bring unvisited rooms to the front
j = 0;
for (i = 0; i < MAX_ROOM; i++) {
if (visited[room[i]] == 0) next[j++] = room[i];
}
// and append the visited rooms at the back
for (i = 0; i < MAX_ROOM; i++) {
if (visited[room[i]] != 0) next[j++] = room[i];
}
// connect the first three
for (i = 0; i < 3; i++) {
connect(visited, here, next[i]);
}
}
}
int main(void)
{
char *room_name[] = { "Eclectic", "Country", "Nautical", "Romantic",
"Modern", "Urban", "Tropical", "Traditional", "Vintage", "European" };
int visited[MAX_ROOM] = {0}; // was room visited in BFS?
int i, j;
srand(time(NULL));
// establish two-way connections
connect(visited, 0, 1);
// shuffle room names (for fun)
i = 10;
while (i) {
char *p;
j = uniform(i--);
p = room_name[i];
room_name[i] = room_name[j];
room_name[j] = p;
}
// print rooms and connections
for (i = 0; i < MAX_ROOM; i++) {
printf("%s\n", room_name[i]);
for (j = 0; j < MAX_ROOM; j++) {
if (conn[i][j]) printf(" -> %s\n", room_name[j]);
}
printf("\n");
}
return 0;
}