计算数组中的负数

Dis*_*ada 5 java arrays multidimensional-array

我正在尝试查找二维数组(平方矩阵)中负数的计数。在矩阵中,如果您从上到下然后向左写,则写数增加。此处的逻辑是从最后一列开始,然后向左进行。如果找到负数,则增加行索引,并以相同的方式进行操作,直到最后一行。我在Java代码中收到错误,但在python中却没有。

public class O_n 

{

public static void main(String[] args)

{

    int firstarray[][] = {{-2,-1,0},{-1,0,1},{0,1,2}};
    int secondarray[][] = {{-4,-3,-2},{-3,-2,-1},{-2,-1,0}};
    System.out.print ("First array has"+count_neg(firstarray));
    System.out.println("negative numbers");
    System.out.print ("Second array has"+count_neg(secondarray));
    System.out.println("negative numbers");
}

public static int count_neg(int x[][]){
    int count = 0;
    int i = 0; //rows
    int j = x.length - 1; //columns

    System.out.println("max column index is: "+j);
    while ( i >=0 && j<x.length){
        if (x[i][j] < 0){ // negative number
            count += (j + 1);// since j is an index...so j + 1
            i += 1;
        }
        else { // positive number
            j -= 1;
        }
    }
    return (count);
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到这个输出

max column index is: 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at O_n.count_neg(O_n.java:22)
    at O_n.main(O_n.java:9)
/home/eos/.cache/netbeans/8.1/executor-snippets/run.xml:53: Java 
returned: 1
BUILD FAILED (total time: 0 seconds)
Run Code Online (Sandbox Code Playgroud)

此代码有什么问题?相同的东西在python中工作...

def count_neg(array):
    count = 0
    i = 0 # row
    j = len(array) -1 # col
    # since we are starting from right side

    while j >= 0 and i < len(array):
        if array[i][j] < 0: 
            count += (j + 1)
            i += 1
        else:
            j -= 1
    return count
print(count_neg([[-4,-3,-1,1],[-2,-2,1,2],[-1,1,2,3],[1,2,4,5]]))
Run Code Online (Sandbox Code Playgroud)

Sta*_*gle 1

您的索引与 python 版本相反:

while j >= 0 and i < len(array)
Run Code Online (Sandbox Code Playgroud)

到Java版本:

while (i >= 0 && j < x.length)
// Change to
while (j >= 0 && i < x.length)
Run Code Online (Sandbox Code Playgroud)

输出:

max column index is: 2
3
Run Code Online (Sandbox Code Playgroud)

如果您使用Java8,您可以使用流来实现count_neg:

public static int countNeg(int x[][]) {
    long count = Stream.of(x)
            .flatMapToInt(arr -> IntStream.of(arr))
            .filter(i -> i < 0)
            .count();
    return Math.toIntExact(count);
}
Run Code Online (Sandbox Code Playgroud)