aboutsummaryrefslogtreecommitdiff
path: root/challenge-095/abigail/awk/ch-2.awk
blob: b88c1e87f04723d09745123a2a0b4e9ce2593ce2 (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
BEGIN {
    error = "Stack is empty"
}

{
    size = length (stack)
}

/^push/ {
    #
    # Push the argument on the stack. We use split to retrieve
    # the argument. split() puts the various parts into its
    # second argument -- an array. Note that arrays are indexed 1-based.
    #
    split($0, a, / +/)
    stack [size + 1] = a [2]
}

/^pop/  {
    #
    # Remove the last element from the stack.
    #
    delete stack [size]
}

/^top/  {
    #
    # Print the top of the stack, or an error if the stack is empty.
    #
    print size ? stack [size] : error
}

/^min/  {
    #
    # Find the minimum number in the stack, which we find by iterating
    # over the array which represents the stack. If the stack is
    # empty, we print an error message.
    #
    if (size) {
        min = stack [1]
        for (i = 2; i <= size; i ++) {
            if (min > stack [i]) {
                min = stack [i]
            }
        }
        print min
    }
    else {
        print error
    }
}