aboutsummaryrefslogtreecommitdiff
path: root/challenge-099/paulo-custodio/awk/ch-1.awk
blob: 8b65b0b4a5fba29f5c4612d000ffe6b5117902e8 (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
#!/usr/bin/gawk

# Challenge 099
#
# TASK #1 > Pattern Match
# Submitted by: Mohammad S Anwar
# You are given a string $S and a pattern $P.
#
# Write a script to check if given pattern validate the entire string.
# Print 1 if pass otherwise 0.
#
# The patterns can also have the following characters:
#
# ? - Match any single character.
# * - Match any sequence of characters.
# Example 1:
# Input: $S = "abcde" $P = "a*e"
# Output: 1
# Example 2:
# Input: $S = "abcde" $P = "a*d"
# Output: 0
# Example 3:
# Input: $S = "abcde" $P = "?b*d"
# Output: 0
# Example 4:
# Input: $S = "abcde" $P = "a*c?e"
# Output: 1

function match_pattern(s, p) {
    while (1) {
        if (s=="" && p=="")         # string and pattern finished
            return 1;
        else if (s=="" || p=="")    # either string or pattern finished
            return 0;
        else if (p ~ /^\?/) {       # match any character
            s = substr(s, 2);
            p = substr(p, 2);
        }
        else if (p ~ /^\*/) {       # match any sub-sequence
            p = substr(p, 2);
            for (i = 1; i <= length(s); i++) {
                if (match_pattern(substr(s, i), p))
                    return 1;
            }
            return 0;
        }
        else if (substr(p,1,1) != substr(s,1,1)) {  # chars different
            return 0;
        }
        else {                      # search next char
            s = substr(s, 2);
            p = substr(p, 2);
        }
    }
}

BEGIN {
    print match_pattern(ARGV[1], ARGV[2]);
    exit 0;
}