gpt4 book ai didi

c - 显示垂直和对角字母的问题 - C 编程

转载 作者:太空宇宙 更新时间:2023-11-04 04:32:15 25 4
gpt4 key购买 nike

我是 C 编程的新手,我正在尝试创建一个 Word Search .

我有一个单词列表,其中只有 4 个是随机选择的。这 4 个字要水平、垂直或对角地打印在网格中,但我只能让它们水平打印。我还必须补充一点,我不知道这段代码是如何工作的,所以如果有人真的能帮助我,我真的很感激。那么任何人都可以帮助我在正确的方向上创建垂直和对角对齐的随机单词吗? http://imgur.com/VSrXf4C

void putHorizzontalWord(char word[10])
{
int rRow, rCol , ok , i;

do
{

rRow = rand() % 10;
rCol = rand() % 10;

ok = 1;
if(rCol + strlen(word) < 10)
{
for(i = 0;i < strlen(word);i++)
{
if(puzzle[rRow][rCol + i] == ' ' ||
puzzle[rRow][rCol + i] == word[i])
{
puzzle[rRow][rCol + i] = word[i];
}
else
{
ok = 0;
}
}
}
else
{
ok = 0;
}
}
while(ok == 0);
}

最佳答案

这里有一些注释旨在向您解释该代码的作用:

// This function takes a string as input then puts that string
// at a random "open" location in a 2D grid (puzzle) in an
// horizontal manner
//
// This function expects the size of the string to be at most = 10

void putHorizontalWord(char word[10])
{
int rRow, rCol , ok , i;

do
{
// Randomly select a location
rRow = rand() % 10;
rCol = rand() % 10;

// For now, assume that this location is "ok", i.e. is open
ok = 1;

// Check that the word fits inside the grid from (rRow, rCol)
if(rCol + strlen(word) < 10)
{
// If it does, then try to put the word at this location
// Thus, we need to process the word character by character
for(i = 0;i < strlen(word);i++)
{
// We are inside the for loop
// The current character to process is word[i]
// And the current cell to fill is (rRow, rCol + i)
//
// If current cell is empty || is same as the current character
// then this cell is "open" i.e. we can use it
if(puzzle[rRow][rCol + i] == ' ' ||
puzzle[rRow][rCol + i] == word[i])
{
puzzle[rRow][rCol + i] = word[i];
}
else
{
// The cell is not open
// => (rRow, rCol) is not "ok"
ok = 0;
}
}
}
else
{
// word not fits inside the grid from the location
// => (rRow, rCol) is not "ok"
ok = 0;
}
}
while(ok == 0); // Exit loop while not found a good location
}

如果您已经理解,那么您现在可以修改它来编写您的垂直和对角线版本。如果您还不明白,请告诉我还有什么不明白。

关于c - 显示垂直和对角字母的问题 - C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34620824/

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