aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAbigail <abigail@abigail.be>2021-01-12 14:17:16 +0100
committerAbigail <abigail@abigail.be>2021-01-12 16:00:45 +0100
commitb24494336813d32e997c11c01b7f6a65e7156c76 (patch)
treefc39f0b4b0e2a46626364c1ade4f0f712743939a
parentbf10a659e60a77df908278b48c949f31f01cdb68 (diff)
downloadperlweeklychallenge-club-b24494336813d32e997c11c01b7f6a65e7156c76.tar.gz
perlweeklychallenge-club-b24494336813d32e997c11c01b7f6a65e7156c76.tar.bz2
perlweeklychallenge-club-b24494336813d32e997c11c01b7f6a65e7156c76.zip
AWK solution for week 95/part 2
-rw-r--r--challenge-095/abigail/README.md2
-rw-r--r--challenge-095/abigail/awk/ch-2.awk49
2 files changed, 51 insertions, 0 deletions
diff --git a/challenge-095/abigail/README.md b/challenge-095/abigail/README.md
index 41d284a063..24ed0ef1dc 100644
--- a/challenge-095/abigail/README.md
+++ b/challenge-095/abigail/README.md
@@ -20,6 +20,7 @@ Output: 0
~~~~
### Solutions
+* [awk](awk/ch-1.c)
* [C](c/ch-1.c)
* [Node](node/ch-1.js)
* [Perl](perl/ch-1.pl)
@@ -47,6 +48,7 @@ print $stack->min; # prints -1
~~~~
### Solutions
+* [awk](awk/ch-2.awk)
* [C](c/ch-2.c)
* [Node](node/ch-2.js)
* [Perl](perl/ch-2.pl)
diff --git a/challenge-095/abigail/awk/ch-2.awk b/challenge-095/abigail/awk/ch-2.awk
new file mode 100644
index 0000000000..d407cc7e74
--- /dev/null
+++ b/challenge-095/abigail/awk/ch-2.awk
@@ -0,0 +1,49 @@
+BEGIN {
+ size = 0
+ error = "Stack is empty"
+}
+
+/^push/ {
+ #
+ # Push the argument on the stack. We use split to retrieve
+ # the argument. split() puts the various parts into its
+ # second argument -- an array. Note that arrays are indexed 1-based.
+ #
+ split($0, a, / +/)
+ stack [size += 1] = a [2]
+}
+
+/^pop/ {
+ #
+ # Popping just means reducing the size of the stack by 1.
+ # Don't let it go below 0.
+ #
+ size = size ? size - 1 : 0
+}
+
+/^top/ {
+ #
+ # Print the top of the stack, or an error if the stack is empty.
+ #
+ print size ? stack [size] : error
+}
+
+/^min/ {
+ #
+ # Find the minimum number in the stack, which we find by iterating
+ # over the array which represents the stack. If the stack is
+ # empty, we print an error message.
+ #
+ if (size) {
+ min = stack [1]
+ for (i = 2; i <= size; i ++) {
+ if (min > stack [i]) {
+ min = stack [i]
+ }
+ }
+ print min
+ }
+ else {
+ print error
+ }
+}