aboutsummaryrefslogtreecommitdiff
path: root/challenge-002/abigail/awk
diff options
context:
space:
mode:
authorDave Jacoby <jacoby.david@gmail.com>2021-01-26 16:13:59 -0500
committerDave Jacoby <jacoby.david@gmail.com>2021-01-26 16:13:59 -0500
commit1ed6ac427cbce65a68f7f5704fa33bf892f1c1fd (patch)
treed2aa0002dd04845071ea4454d9520b474b960de3 /challenge-002/abigail/awk
parent3c7bc8e0bb03a8177808ef3223099f2e0fc07416 (diff)
parentc34bb5d7bd7fce08e8311a0f527ce7fbd69e4dae (diff)
downloadperlweeklychallenge-club-1ed6ac427cbce65a68f7f5704fa33bf892f1c1fd.tar.gz
perlweeklychallenge-club-1ed6ac427cbce65a68f7f5704fa33bf892f1c1fd.tar.bz2
perlweeklychallenge-club-1ed6ac427cbce65a68f7f5704fa33bf892f1c1fd.zip
Merge branch 'master' of https://github.com/manwar/perlweeklychallenge-club into master
Diffstat (limited to 'challenge-002/abigail/awk')
-rw-r--r--challenge-002/abigail/awk/ch-1.awk1
-rw-r--r--challenge-002/abigail/awk/ch-2.awk80
2 files changed, 81 insertions, 0 deletions
diff --git a/challenge-002/abigail/awk/ch-1.awk b/challenge-002/abigail/awk/ch-1.awk
new file mode 100644
index 0000000000..6f2ef2064c
--- /dev/null
+++ b/challenge-002/abigail/awk/ch-1.awk
@@ -0,0 +1 @@
+{print 0 + $1}
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
+}