【问题标题】:c# filling my 2D array with specific charactersc# 用特定字符填充我的二维数组
【发布时间】:2016-05-26 17:14:42
【问题描述】:

我大约一周前在学校开始编码,并得到一个任务,要制作一个 20x20 的盒子,并用字符 B、V、M、SB、SL、_、F、P、K、L 随机填充它。我也必须对字符在框中的机会进行编码。例如:B 有 8% 的机会出现在我的 20x20 盒子里。我不知道如何让角色随机出现,也不知道如何为他们所有人编码一定的机会。

这是我目前所拥有的:

int[,] objectArray = new int[20, 20];

// Horizontal numbers.
for (int i = 1; i <= 20; i++)
{
    if (i == 1)
        Console.Write("   " + i);
    else if (i < 9)
        Console.Write("  " + i);
    else
        Console.Write(" " + i);

}
Console.WriteLine("");

//Vertical numbers
for (int x = 0; x < 20; x++)
{
    if (x < 9)
        Console.Write((x + 1) + "  ");
    else
        Console.Write((x + 1) + " ");

    for (int y = 0; y < 20; y++)
    {
        Console.Write("_  ");
    }

    Console.WriteLine();
}

Console.Read();

我希望你能给我一些关于如何解决这个问题的提示。

【问题讨论】:

  • 欢迎来到 StackOverflow!修什么?什么确切不起作用,而究竟应该如何表现呢?
  • 就编译 20x20 框而言,该代码正在工作,但我不知道如何将有一定机会出现的字符随机放入其中:(

标签: c# arrays random 2d character


【解决方案1】:

C# 有大量内置的随机数生成器代码可以帮助您 - 我建议阅读这个关于如何在某些值之间生成随机数的问题: Produce a random number in a range using C#

如果您随后将您选择的每个字符(B、V、M、SB、SL、_、F、P、K、L.I)放入一个数组中,那么您可以使用具有已生成。

像下面这样的一些代码将从您的字符串列表中打印出 20 个随机值 - 因此您可以对其进行调整以完全满足您的需要。

string[] chars = new string[] { "B", "V", "M", "SB", "SL", "_", "F", "P", "K", "L" };
Random rand = new Random();
for (int i = 0; i < 20; i++) {
      Console.WriteLine(chars[rand.Next(0, chars.Length - 1)]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 2014-12-23
    • 2021-02-10
    • 1970-01-01
    相关资源
    最近更新 更多