【问题标题】:How can I check if a multidimensional array has a value and its index?如何检查多维数组是否具有值及其索引?
【发布时间】:2016-09-11 00:30:55
【问题描述】:

我有一个多维数组:

string[,] array = new string[,]
{
    {"cat", "dog", "plane"},
    {"bird", "fish", "elephant"},
};

我想确定它是否包含一个值,如果是,我需要它的索引,比如说“鸟”。

我需要的是

  • 查找它是否包含它。
  • 获取它的索引。
  • 获取第二个维度的长度(我不知道它怎么叫)并返回一个从第二个元素到该维度最后一个元素的随机值。

所以,如果我说“鸟”,我希望它给我一个介于“鱼”和“大象”之间的随机字符串。 如果它是一个普通的数组,我会做一个简单的

random.Next(1, array.Length);

但是,我不知道如何用二维数组制作它。

谢谢!

【问题讨论】:

  • 我可以检查您是否只在最左边的列中搜索匹配项,然后从其余列中生成随机值?或者匹配可以在任何列中?

标签: c# arrays multidimensional-array


【解决方案1】:

您需要使用array.GetLength() 而不是array.Length 来获取多维数组的一维长度。

遍历数组。如果找到匹配项,则存储当前索引并从匹配行中获取随机值,使用 array.GetLengthRandom 类。

Random rnd = new Random();

int index = -1;
string randomWord = "";

for(int i = 0; i < array.GetLength(0); i++)
{
    if (array[i,0] == "bird")
    {
        index = i;
        randomWord = array[i,rnd.Next(1, array.GetLength(1))];
        break;
    }
}

【讨论】:

    【解决方案2】:

    List&lt;list&lt;string&gt;&gt; 会更容易使用。

    如果我从您的原始数据开始,我会这样做以将其嵌套在列表中:

    List<List<string>> nested =
        array
            .OfType<string>()
            .Select((x, i) => new { x, i })
            .GroupBy(x => x.i / array.GetLength(1), x => x.x)
            .Select(x => x.ToList())
            .ToList();
    

    现在我可以编写这个函数了:

    var random = new Random();
    Func<string, string> getRandom = x =>
    (
        from row in nested
        where row[0] == x
        from choice in row.Skip(1).OrderBy(y => random.Next())
        select choice
    ).FirstOrDefault();
    

    正确地用getRandom("bird") 调用它会给我"fish""elephant"

    【讨论】:

      【解决方案3】:

      这是一个使用多维数组做你想做的事的例子。请注意,在评论中有一个您需要处理的极端情况。

      using System;
      
      class Program
      {
          static string[,] array = new string[,]
          {
              { "cat", "dog", "plane" },
              { "bird", "fish", "elephant" },
          };
      
          static int FindRow(string elem)
          {
              int rowCount = array.GetLength(0),
                  colCount = array.GetLength(1);
              for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
              {
                  for (int colIndex = 0; colIndex < colCount; colIndex++)
                  {
                      if (array[rowIndex, colIndex] == elem)
                      {
                          return rowIndex;
                      }
                  }
              }
              return -1;
          }
      
          static string PickRandomTail(int rowIndex)
          {
              int colCount = array.GetLength(1);
              int randColIndex = new Random().Next(1, colCount);
              return array[rowIndex, randColIndex];
          }
      
          static void Main()
          {
              int rowIndex = FindRow("bird");
              if (rowIndex < 0)
              {
                  // handle the element is not found
              }
              Console.WriteLine(PickRandomTail(rowIndex));
          }
      }
      

      【讨论】:

        【解决方案4】:

        这是一个不破坏数据结构的示例:

        static int IndexOf<T>(T[,] array, T toFind)
            {
                int i = -1;
                foreach (T item in array)
                {
                    ++i;
                    if (toFind.Equals(item))
                        break ;
                }
                return i;
            }
        
            static string GetRandomString(string[,] array, string toFind)
            {
                int lineLengh = array.Length / array.Rank;
                int index = IndexOf(array, toFind);
                int lineIndex = index / lineLengh;
        
                Random random = new Random();
                index = random.Next(lineIndex * lineLengh + 1, (lineIndex + 1) * lineLengh);
                return array[lineIndex, index % lineLengh];
            }
        
            // If you want to get a random element between the index and the end of the line
            // You can replace "bird" by any word you want,
            // except a word at the end of a line (it will return you the first element of the next line)
            // static string GetRandomString(string[,] array, string toFind)
            // {
            //     int lineLengh = array.Length / array.Rank;
            //     int index = IndexOf(array, toFind);
        
            //     Random random = new Random();
            //     index = random.Next(index + 1, (index / lineLengh + 1) * lineLengh);
            //     return array[index / lineLengh, index % lineLengh];
            // }
        
            static void Main(string[] args)
            {
                string[,] array = new string[,]
                {
                    {"cat", "dog", "plane"},
                    {"bird", "fish", "elephant"},
                };
                Console.WriteLine(GetRandomString(array, "bird"));
                Console.ReadKey();
            }
        

        为了完美,您应该添加一个检查索引是否不是-1,以及是否可以从索引和行尾之间的范围内获取随机数。


        如果您的多维数组可以包含不同大小的行,您还应该使用 string[][]。使用 string[,],您的数组必须包含相同大小的行。

        【讨论】:

          猜你喜欢
          • 2013-03-15
          • 2019-05-29
          • 1970-01-01
          • 2015-10-16
          • 2014-05-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多