diff options
| author | Abigail <abigail@abigail.be> | 2021-02-10 17:33:35 +0100 |
|---|---|---|
| committer | Abigail <abigail@abigail.be> | 2021-02-10 17:33:35 +0100 |
| commit | 110486b7d7c624bfd545b66a130a18325f1e149d (patch) | |
| tree | 29fe9a267e4db6253e3b8d200a9d74f998d13d39 /challenge-099/abigail/awk | |
| parent | 8360d023321f62c8c39a844398c649a6d08ada42 (diff) | |
| download | perlweeklychallenge-club-110486b7d7c624bfd545b66a130a18325f1e149d.tar.gz perlweeklychallenge-club-110486b7d7c624bfd545b66a130a18325f1e149d.tar.bz2 perlweeklychallenge-club-110486b7d7c624bfd545b66a130a18325f1e149d.zip | |
AWK solution for week 99, part 2
Diffstat (limited to 'challenge-099/abigail/awk')
| -rw-r--r-- | challenge-099/abigail/awk/ch-2.awk | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/challenge-099/abigail/awk/ch-2.awk b/challenge-099/abigail/awk/ch-2.awk new file mode 100644 index 0000000000..d88806279e --- /dev/null +++ b/challenge-099/abigail/awk/ch-2.awk @@ -0,0 +1,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 +} |
