aboutsummaryrefslogtreecommitdiff
path: root/challenge-099/abigail/awk/ch-2.awk
blob: d88806279ee947f56493ac553641c3db12fcc226 (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
#!/usr/bin/awk

#
# See ../README.md
#

#
# Run as: awk -f ch-2.awk < input-file
#

#
# Read input from standard input, assuming one exercise per line.
# Each line consists of a string $S, and a pattern $T, separated
# by whitespace.
#

#
# Recursively count matches:
#   - If either the string or the pattern is empty, there are no matches.
#   - Else, + count the matches if we don't match at the first character
#             if the string.
#           + if the first character of the string equals the first
#             character of the pattern:
#             o  add 1 if the pattern is just one character long
#             o  else, add the number of matches starting from the
#                then next character in the string, and the next
#                character in the pattern.
#

#
# Note that we do not have lexical variables in AWK, so we're
# using a global count variable.
#
function matches (string, pattern) {
    if (length (string) == 0 || length (pattern) == 0) {
        return 0
    }
    matches(substr (string, 2), pattern)
    if (substr (string, 1, 1) == substr (pattern, 1, 1)) {
        if (length (pattern) == 1) {
            count ++
        }
        else {
            matches(substr (string, 2), substr (pattern, 2))
        }
    }
}

{
    count = 0
    matches($1, $2)
    print count
}