aboutsummaryrefslogtreecommitdiff
path: root/challenge-079/abigail/awk/ch-2.awk
blob: 164dc88b6fc9c77b61ba0c6a5279e6046337f363 (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#
# Challenge:
#
#    You are given an array of positive numbers @N.
#    Write a script to represent it as Histogram Chart and find out
#    how much water it can trap.
#

{
    #
    # First, find the maximum value.
    #
    max = 0;
    for (i = 1; i <= NF; i ++) {
        if ($i > max) {
            max = $i;
        }
    }

    #
    # Given the value, we know how wide every column must be.
    #
    format = "%" length (max) "s";
    show   = sprintf (" " format, "#");
    noshow = sprintf (" " format, " ");

    #
    # Print the histogram
    #
    for (vol = max; vol; vol --) {
        printf format, vol;
        for (i = 1; i <= NF; i ++) {
            if ($i >= vol) {printf   show;}
            else           {printf noshow;}
        }
        printf "\n";
    }

    #
    # Print the line with the bars.
    #
    bar = "";
    for (i = 0; i < length (max); i ++) {
        bar = bar "_";
    }
    printf bar;
    for (i = 1; i <= NF; i ++) {
        printf " " bar;
    }
    printf "\n";

    #
    # Print the line with the totals
    #
    printf format, " ";
    for (i = 1; i <= NF; i ++) {
        printf " " format, $i;
    }
    printf "\n";
}