aboutsummaryrefslogtreecommitdiff
path: root/challenge-084/abigail/awk/ch-2.awk
blob: ddb4a84b5a5e9665380c84ccf67de96f38aaf322 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#
# You are given matrix of size m x n with only 1 and 0.
#
# Write a script to find the count of squares having all four corners set as 1.
#

BEGIN {
    FS = " ";  # Split input on spaces.
    x  = 0;    # Array indices start at 1.
}

#
# Read the input, store it in array matrix.
#
{
    x ++;
    for (y = 1; y <= NF; y ++) {
        matrix [x, y] = +$y;
    }
    y = NF;
}

END {
    #
    # Now, x and y are the maximum index values.
    #
    count = 0;

    #
    # Cubic algorithm, counting all possible squares.
    #
    for (i = 1; i <= x; i ++) {
        for (j = 1; j <= y; j ++) {
            if (matrix [i, j]) {
                for (k = 1; i + k <= x && j + k <= y; k ++) {
                    if (matrix [i,     j + k] &&
                        matrix [i + k, j    ] &&
                        matrix [i + k, j + k]) {
                        count ++;
                    }
                }
            }
        }
    }
    print count;
}