给一个二维数组,横纵坐标随机,里面数值要么是1,要么是0,统计对角是1的个数

问题:给一个二维数组,横纵坐标随机,里面数值要么是1,要么是0,统计对角是1的个数?

解析 :

首先说一下,怎样的算对角,框成一个矩形是1的就是对角,四点在直线上的值为1组成矩形就算对角。如下图,框起来的都算对角。统计它里面对角的个数?怎么算呢?

给一个二维数组,横纵坐标随机,里面数值要么是1,要么是0,统计对角是1的个数

1. 如果要是对角,肯定一开始那个值为1,它在数组里面的坐标是i,j,即a[i][j] =1。

2.还要计算其他三个点是1,就需要在i,j的基础上往下探测,长度是横坐标的长度,图中是7(下标为0,1,2,3,4,5,6),也需要在j的基础上往右探测,图中的是6(下标为 0,1,2,3,4,5)。

好了算法讲完了,下面给下实现代码:

public class MyTest {
    public static void main(String[] args) {
        int m = 15;
        int n = 23;
        int a[][] = initTable(m, n);
        print(a, m, n);
        int count = count(a, m, n);
        System.out.println("个数为:" + count);

    }

    static int[][] initTable(int m, int n) {
        int[][] a = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                a[i][j] = Math.random() > 0.5 ? 1 : 0;  //设置值为0 或1
            }
        }
        return a;
    }

    static void print(int a[][], int m, int n) {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(a[i][j]);
            }
            System.out.println();
        }
    }

    static int count(int a[][], int m, int n) {
        int count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (a[i][j] == 1) {
                    for (int p = i + 1; p < m; p++) {
                        for (int q = j + 1; q < n; q++) {
                            if (a[p][q] == 1 && a[p][j] == 1 && a[i][q] == 1) {
                                count++;
                            }
                        }
                    }
                }
            }
        }
        return count;
    }
}

执行结果:

01001010001010000111111
01111111100101110110001
00001101101101101010110
10101111111001001101111
11111101111110100111001
11110100100100000001110
01011010101100011111101
01101010010011110111110
10001000010000100011000
11110101111100101110000
01111110100110011101101
01100000110111010001011
11000100000010110111000
00011110011100011011111
10111101100100110001100

个数为:2457

说明:代码中的m是横坐标的长度,n是纵坐标的个数!