aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAbigail <abigail@abigail.be>2021-02-05 02:04:24 +0100
committerAbigail <abigail@abigail.be>2021-02-05 18:39:26 +0100
commit9ad3b511c7ff826bfeeb646f356bb17df7e50957 (patch)
tree4e6d36c04a4bae06390cf3d2ca3d7c6faa29faa8
parent686952c9bef6e28629e4b31365aa3bc4e1b8e3d0 (diff)
downloadperlweeklychallenge-club-9ad3b511c7ff826bfeeb646f356bb17df7e50957.tar.gz
perlweeklychallenge-club-9ad3b511c7ff826bfeeb646f356bb17df7e50957.tar.bz2
perlweeklychallenge-club-9ad3b511c7ff826bfeeb646f356bb17df7e50957.zip
Bash solution for week 98, part 2
-rw-r--r--challenge-098/abigail/README.md1
-rw-r--r--challenge-098/abigail/bash/ch-2.sh53
2 files changed, 54 insertions, 0 deletions
diff --git a/challenge-098/abigail/README.md b/challenge-098/abigail/README.md
index d550cdd363..3b8c4e5800 100644
--- a/challenge-098/abigail/README.md
+++ b/challenge-098/abigail/README.md
@@ -103,6 +103,7 @@ anyway).
### Solutions
+* [Bash](bash/ch-2.sh)
* [Perl](perl/ch-2.pl)
### Blog
diff --git a/challenge-098/abigail/bash/ch-2.sh b/challenge-098/abigail/bash/ch-2.sh
new file mode 100644
index 0000000000..2a6158d1db
--- /dev/null
+++ b/challenge-098/abigail/bash/ch-2.sh
@@ -0,0 +1,53 @@
+#!/bin/sh
+
+#
+# See ../README.md
+#
+
+#
+# Run as: perl ch-2.sh < input-file
+#
+# Each line is a challenge: first number is the target number;
+# the rest of the line is the array to search in.
+#
+
+set -f
+
+while read -a numbers
+do target=${numbers[0]}
+ #
+ # Try to find the target, counting from 1
+ #
+ found=-1
+ for ((i = 1; i < ${#numbers[@]}; i ++))
+ do if (($target == ${numbers[$i]}))
+ then found=$((i - 1))
+ break
+ fi
+ done
+ #
+ # If found, report the position and go to the next line
+ #
+ if (($found >= 0))
+ then echo $found
+ continue
+ fi
+
+ #
+ # Create a new array, by sorting numbers
+ #
+ IFS=$'\n'
+ numbers=($(sort -n <<< "${numbers[*]}"))
+ unset IFS
+
+ #
+ # Search for the target again
+ #
+ for ((i = 0; i < ${#numbers[@]}; i ++))
+ do if (($target == ${numbers[$i]}))
+ then found=$i
+ break
+ fi
+ done
+ echo $found
+done