在C#中用锯齿状数组求中间数

时间:2017-02-22 09:27:36

标签: c#

我用锯齿状数组编写了一些代码但是当我将中间数字程序不能正常工作时我无法解决它...:

 public class JaggedArray
{ 
    public static void Array()
    {
        int[][] arrayOfArray = ArrayOfArray();
        var tong = 0;
        for (var i = 1; i < arrayOfArray.Length; i++)
        {
            for (var j = 0; j < arrayOfArray[i].Length; j++)
            {
                var bienTam = arrayOfArray[i].Length;
                var tamThoi = j;
                if (bienTam%2==0&&tamThoi==bienTam/2) 
                {
                    tamThoi++;
                    tong += arrayOfArray[i][tamThoi];
                }
            }
        }
        OutPut(arrayOfArray, tong);
    }

private static int[][] ArrayOfArray()
    {
        Random ngauNhien = new Random();
        int[][] arrayOfArray = new int[13][];
        for (var i = 0; i <arrayOfArray.Length; i++)
        {
            arrayOfArray[i] = new int[i];
            for (var j = 0; j < arrayOfArray[i].Length; j++)
            {
                arrayOfArray[i][j] = ngauNhien.Next(0, 99); //throw exception

            }
        }

        return arrayOfArray;
    }

有人可以解释为什么我错了,以及如何解决它?

2 个答案:

答案 0 :(得分:1)

您正在解决的问题是 Linq 非常适合:

int[][] arrayOfArray = new int[][] {
  new[] {1, 2, 3}, // 2 is the middle item
  new[] {4, 5}     // in case of tie, let 5 (right) be the middle item
  new[] {7},       // 7  
  new int[] {},    // should be ignored
};

// 2 + 5 + 7 == 14 
var result = arrayOfArray
  .Where(line => line != null && line.Length > 0)
  .Sum(line => line[line.Length / 2]);

答案 1 :(得分:0)

所以我已经编译了:

public class JaggedArray
{
    public static void Array()
    {
        int[][] arrayOfArray = ArrayOfArray();
        var tong = 0;
        for (var i = 1; i < arrayOfArray.Length; i++)
        {
            for (var j = 0; j < arrayOfArray[i].Length; j++)
            {
                var bienTam = arrayOfArray[i].Length;
                var tamThoi = j;
                if (j % 2 == 0 && j / 2 == bienTam / 2)
                {
                    tamThoi++;
                    // You need to check here that tamThoi isn't
                    // outside the bounds of your array
                    if (tamThoi >= arrayOfArray[i].Length)
                    {
                        continue;
                    }
                    tong += arrayOfArray[i][tamThoi];
                }
            }
        }


    }

    private static int[][] ArrayOfArray()
    {
        Random ngauNhien = new Random();
        int[][] arrayOfArray = new int[13][];
        for (var i = 0; i < 13; i++)
        {
            arrayOfArray[i] = new int[i];
            // here you're better off using i
            // instead of the arrayOfArray[i].Length - because you know the length
            for (var j = 0; j < i; j++)
            {
                arrayOfArray[i][j] = ngauNhien.Next(0, 99);
            }
        }

        return arrayOfArray;
    }
}

你可以使用LINQ更加简洁。