給一個二維數組,橫縱座標隨機,裏面數值要麼是1,要麼是0,統計對角是1的個數

問題:給一個二維數組,橫縱座標隨機,裏面數值要麼是1,要麼是0,統計對角是1的個數?

解析 :

首先說一下,怎樣的算對角,框成一個矩形是1的就是對角,四點在直線上的值爲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是縱座標的個數!


發佈了60 篇原創文章 · 獲贊 122 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章