如何创建一个函数C#将随机单词放在char的矩阵中? [英] How to create a function C# to put random words in matrix of char?

查看:55
本文介绍了如何创建一个函数C#将随机单词放在char的矩阵中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!我需要一些学校项目的帮助。我有一个矩阵N x N,一个字符串[]字和字符串[]方向。我需要帮助创建一个函数,在矩阵中生成随机方向的单词。



我尝试过:



Hi all! I need some help for a school project.I have a matrix N x N , a string[] Words , and string[]Directions. I need help at create a function to generate in the Matrix the Words in Random Directions.

What I have tried:

Random rn = new Random();
            int count = 0;
           
            for (int k = 0; k < nou1.n; k++)
            {
                bool ok = false;
                int dir = rn.Next(0, nou1.nrdir-1);



}


}

推荐答案

假设您正在创建单词搜索或类似内容,它并不像您想象的那么简单。



首先编写一个方法来插入单个单词:

Assuming that you are creating a "word search" or similar, it's not as simple as you might think.

Start by writing a method to insert a single word:
private Random rand = new Random();
private bool InsertWord(string word, char[,] matrix)
   {
   ...
   }

返回值如果单词成功插入则为true,而错误则为true。如果它对于矩阵而言太大,则无法插入单词。

首先检查单词是否适合:这很容易 - 如果单词的长度小于UpperBound或者任何尺寸,它都适合某种方式!



现在使用Random实例(它应该是私有的,因此它不是方法本地的)来生成方向和(X ,Y)对应该通过的单词。

使用方向修改(X,Y)值,使整个单词适合矩阵。例如,如果单词ifHELLO,方向是从左到右,并且X宽度是10,则需要调整X以使其小于或等于10 - 5或者teh将超出矩阵的右边缘。



使用foreach从单词依次访问每个字符,并将它们插入(X,Y),修改X和Y根据指示:

The return value is a true if the word was inserted successfully, and a false it was not. A word can't be inserted if it it too big for the matrix for example.
Start by checking if the word fits at all: that's easy - if the length of the word is less than the UpperBound or either dimension, it fits somehow!

Now use the Random instance (which should be private so it's not local to the method) to generate a direction and an (X, Y) pair the word should go through.
Use the direction to modify the (X, Y) value so that the whole word fits in the matrix. For example, if the word if "HELLO", the direction is "left to right", and the X width is 10, then X needs to be adjusted so that it is less than or equal to 10 - 5 or teh word will "overrun" the right edge of the matrix.

Use foreach to access each character in turn from the word, and insert them at (X, Y), modifying X and Y according to the direction:

Dir        dX  dY
Up          0  -1
UpRight     1  -1
Right       1   0
DownRight   1   1
Down        0   1
DownLeft   -1   1
Left       -1   0
UpLeft     -1  -1

让它工作,然后再看在碰撞,这将阻止你插入一个单词。



当你有其他一切工作时,随机用字符填充所有未分配的矩阵位置。

Get that working, then look at "collisions" which will prevent you inserting a word.

When you have everything else working, Randomly fill all unassigned matrix locations with characters.


这篇关于如何创建一个函数C#将随机单词放在char的矩阵中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆