diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2021-01-26 15:48:31 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-01-26 15:48:31 +0000 |
| commit | b4d2998acaab110134b17acacedca0645cc011d4 (patch) | |
| tree | 66741a6d0ae8b19611b4b9f6be1e470de7e85af7 /challenge-002/abigail/awk/ch-2.awk | |
| parent | 224ce57074c8183cb687c8395897eb03e0230ce3 (diff) | |
| parent | 9aeed56c942517679d2e97deea955c6f72abd70a (diff) | |
| download | perlweeklychallenge-club-b4d2998acaab110134b17acacedca0645cc011d4.tar.gz perlweeklychallenge-club-b4d2998acaab110134b17acacedca0645cc011d4.tar.bz2 perlweeklychallenge-club-b4d2998acaab110134b17acacedca0645cc011d4.zip | |
Merge pull request #3378 from Abigail/abigail/week-002
Abigail/week 002
Diffstat (limited to 'challenge-002/abigail/awk/ch-2.awk')
| -rw-r--r-- | challenge-002/abigail/awk/ch-2.awk | 80 |
1 files changed, 80 insertions, 0 deletions
diff --git a/challenge-002/abigail/awk/ch-2.awk b/challenge-002/abigail/awk/ch-2.awk new file mode 100644 index 0000000000..b171fcd08f --- /dev/null +++ b/challenge-002/abigail/awk/ch-2.awk @@ -0,0 +1,80 @@ +#!/usr/bin/awk +# +# See ../README.md +# + +# +# Run as: awk -f ch-2.awk {-f | -t} < input-file +# +# -f: Translate from base 35 to base 10 +# -t: Translate to base 35 from base 10 +# + +BEGIN { + # + # Parse command line + # + from_base = 0; + to_base = 0; + for (i = 0; i < ARGC; i ++) { + if (ARGV [i] == "-f") { + from_base = 1 + } + if (ARGV [i] == "-t") { + to_base = 1 + } + } + ARGC = 0 # Prevent AWK to process the parameters. + + # + # Map base-35 digits to base-10 numbers, and back + # + BASE = 35 + for (i = 0; i < 10; i ++) { + digits [i] = i + } + for (i = 10; i < BASE; i ++) { + char = sprintf("%c", 65 + i - 10) + digits [i] = char + digits [char] = i + } +} + +# +# This is only executed if the -t option is used +# +to_base { + # + # Translate the input number from base 10 to base BASE, + # using a standard mod and divide approach. + # + number = $0 + out = "" + while (number > 0) { + digit = number % BASE + out = digits [digit] out + number = int(number / BASE) + } +} + +# +# This is only executed if the -f option is used +# +from_base { + # + # Translate the input number from base BASE to base 10, + # using a standard multiply and add approach. + # + out = 0 + n = split ($0, d, "") + for (i = 1; i <= n; i ++) { + out = BASE * out + digits [d [i]] + } +} + +# +# Always executed +# +{ + print out +} |
