代码之家  ›  专栏  ›  技术社区  ›  Ginxxx

在多维数组(C Unity)中获取特定的整个(0)维

  •  0
  • Ginxxx  · 技术社区  · 8 年前

    我怎样才能在多维数组中只计算我想要的特定整列

    我像这样计算我的整个列和行

    //COLUMN
    for(int col = 0; col < table.GetLength(0); col++)
    {
        int sum = 0;
        //ROW
        for (int row = 0; row < table.GetLength(1); row++)
        {
             if (table[col,row] != null)
             {
                 sum++;
             }
        }
         Debug.Log("table column: " + col + " has " + sum + " data");
    }
    

    我只想得到特定的整列,然后像这样移到另一列。我需要这样做,因为我需要将它与最后一个列值与下一个列值进行比较。

    例如:我想检查第二列中有多少数据,然后将其与第一列进行比较。

    2 回复  |  直到 8 年前
        1
  •  2
  •   MakePeaceGreatAgain    8 年前

    你快到了。您所要做的就是将当前列的总和存储到一个列表中:

    var List<int> sums = new List<int>();
    //COLUMN
    for(int col = 0; col < table.GetLength(0); col++)
    {
        int sum = 0;
        //ROW
        for (int row = 0; row < table.GetLength(1); row++)
        {
             if (table[col,row] != null)
             {
                 sum++;
             }
        }
        Debug.Log("table column: " + col + " has " + sum + " data");
        sums.Add(sum);
    }
    

    现在,您可以很容易地比较第1列和第2列中的行数:

    bool areEqual = sums[0] == sums[1];
    
        2
  •  0
  •   Ginxxx    8 年前

    找到解决方案:)

    //generic function
    public static int CountRow<T>(T[,] table, int col)
    {
        if (table == null || col < 0 || col >= table.GetLength(1)) 
        {
            //handle error
            return -1;
        }
    
        //this is the same as the block of the outer for loop
        int sum = 0;
        for (int row = 0; row < table.GetLength(1); row++)
        {
            if(table[col,row] != null)
            {
                sum++;
            }
        }
        return sum;
    }
    

    然后像这样使用

    int prevSum = -1;
    for (int col = 0; col < table.GetLength(0); ++col)
    {
        int sum = CountRow(table, col);
        Debug.Log("table column :" + col + " has " + sum + " data");
        if (sum == prevSum)
        {
           //comparison happens
        }
    }