【问题标题】:The sum for every column and raw in a 2D array with N columns具有 N 列的二维数组中每一列和每一行的总和
【发布时间】:2021-12-04 17:31:31
【问题描述】:

我在 C# 中有一个二维数组,用户输入来填充数组。我需要帮助才能找到每一列和每一行的总和。

var input = Console.ReadLine();
        var n = int.Parse(input);

        int[,] intArr = new int[n, 3];

        for (int i = 0; i < n; i++)
        {
            input = Console.ReadLine();
            var parts = input.Split(' ');

            for (int j = 0; j < 3; j++)
            {
                intArr[i, j] = int.Parse(parts[j]);
            }
        }
        if (n == 1)
        {
            Console.WriteLine("Sum of column " + Convert.ToString(n) + ": " + (intArr[n - 1, 0] + intArr[n - 1, 1] + intArr[n - 1, 2]));
            Console.WriteLine("Row1: " + (intArr[n - 1, 0]));
            Console.WriteLine("Row2: " + (intArr[n - 1, 1]));
            Console.WriteLine("Row3: " + (intArr[n - 1, 2]));
        }
        if (n == 2)
        {
            Console.WriteLine("Sum of column " + Convert.ToString(n - 1) + ": " + (intArr[n - 2, 0] + intArr[n - 2, 1] + intArr[n - 2, 2]));
            Console.WriteLine("Sum of column " + Convert.ToString(n) + ": " + (intArr[n - 1, 0] + intArr[n - 1, 1] + intArr[n - 1, 2]));
            Console.WriteLine("Row 1: " + (intArr[n - 2, 0] + intArr[n - 1, 0]));
            Console.WriteLine("Row 2: " + (intArr[n - 2, 1] + intArr[n - 1, 1]));
            Console.WriteLine("Row 3: " + (intArr[n - 1, 2] + intArr[n - 1, 1]));

      }
   }
User input:
       2
       1 2 3
       4 5 6
       The output:  
       Sum of column 1: 6
       Sum of column 2: 15
       Row 1: 5
       Row 2: 7
       Row 3: 11

我想要用户输入的 N 列的此输出,但我被卡住了! 谢谢!

【问题讨论】:

  • 简单提示:将i替换为j

标签: c# arrays


【解决方案1】:

不确定,您的问题是得到了不想要的结果,还是您的模型具有固定数量的元素?数组是一个固定大小的数据容器,所以如果你想要任意数量的列,那么架构可能就是你想要改变数组的地方。 无论如何,问题 1 是您让用户选择了他们想要的行数,但现在选择了多少列,所以假设您的数据会有 3 个冲突。所以你在数组上有一个 .getUpperBound() ,它接受一个范围参数,这样我们就可以使用动态结构

//From:
for (int i = 0; i < n; i++)
{
        input = Console.ReadLine();
        var parts = input.Split(' ');

        for (int j = 0; j < 3; j++)
        {
            intArr[i, j] = int.Parse(parts[j]);
        }
    }

//TO:  
var rows = new List<int[]>();      
for (int i = 0; i < n; i++)
{
    input = Console.ReadLine();
    var parts = input.Split(' ');
    var listOf = new List<int>();                

    for (int j = 0; j < parts.GetUpperBound(0); j++)
        {
            listOf.Add(int.Parse(parts[j]));
        }
    rows.Add(listOf.ToArray());
}

来自https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate?view=net-5.0你获得聚合能力

    [Fact]
    public void SumExerciseTest()
    {
    /*
     The output:  
     Sum of column 1: 6
     Sum of column 2: 15
     Row 1: 5
     Row 2: 7
     Row 3: 11 => 9
    */
        var testData = new[] { "1 2 3", "4 5 6" };

        var input = "2"; // Console.ReadLine();
        var n = int.Parse(input);

        var rows = new List<int[]>(n);

        for (int i = 0; i < n; i++)
        {
            input = testData[i];
            var parts = input.Split(' ');

            var listOf = new List<int>();
            for (int j = 0; j <= parts.GetUpperBound(0); j++)
            {
                listOf.Add(int.Parse(parts[j]));
            }
            rows.Add(listOf.ToArray());
        }

        var rowSums = new List<int>(n);
        foreach (int[] row in rows)
        {
            rowSums.Add(row.Aggregate((result, item) => result + item));
        }

        int maxLength = 0;
        var rowLengths = new List<int>(n);
        foreach (int[] row in rows)
        {
            rowLengths.Add(row.Length);
        }
        maxLength = rowLengths.Max();

        int[] columnSums = new int[maxLength];
        for (int idx = 0; idx < columnSums.Length; idx++){
            foreach (var row in rows)
            {
                if (row.GetUpperBound(0) >= idx)
                {
                    columnSums[idx] += row[idx];
                }
            }
        }

        int counter = 0;
        //Outputting:
        foreach(var sum in rowSums)
        {
            counter += 1;
            System.Diagnostics.Debug.WriteLine($"Row {counter}: {sum}");
        }

        counter = 0;
        foreach(var sum in columnSums)
        {
            counter += 1;
            System.Diagnostics.Debug.WriteLine($"Column {counter}: {sum}");
        }

【讨论】:

    【解决方案2】:

    好吧,让我们实现(提取)对任意列和行求和的方法:

      private static int SumColumn(int[,] array, int column) {
        if (array == null)
          throw new ArgumentNullException(nameof(array));
    
        if (column < 0 || column >= array.GetLength(1))
          throw new ArgumentOutOfRangeException(nameof(column)); 
    
        int result = 0;
    
        for (int r = 0; r < array.GetLength(0); ++r)
          result += array[r, column];
    
        return result; 
      }
    
      private static int SumRow(int[,] array, int row) {
        if (array == null)
          throw new ArgumentNullException(nameof(array));
    
        if (row < 0 || row >= array.GetLength(0))
          throw new ArgumentOutOfRangeException(nameof(row)); 
    
        int result = 0;
    
        for (int c = 0; c < array.GetLength(1); ++c)
          result += array[row, c];
    
        return result; 
      }
    

    那么你就可以放

      for (int c = 0; c < intArr.GetLength(1); ++c)
        Console.WriteLine($" Sum of column {c + 1}: {SumColumn(intArr, c)}"); 
    
      for (int r = 0; r < intArr.GetLength(0); ++r)
        Console.WriteLine($" Sum of row {r + 1}: {SumRow(intArr, r)}");
    

    【讨论】:

      猜你喜欢
      • 2021-08-13
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2022-12-03
      • 2016-12-07
      • 1970-01-01
      相关资源
      最近更新 更多