C#2D Array通过obj.method()调用另一个类;

问题描述 投票:1回答:4

编写一个Java类,它具有一个名为count的静态方法,它接受一个2D整数数组和一个目标整数值作为参数,并返回数组中目标值的出现次数。例如,如果名为list的变量引用包含值{{3,5,7,94}{5,6,3,50}}的数组,则count(list, 3)的调用应返回2,因为数组中有2次出现值3。

这是我的编码,它没有给我正确的输出P.S: - 我被告知采取计数方法公共而非静态

class java
{
    public int count(int [,] list,int n)
    {
        int c = 0;
        for (int i = 0; i <list.Length; i++)
        {
            for (int j = 0; j < list.Length; j++)
            {
                if (list[i, j] == n)
                {
                    c++;
                }
            }
        }
        return c;
    }

class Program
{
    static void Main(string[] args)
    {
        java jv = new java();
        int[,] arr = { { 3, 5, 7, 94 }, {5, 6, 3, 50 } };
        int k=0;
        jv.count(arr,k);
    }
}
c# .net arrays
4个回答
2
投票

迭代多维数组需要您使用自己的长度迭代每个维度,这意味着ij应分别为0-30-1

从图中可以看出,但对于不同尺寸的数组:

Multi-Dimensional Array

GetLength(0)将返回4。

GetLength(1)将返回3。

当你在i = (0 to Length) = 8时j = (0 to Length)超过Length = Height * Width时,你正在做的是迭代它们,这意味着8超过8。

所以你的count()方法应该是这样的:

public int count(int[,] list,int n)
{
    int c = 0;
    for (int i = 0; i < list.GetLength(0); i++)
    {
        for (int j = 0; j < list.GetLength(1); j++)
        {
            if (list[i, j] == n)
            {
                c++;
            }
        }
    }
    return c;
}

如果你想将数组迭代为一个数组数组而不是让事情变得复杂“我现在正在迭代哪个维度?”你可以使用Jagged Arrays(当然还有更多的事情需要考虑),这将允许你用这个短的Linq替换整个方法:

public int count(int[][] list,int n)
{
    return list.SelectMany(x => x).Count(x => x == n);
}

要么:

public int count(int[][] list, int n)
{
    return list.Sum(x => x.Count(y => y == n));
}

1
投票

注意i在内部for中对抗j。并且使用i <list.GetLength(0)j < list.GetLength(1)对抗list.Length

class java
{
    public int count(int [,] list,int n)
    {
        int c = 0;
        for (int i = 0; i < list.GetLength(0); i++)
        {
            for (int j = 0; j < list.GetLength(1); j++)
            {
                if (list[i, j] == n)
                {
                    c++;
                }
            }
        }
        return c;
    }

class Program
{
    static void Main(string[] args)
    {
        java jv = new java();
        int[,] arr = { {3,5,7,94 }, {5,6,3,50 } };
        int k=5;
        Console.WriteLine(jv.count(arr,k));
    }
}

0
投票

由于Array已经实现了IEnumerable,你可以在这里简单地使用foreach循环(随意将static更改为实例方法):

    public static int count(int[,] list, int n)
    {
        int c = 0;
        foreach (var item in list) if (item == n) c++;
        return c;
    }

用法:

  static void Main()
    {
        var r = count(new int[,]{
            {
                5, 8, 7, 8
            }, 
            {
                0, 8, 9, 3
            }}, 8);

        Console.WriteLine(r);

输出:3

附:通常如果可能的话,最好使用for循环,因为它比foreach快,但在这种情况下我喜欢,如果你使用foreach你没有嵌套的for循环也没有GetLength(x)调用它只是一行代码和它几乎具有相同的性能......


-1
投票

你的错误在这一行:

for (int j = 0; i < list.Length; j++)

它应该是

for (int j = 0; j < list.Length; j++)
© www.soinside.com 2019 - 2024. All rights reserved.