aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAbigail <abigail@abigail.be>2021-05-25 19:52:26 +0200
committerAbigail <abigail@abigail.be>2021-05-25 19:52:26 +0200
commit42fee0cd8e2eb6639761d5bd258267ad75490c16 (patch)
treefc58e54b9b44f4007457f2e9d828d597810039af
parent91985f9df2122f8896cd9758889abe35956f62ac (diff)
downloadperlweeklychallenge-club-42fee0cd8e2eb6639761d5bd258267ad75490c16.tar.gz
perlweeklychallenge-club-42fee0cd8e2eb6639761d5bd258267ad75490c16.tar.bz2
perlweeklychallenge-club-42fee0cd8e2eb6639761d5bd258267ad75490c16.zip
AWK solution for week 114, part 2
-rw-r--r--challenge-114/abigail/README.md1
-rw-r--r--challenge-114/abigail/awk/ch-2.gawk47
2 files changed, 48 insertions, 0 deletions
diff --git a/challenge-114/abigail/README.md b/challenge-114/abigail/README.md
index 6d6da56bb8..399c8978c5 100644
--- a/challenge-114/abigail/README.md
+++ b/challenge-114/abigail/README.md
@@ -46,6 +46,7 @@ Binary representation of `$N` is `1100`. There are two `1` bits. So the next
higher integer is `17` having the same number of `1` bits i.e. `10001`.
### Solutions
+* [GNU AWK](awk/ch-2.gawk)
* [Perl](perl/ch-2.pl)
### Blog
diff --git a/challenge-114/abigail/awk/ch-2.gawk b/challenge-114/abigail/awk/ch-2.gawk
new file mode 100644
index 0000000000..49c2ef960f
--- /dev/null
+++ b/challenge-114/abigail/awk/ch-2.gawk
@@ -0,0 +1,47 @@
+#!/usr/bin/awk
+
+#
+# See ../README.md
+#
+
+#
+# Run as: gawk -f ch-2.gawk < input-file
+#
+
+#
+# Take a number, and return a binary representation
+#
+function d2b (d, b) {
+ b = ""
+ while (d > 0) {
+ b = d % 2 b
+ d = int (d / 2)
+ }
+ return (b)
+}
+
+#
+# Take a binary representation of a number, return that number.
+#
+function b2d (b, d, i) {
+ d = 0
+ i = 0
+ while (length (b) > 0) {
+ if (substr (b, length (b), 1) == "1") {
+ d += 2 ^ i
+ }
+ i ++
+ b = substr (b, 1, length (b) - 1)
+ }
+ return (d)
+}
+
+
+{
+ #
+ # Take a number, turn it into a binary representation (d2b), prepend a 0.
+ # Replace the last 01 with 10, and swap trailing sequence of 1s and 0s.
+ # Turn this back into a decimal representation, and print it.
+ #
+ print (b2d(gensub (/^(.*)01(1*)(0*)$/, "\\110\\3\\2", 1, 0 d2b($1))))
+}